The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Load the chat list through the record API (#26957)
Félix Malfait6b8fc1888d09
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex f9a02a13a06..8ae336e1ca0 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3449,7 +3449,6 @@ type AgentChatThread {createdAt: DateTime!updatedAt: DateTime!deletedAt: DateTime- lastMessageAt: DateTime}type AiSystemPromptSection {@@ -3926,7 +3925,6 @@ type Query {appConnection(id: ID!): AppConnection!findWorkspaceAiStats: WorkspaceAiStats!aiChatUsage: AiChatUsage- chatThreads: [AgentChatThread!]!chatThread(id: UUID!): AgentChatThread!chatMessages(threadId: UUID!): [AgentMessage!]!chatStreamCatchupChunks(threadId: UUID!): ChatStreamCatchupChunks!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex de4990f322e..57c56e2f50a 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3029,7 +3029,6 @@ export interface AgentChatThread {createdAt: Scalars['DateTime']updatedAt: Scalars['DateTime']deletedAt?: Scalars['DateTime']- lastMessageAt?: Scalars['DateTime']__typename: 'AgentChatThread'}@@ -3446,7 +3445,6 @@ export interface Query {appConnection: AppConnectionfindWorkspaceAiStats: WorkspaceAiStatsaiChatUsage?: AiChatUsage- chatThreads: AgentChatThread[]chatThread: AgentChatThreadchatMessages: AgentMessage[]chatStreamCatchupChunks: ChatStreamCatchupChunks@@ -6935,7 +6933,6 @@ export interface AgentChatThreadGenqlSelection{createdAt?: boolean | numberupdatedAt?: boolean | numberdeletedAt?: boolean | number- lastMessageAt?: boolean | number__typename?: boolean | number__scalar?: boolean | number}@@ -7375,7 +7372,6 @@ export interface QueryGenqlSelection{appConnection?: (AppConnectionGenqlSelection & { __args: {id: Scalars['ID']} })findWorkspaceAiStats?: WorkspaceAiStatsGenqlSelectionaiChatUsage?: AiChatUsageGenqlSelection- chatThreads?: AgentChatThreadGenqlSelectionchatThread?: (AgentChatThreadGenqlSelection & { __args: {id: Scalars['UUID']} })chatMessages?: (AgentMessageGenqlSelection & { __args: {threadId: Scalars['UUID']} })chatStreamCatchupChunks?: (ChatStreamCatchupChunksGenqlSelection & { __args: {threadId: Scalars['UUID']} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex e86daaeada3..4e0adb4ebf6 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -6814,9 +6814,6 @@ export default {"deletedAt": [4],- "lastMessageAt": [- 4- ],"__typename": [1]@@ -8209,9 +8206,6 @@ export default {"aiChatUsage": [374],- "chatThreads": [- 376- ],"chatThread": [376,{diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 25ea01fd0de..f5918ba085a 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -71,7 +71,6 @@ export type AgentChatThread = {createdAt: Scalars['DateTime']['output'];deletedAt?: Maybe<Scalars['DateTime']['output']>;id: Scalars['ID']['output'];- lastMessageAt?: Maybe<Scalars['DateTime']['output']>;title?: Maybe<Scalars['String']['output']>;totalCacheReadTokens: Scalars['Int']['output'];totalInputCredits: Scalars['Float']['output'];@@ -5198,7 +5197,6 @@ export type Query = {chatMessages: Array<AgentMessage>;chatStreamCatchupChunks: ChatStreamCatchupChunks;chatThread: AgentChatThread;- chatThreads: Array<AgentChatThread>;checkUserExists: CheckUserExist;checkWorkspaceInviteHashIsValid: WorkspaceInviteHashValid;checkWorkspaceSubdomainAvailability: SubdomainAvailabilityDto;@@ -7893,7 +7891,7 @@ export type FindManyTimelineActivityTypesQueryVariables = Exact<{ [key: string]:export type FindManyTimelineActivityTypesQuery = { __typename?: 'Query', timelineActivityTypes: Array<{ __typename?: 'TimelineActivityType', id: string, applicationId?: string | null, universalIdentifier: string, name: string, label: string, icon?: string | null, frontComponentUniversalIdentifier?: string | null, isActive: boolean, emit?: { __typename?: 'TimelineActivityTypeEmit', on: string, objectUniversalIdentifier?: string | null } | null }> };-export type AgentChatThreadFieldsFragment = { __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string };+export type AgentChatThreadFieldsFragment = { __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, createdAt: string, updatedAt: string };export type AgentFieldsFragment = { __typename?: 'Agent', id: string, name: string, label: string, description?: string | null, icon?: string | null, prompt: string, modelId: string, responseFormat?: any | null, roleId?: string | null, isCustom: boolean, modelConfiguration?: any | null, evaluationInputs: Array<string>, applicationId?: string | null, createdAt: string, updatedAt: string };@@ -8077,11 +8075,6 @@ export type GetChatMessagesQueryVariables = Exact<{export type GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{ __typename?: 'AgentMessage', id: string, threadId: string, turnId?: string | null, senderUserWorkspaceId?: string | null, role: string, status: string, createdAt: string, parts: Array<{ __typename?: 'AgentMessagePart', id: string, messageId: string, orderIndex: number, type: string, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, state?: string | null, providerExecuted?: boolean | null, errorMessage?: string | null, errorDetails?: any | null, sourceUrlSourceId?: string | null, sourceUrlUrl?: string | null, sourceUrlTitle?: string | null, sourceDocumentSourceId?: string | null, sourceDocumentMediaType?: string | null, sourceDocumentTitle?: string | null, sourceDocumentFilename?: string | null, fileMediaType?: string | null, fileFilename?: string | null, fileUrl?: string | null, fileId?: string | null, providerMetadata?: any | null, createdAt: string }> }>, chatStreamCatchupChunks: { __typename?: 'ChatStreamCatchupChunks', chunks: Array<any>, maxSeq: number, error?: { __typename?: 'ChatStreamError', code: string, message: string } | null } };-export type GetChatThreadsQueryVariables = Exact<{ [key: string]: never; }>;---export type GetChatThreadsQuery = { __typename?: 'Query', chatThreads: Array<{ __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string }> };-export type GetToolIndexQueryVariables = Exact<{ [key: string]: never; }>;@@ -8959,7 +8952,7 @@ export type StartWorkspaceSetupChatMutationVariables = Exact<{}>;-export type StartWorkspaceSetupChatMutation = { __typename?: 'Mutation', startWorkspaceSetupChat: { __typename?: 'StartWorkspaceSetupChatResult', outcome: WorkspaceSetupChatOutcome, thread?: { __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, lastMessageAt?: string | null, createdAt: string, updatedAt: string } | null } };+export type StartWorkspaceSetupChatMutation = { __typename?: 'Mutation', startWorkspaceSetupChat: { __typename?: 'StartWorkspaceSetupChatResult', outcome: WorkspaceSetupChatOutcome, thread?: { __typename?: 'AgentChatThread', id: string, title?: string | null, totalCacheReadTokens: number, totalInputTokens: number, totalOutputTokens: number, contextWindowTokens?: number | null, conversationSize: number, totalInputCredits: number, totalOutputCredits: number, deletedAt?: string | null, createdAt: string, updatedAt: string } | null } };export type TriggerInstallAppsOnboardingStepMutationVariables = Exact<{universalIdentifiers: Array<Scalars['String']['input']> | Scalars['String']['input'];@@ -10455,7 +10448,7 @@ export type FindManyMarketplaceAppsForToolTableQueryVariables = Exact<{ [key: stexport type FindManyMarketplaceAppsForToolTableQuery = { __typename?: 'Query', findManyMarketplaceApps: Array<{ __typename?: 'MarketplaceApp', id: string, logoUrl?: string | null }> };-export const AgentChatThreadFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<AgentChatThreadFieldsFragment, unknown>;+export const AgentChatThreadFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"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<AgentChatThreadFieldsFragment, unknown>;export const SkillFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SkillFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Skill"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"content"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SkillFieldsFragment, unknown>;export const AgentFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Agent"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"prompt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"responseFormat"}},{"kind":"Field","name":{"kind":"Name","value":"roleId"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"modelConfiguration"}},{"kind":"Field","name":{"kind":"Name","value":"evaluationInputs"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<AgentFieldsFragment, unknown>;export const ObjectMetadataFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"ObjectMetadataFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"Object"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}},{"kind":"Field","name":{"kind":"Name","value":"labelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"labelPlural"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isRemote"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}},{"kind":"Field","name":{"kind":"Name","value":"isUICreatable"}},{"kind":"Field","name":{"kind":"Name","value":"writability"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"labelIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"imageIdentifierFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"shortcut"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"isSearchable"}},{"kind":"Field","name":{"kind":"Name","value":"openRecordIn"}},{"kind":"Field","name":{"kind":"Name","value":"duplicateCriteria"}},{"kind":"Field","name":{"kind":"Name","value":"searchFieldMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"tsVectorFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"indexMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"indexWhereClause"}},{"kind":"Field","name":{"kind":"Name","value":"indexType"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"isCustom"}},{"kind":"Field","name":{"kind":"Name","value":"indexFieldMetadataList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"subFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"order"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"fieldsList"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"isSystem"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}},{"kind":"Field","name":{"kind":"Name","value":"writability"}},{"kind":"Field","name":{"kind":"Name","value":"isNullable"}},{"kind":"Field","name":{"kind":"Name","value":"isUnique"}},{"kind":"Field","name":{"kind":"Name","value":"isSearchable"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"defaultValue"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"settings"}},{"kind":"Field","name":{"kind":"Name","value":"isLabelSyncedWithName"}},{"kind":"Field","name":{"kind":"Name","value":"morphId"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"relation"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"morphRelations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"sourceObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetObjectMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"nameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"namePlural"}}]}},{"kind":"Field","name":{"kind":"Name","value":"sourceFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}},{"kind":"Field","name":{"kind":"Name","value":"targetFieldMetadata"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]}}]}}]} as unknown as DocumentNode<ObjectMetadataFieldsFragment, unknown>;@@ -10540,7 +10533,6 @@ export const FindWorkspaceAiStatsDocument = {"kind":"Document","definitions":[{"export const GetAgentTurnsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAgentTurns"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"agentTurns"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"agentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"evaluations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"score"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"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":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"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":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"providerExecuted"}},{"kind":"Field","name":{"kind":"Name","value":"errorDetails"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"fileFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileUrl"}},{"kind":"Field","name":{"kind":"Name","value":"providerMetadata"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetAgentTurnsQuery, GetAgentTurnsQueryVariables>;export const GetAiChatUsageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAiChatUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"aiChatUsage"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"limitValue"}},{"kind":"Field","name":{"kind":"Name","value":"consumedValue"}},{"kind":"Field","name":{"kind":"Name","value":"periodEnd"}},{"kind":"Field","name":{"kind":"Name","value":"kind"}}]}}]}}]} as unknown as DocumentNode<GetAiChatUsageQuery, GetAiChatUsageQueryVariables>;export const GetChatMessagesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChatMessages"},"variableDefinitions":[{"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":"chatMessages"},"arguments":[{"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":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"turnId"}},{"kind":"Field","name":{"kind":"Name","value":"senderUserWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"orderIndex"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"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":"providerExecuted"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"errorDetails"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlUrl"}},{"kind":"Field","name":{"kind":"Name","value":"sourceUrlTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentSourceId"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentTitle"}},{"kind":"Field","name":{"kind":"Name","value":"sourceDocumentFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileMediaType"}},{"kind":"Field","name":{"kind":"Name","value":"fileFilename"}},{"kind":"Field","name":{"kind":"Name","value":"fileUrl"}},{"kind":"Field","name":{"kind":"Name","value":"fileId"}},{"kind":"Field","name":{"kind":"Name","value":"providerMetadata"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"chatStreamCatchupChunks"},"arguments":[{"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":"chunks"}},{"kind":"Field","name":{"kind":"Name","value":"maxSeq"}},{"kind":"Field","name":{"kind":"Name","value":"error"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"code"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]}}]} as unknown as DocumentNode<GetChatMessagesQuery, GetChatMessagesQueryVariables>;-export const GetChatThreadsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetChatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"chatThreads"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThread"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<GetChatThreadsQuery, GetChatThreadsQueryVariables>;export const GetToolIndexDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetToolIndex"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getToolIndex"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"category"}},{"kind":"Field","name":{"kind":"Name","value":"objectName"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"widgetName"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}}]}}]}}]} as unknown as DocumentNode<GetToolIndexQuery, GetToolIndexQueryVariables>;export const GetToolInputSchemaDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetToolInputSchema"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getToolInputSchema"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"toolName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"toolName"}}}]}]}}]} as unknown as DocumentNode<GetToolInputSchemaQuery, GetToolInputSchemaQueryVariables>;export const OnAgentChatEventDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"OnAgentChatEvent"},"variableDefinitions":[{"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":"onAgentChatEvent"},"arguments":[{"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":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"event"}}]}}]}}]} as unknown as DocumentNode<OnAgentChatEventSubscription, OnAgentChatEventSubscriptionVariables>;@@ -10642,7 +10634,7 @@ export const CompleteBookCallOnboardingStepDocument = {"kind":"Document","definiexport const EnrichWorkspaceCompanyDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EnrichWorkspaceCompany"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"enrichWorkspaceCompany"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"kind":"Field","name":{"kind":"Name","value":"enrichment"}},{"kind":"Field","name":{"kind":"Name","value":"personOutcome"}},{"kind":"Field","name":{"kind":"Name","value":"personEnrichment"}},{"kind":"Field","name":{"kind":"Name","value":"isBookCallOnboardingStepPending"}}]}}]}}]} as unknown as DocumentNode<EnrichWorkspaceCompanyMutation, EnrichWorkspaceCompanyMutationVariables>;export const GoBackToPreviousOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GoBackToPreviousOnboardingStep"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"goBackToPreviousOnboardingStep"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"onboardingStatus"}},{"kind":"Field","name":{"kind":"Name","value":"previousOnboardingStatus"}}]}}]}}]} as unknown as DocumentNode<GoBackToPreviousOnboardingStepMutation, GoBackToPreviousOnboardingStepMutationVariables>;export const SkipSyncEmailOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SkipSyncEmailOnboardingStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"skipSyncEmailOnboardingStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"isAutoSkipped"},"value":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<SkipSyncEmailOnboardingStepMutation, SkipSyncEmailOnboardingStepMutationVariables>;-export const StartWorkspaceSetupChatDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StartWorkspaceSetupChat"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"startWorkspaceSetupChat"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"companyContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}}},{"kind":"Argument","name":{"kind":"Name","value":"personContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"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":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"lastMessageAt"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]}}]} as unknown as DocumentNode<StartWorkspaceSetupChatMutation, StartWorkspaceSetupChatMutationVariables>;+export const StartWorkspaceSetupChatDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StartWorkspaceSetupChat"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"startWorkspaceSetupChat"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"companyContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"companyContext"}}},{"kind":"Argument","name":{"kind":"Name","value":"personContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"personContext"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"outcome"}},{"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":"totalCacheReadTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"contextWindowTokens"}},{"kind":"Field","name":{"kind":"Name","value":"conversationSize"}},{"kind":"Field","name":{"kind":"Name","value":"totalInputCredits"}},{"kind":"Field","name":{"kind":"Name","value":"totalOutputCredits"}},{"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<StartWorkspaceSetupChatMutation, StartWorkspaceSetupChatMutationVariables>;export const TriggerInstallAppsOnboardingStepDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"TriggerInstallAppsOnboardingStep"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}},"type":{"kind":"NonNullType","type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"triggerInstallAppsOnboardingStep"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"universalIdentifiers"},"value":{"kind":"Variable","name":{"kind":"Name","value":"universalIdentifiers"}}},{"kind":"Argument","name":{"kind":"Name","value":"isAutoSkipped"},"value":{"kind":"Variable","name":{"kind":"Name","value":"isAutoSkipped"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<TriggerInstallAppsOnboardingStepMutation, TriggerInstallAppsOnboardingStepMutationVariables>;export const GetInviteSuggestionsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetInviteSuggestions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getInviteSuggestions"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}}]}}]}}]} as unknown as DocumentNode<GetInviteSuggestionsQuery, GetInviteSuggestionsQueryVariables>;export const ResetPageLayoutTabToDefaultDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ResetPageLayoutTabToDefault"},"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":"resetPageLayoutTabToDefault"},"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":"PageLayoutTabFragment"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutWidgetFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidget"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"deletedAt"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"conditionalAvailabilityExpression"}},{"kind":"Field","name":{"kind":"Name","value":"gridPosition"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}}]}},{"kind":"Field","name":{"kind":"Name","value":"position"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetGridPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"row"}},{"kind":"Field","name":{"kind":"Name","value":"column"}},{"kind":"Field","name":{"kind":"Name","value":"rowSpan"}},{"kind":"Field","name":{"kind":"Name","value":"columnSpan"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetVerticalListPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"index"}},{"kind":"Field","name":{"kind":"Name","value":"heightBehavior"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutWidgetCanvasPosition"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"configuration"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"BarChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"groupMode"}},{"kind":"Field","name":{"kind":"Name","value":"layout"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"LineChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"primaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisGroupByDateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisOrderBy"}},{"kind":"Field","name":{"kind":"Name","value":"secondaryAxisManualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"omitNullValues"}},{"kind":"Field","name":{"kind":"Name","value":"axisNameDisplay"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMin"}},{"kind":"Field","name":{"kind":"Name","value":"rangeMax"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"isStacked"}},{"kind":"Field","name":{"kind":"Name","value":"isCumulative"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PieChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"groupByFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"groupBySubFieldName"}},{"kind":"Field","name":{"kind":"Name","value":"dateGranularity"}},{"kind":"Field","name":{"kind":"Name","value":"orderBy"}},{"kind":"Field","name":{"kind":"Name","value":"manualSortOrder"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"showCenterMetric"}},{"kind":"Field","name":{"kind":"Name","value":"displayLegend"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"hideEmptyCategory"}},{"kind":"Field","name":{"kind":"Name","value":"splitMultiValueFields"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AggregateChartConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"aggregateOperation"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"displayDataLabel"}},{"kind":"Field","name":{"kind":"Name","value":"numberFormat"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"filter"}},{"kind":"Field","name":{"kind":"Name","value":"prefix"}},{"kind":"Field","name":{"kind":"Name","value":"suffix"}},{"kind":"Field","name":{"kind":"Name","value":"timezone"}},{"kind":"Field","name":{"kind":"Name","value":"firstDayOfTheWeek"}},{"kind":"Field","name":{"kind":"Name","value":"ratioAggregateConfig"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"optionValue"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"IframeConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"url"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"StandaloneRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"body"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"blocknote"}},{"kind":"Field","name":{"kind":"Name","value":"markdown"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CalendarConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"EmailThreadConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingSummaryConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"CallRecordingTranscriptConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ChatThreadsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignBodyConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"MessageCampaignDetailsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldDisplayMode"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"nestedRelationFieldMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldRichTextConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FieldsConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"newFieldDefaultVisibility"}},{"kind":"Field","name":{"kind":"Name","value":"shouldAllowUserToSeeHiddenFields"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FormFieldConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"fieldMetadataId"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FilesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"NotesConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TasksConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"TimelineConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"ViewConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"RecordTableConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"viewId"}},{"kind":"Field","name":{"kind":"Name","value":"recordLimit"}},{"kind":"Field","name":{"kind":"Name","value":"isUIEditable"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowRunConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkflowVersionConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"FrontComponentConfiguration"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"configurationType"}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentId"}},{"kind":"Field","name":{"kind":"Name","value":"headerCommandMenuItemUniversalIdentifiers"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutTabId"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"PageLayoutTabFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"PageLayoutTab"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"applicationId"}},{"kind":"Field","name":{"kind":"Name","value":"universalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isSystemSideEffect"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"position"}},{"kind":"Field","name":{"kind":"Name","value":"layoutMode"}},{"kind":"Field","name":{"kind":"Name","value":"widgets"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"PageLayoutWidgetFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageLayoutId"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ResetPageLayoutTabToDefaultMutation, ResetPageLayoutTabToDefaultMutationVariables>;diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsxindex eee03723b86..eafbcca9950 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInitializationEffect.tsx@@ -1,4 +1,4 @@-import { useAtomValue, useStore } from 'jotai';+import { useStore } from 'jotai';import { useEffect } from 'react';import {isDefined,@@ -13,30 +13,45 @@ import {agentChatDraftsByThreadIdState,} from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';import { agentChatThreadsLoadingState } from '@/ai/states/agentChatThreadsLoadingState';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';import { hasInitializedAgentChatThreadsState } from '@/ai/states/hasInitializedAgentChatThreadsState';import { hasTriggeredCreateForDraftState } from '@/ai/states/hasTriggeredCreateForDraftState';import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { metadataStoreStatusFamilySelector } from '@/metadata-store/states/metadataStoreStatusFamilySelector';+import { useIsWorkspaceActivationStatusEqualsTo } from '@/workspace/hooks/useIsWorkspaceActivationStatusEqualsTo';+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';import { useHasPermissionFlag } from '@/settings/roles/hooks/useHasPermissionFlag';+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';-import {- type AgentChatThread,- PermissionFlagType,-} from '~/generated-metadata/graphql';+import { PermissionFlagType } from '~/generated-metadata/graphql';const AGENT_CHAT_THREADS_REFRESH_RETRY_DELAY_MS = 3000;export const AgentChatThreadInitializationEffect = () => {const { refreshAgentChatThreads } = useRefreshAgentChatThreads();const hasAiPermission = useHasPermissionFlag(PermissionFlagType.AI);+ // Chats are read through the record API, whose query is built from the+ // chat object's fields+ const areFieldMetadataItemsLoaded =+ useAtomFamilySelectorValue(+ metadataStoreStatusFamilySelector,+ 'fieldMetadataItems',+ ) === 'up-to-date';++ // The record API refuses a suspended workspace+ const isWorkspaceSuspended = useIsWorkspaceActivationStatusEqualsTo(+ WorkspaceActivationStatus.SUSPENDED,+ );+ const canLoadAgentChatThreads = hasAiPermission && !isWorkspaceSuspended;const currentAiChatThread = useAtomStateValue(currentAiChatThreadState);const setCurrentAiChatThread = useSetAtomState(currentAiChatThreadState);@@ -54,14 +69,18 @@ export const AgentChatThreadInitializationEffect = () => {const agentChatVisibleThreads = useAtomStateValue(agentChatVisibleThreadsSelector,);- const storeEntry = useAtomValue(- metadataStoreState.atomFamily('agentChatThreads'),- );+ const agentChatThreadList = useAtomStateValue(agentChatThreadListState);+ const agentChatThreads = useAtomStateValue(agentChatThreadsSelector);+ const areAgentChatThreadsLoaded = agentChatThreadList !== null;const [hasInitializedAgentChatThreads, setHasInitializedAgentChatThreads] =useAtomState(hasInitializedAgentChatThreadsState);useEffect(() => {- if (storeEntry.status !== 'empty' || !hasAiPermission) {+ if (+ areAgentChatThreadsLoaded ||+ !canLoadAgentChatThreads ||+ !areFieldMetadataItemsLoaded+ ) {return;}@@ -90,24 +109,33 @@ export const AgentChatThreadInitializationEffect = () => {window.clearTimeout(retryTimeoutId);}};- }, [storeEntry.status, hasAiPermission, refreshAgentChatThreads]);+ }, [+ areAgentChatThreadsLoaded,+ areFieldMetadataItemsLoaded,+ canLoadAgentChatThreads,+ refreshAgentChatThreads,+ ]);useEffect(() => {setAgentChatThreadsLoading(- storeEntry.status === 'empty' && hasAiPermission,+ !areAgentChatThreadsLoaded && canLoadAgentChatThreads,);- }, [storeEntry.status, hasAiPermission, setAgentChatThreadsLoading]);+ }, [+ areAgentChatThreadsLoaded,+ canLoadAgentChatThreads,+ setAgentChatThreadsLoading,+ ]);useEffect(() => {if (hasInitializedAgentChatThreads ||- (storeEntry.status === 'empty' && hasAiPermission)+ (!areAgentChatThreadsLoaded && canLoadAgentChatThreads)) {return;}if (isDefined(currentAiChatThread) && isValidUuid(currentAiChatThread)) {- const selectedThread = (storeEntry.current as AgentChatThread[]).find(+ const selectedThread = agentChatThreads.find(({ id }) => id === currentAiChatThread,);if (isDefined(selectedThread)) {@@ -159,11 +187,11 @@ export const AgentChatThreadInitializationEffect = () => {}, [agentChatVisibleThreads,currentAiChatThread,- hasAiPermission,+ canLoadAgentChatThreads,hasInitializedAgentChatThreads,setHasInitializedAgentChatThreads,- storeEntry.status,- storeEntry.current,+ areAgentChatThreadsLoaded,+ agentChatThreads,setCurrentAiChatThread,setAgentChatInput,store,diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsxindex dca86e19b68..2610bf3236e 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadRecordOperationsEffect.tsx@@ -1,3 +1,4 @@+import { useStore } from 'jotai';import { useCallback } from 'react';import { CoreObjectNameSingular } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';@@ -5,42 +6,30 @@ import { isDefined } from 'twenty-shared/utils';import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';import { useLeaveRemovedAiChatThread } from '@/ai/hooks/useLeaveRemovedAiChatThread';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { useListenToObjectRecordOperationBrowserEvent } from '@/browser-event/hooks/useListenToObjectRecordOperationBrowserEvent';import { type ObjectRecordOperationBrowserEventDetail } from '@/browser-event/types/ObjectRecordOperationBrowserEventDetail';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';import { type ObjectRecordOperationUpdateInput } from '@/object-record/types/ObjectRecordOperationUpdateInput';import { useListenToEventsForQuery } from '@/sse-db-event/hooks/useListenToEventsForQuery';import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';-const THREAD_LIST_FIELD_NAMES = ['title', 'deletedAt', 'updatedAt'] as const;-const AGENT_CHAT_THREADS_OPERATION_SIGNATURE = {objectNameSingular: CoreObjectNameSingular.AgentChatThread,variables: {},};-const toThreadListUpdate = ({+const toThreadUpdate = ({recordId,updatedFields,-}: ObjectRecordOperationUpdateInput) => {- const updatedValues = Object.assign({}, ...updatedFields) as Record<- string,- unknown- >;- const listValues = Object.fromEntries(- THREAD_LIST_FIELD_NAMES.filter(- (fieldName) => fieldName in updatedValues,- ).map((fieldName) => [fieldName, updatedValues[fieldName]]),- ) as Partial<FlatAgentChatThread>;-- return Object.keys(listValues).length > 0- ? { id: recordId, ...listValues }- : undefined;-};+}: ObjectRecordOperationUpdateInput): Partial<AgentChatThreadRecord> & {+ id: string;+} => ({+ id: recordId,+ ...(Object.assign({}, ...updatedFields) as Partial<AgentChatThreadRecord>),+});-// Chats are renamed, deleted, restored and destroyed through the record API,-// while the chat keeps its own list of conversationsexport const AgentChatThreadRecordOperationsEffect = () => {const chatObjectMetadataItem = useAtomFamilySelectorValue(objectMetadataItemFamilySelector,@@ -49,23 +38,31 @@ export const AgentChatThreadRecordOperationsEffect = () => {objectNameType: 'singular',},);- const { applyAgentChatThreadUpdate } = useApplyAgentChatThreadUpdate();+ const { applyAgentChatThreadUpdate, addAgentChatThread } =+ useApplyAgentChatThreadUpdate();const { refreshAgentChatThreads } = useRefreshAgentChatThreads();const { leaveRemovedAiChatThread } = useLeaveRemovedAiChatThread();+ const store = useStore();const isEnabled = isDefined(chatObjectMetadataItem);+ // The removal check looks the current chat up itself, so it runs even when+ // the reload could not settle+ const reloadAgentChatThreads = useCallback(async () => {+ await refreshAgentChatThreads();+ await leaveRemovedAiChatThread();+ }, [leaveRemovedAiChatThread, refreshAgentChatThreads]);+useListenToEventsForQuery({queryId: 'agent-chat-thread-record-operations',operationSignature: AGENT_CHAT_THREADS_OPERATION_SIGNATURE,skip: !isEnabled,+ onSseReconnected: reloadAgentChatThreads,});const handleRecordOperation = useCallback(({ operation }: ObjectRecordOperationBrowserEventDetail) => {const applyUpdates = (- updates: (Partial<FlatAgentChatThread> & {- id: string;- })[],+ updates: (Partial<AgentChatThreadRecord> & { id: string })[],) => {for (const update of updates) {applyAgentChatThreadUpdate(update);@@ -73,6 +70,17 @@ export const AgentChatThreadRecordOperationsEffect = () => {};switch (operation.type) {+ case 'create-one': {+ const createdThread =+ operation.createdRecord as AgentChatThreadRecord;++ // A workflow run's conversation is announced to whoever reads the+ // run, but it is listed with the run, not in the chat list+ if (!isDefined(createdThread.workflowRunId)) {+ addAgentChatThread(createdThread);+ }+ return;+ }case 'update-one':case 'update-many': {const updateInputs =@@ -80,7 +88,20 @@ export const AgentChatThreadRecordOperationsEffect = () => {? [operation.result.updateInput]: operation.result.updateInputs;- applyUpdates(updateInputs.map(toThreadListUpdate).filter(isDefined));+ applyUpdates(updateInputs.map(toThreadUpdate));++ // A chat past the loaded pages moves to the top once updated, and+ // reloading keeps workflow run conversations out of the list+ const listedThreadIds =+ store.get(agentChatThreadListState.atom)?.threadIds ?? [];++ if (+ updateInputs.some(+ ({ recordId }) => !listedThreadIds.includes(recordId),+ )+ ) {+ void refreshAgentChatThreads();+ }return;}case 'delete-one':@@ -107,17 +128,16 @@ export const AgentChatThreadRecordOperationsEffect = () => {return;}default:- void refreshAgentChatThreads().then((threads) => {- if (isDefined(threads)) {- leaveRemovedAiChatThread();- }- });+ // Destroy and bulk create events carry no ids+ void reloadAgentChatThreads();}},[+ addAgentChatThread,applyAgentChatThreadUpdate,- leaveRemovedAiChatThread,refreshAgentChatThreads,+ reloadAgentChatThreads,+ store,],);diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadsFetchMoreTrigger.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadsFetchMoreTrigger.tsxnew file mode 100644index 00000000000..fc66b671095--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadsFetchMoreTrigger.tsx@@ -0,0 +1,31 @@+import { styled } from '@linaria/react';+import { useInView } from 'react-intersection-observer';+import { isDefined } from 'twenty-shared/utils';++import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';++const StyledFetchMoreTrigger = styled.div`+ height: 1px;+ min-height: 1px;+ width: 100%;+`;++export const AgentChatThreadsFetchMoreTrigger = () => {+ const agentChatThreadList = useAtomStateValue(agentChatThreadListState);+ const { fetchMoreAgentChatThreads } = useRefreshAgentChatThreads();+ const { ref } = useInView({+ onChange: (inView) => {+ if (inView) {+ void fetchMoreAgentChatThreads();+ }+ },+ });++ if (!isDefined(agentChatThreadList) || !agentChatThreadList.hasNextPage) {+ return null;+ }++ return <StyledFetchMoreTrigger ref={ref} />;+};diff --git a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsxindex fd1bbfa6806..f253216e40f 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatPageThreadUrlSyncEffect.tsx@@ -5,10 +5,9 @@ import { isDefined, isValidUuid } from 'twenty-shared/utils';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import { useSwitchAgentChatThreadWithDraft } from '@/ai/hooks/useSwitchAgentChatThreadWithDraft';import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { currentAiChatThreadDataSelector } from '@/ai/states/selectors/currentAiChatThreadDataSelector';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';export const AiChatPageThreadUrlSyncEffect = () => {@@ -17,12 +16,10 @@ export const AiChatPageThreadUrlSyncEffect = () => {const currentAiChatThreadData = useAtomStateValue(currentAiChatThreadDataSelector,);- const metadataStoreAgentChatThreads = useAtomFamilyStateValue(- metadataStoreState,- 'agentChatThreads',- );+ const areAgentChatThreadsLoaded =+ useAtomStateValue(agentChatThreadListState) !== null;const { switchThreadWithDraft } = useSwitchAgentChatThreadWithDraft();- const { refreshAgentChatThreads } = useRefreshAgentChatThreads();+ const { loadAgentChatThread } = useRefreshAgentChatThreads();const { switchToNewChat } = useSwitchToNewAiChat({shouldOpenInFullPage: true,});@@ -37,18 +34,11 @@ export const AiChatPageThreadUrlSyncEffect = () => {return;}- if (- metadataStoreAgentChatThreads.status === 'up-to-date' &&- !isDefined(currentAiChatThreadData)- ) {+ if (areAgentChatThreadsLoaded && !isDefined(currentAiChatThreadData)) {let isCurrentThread = true;- void refreshAgentChatThreads().then((chatThreads) => {- if (- !isCurrentThread ||- !isDefined(chatThreads) ||- chatThreads.some((chatThread) => chatThread.id === threadId)- ) {+ void loadAgentChatThread(threadId).then((chatThread) => {+ if (!isCurrentThread || chatThread !== null) {return;}@@ -63,8 +53,8 @@ export const AiChatPageThreadUrlSyncEffect = () => {threadId,currentAiChatThread,currentAiChatThreadData,- metadataStoreAgentChatThreads.status,- refreshAgentChatThreads,+ areAgentChatThreadsLoaded,+ loadAgentChatThread,switchThreadWithDraft,switchToNewChat,]);diff --git a/packages/twenty-front/src/modules/ai/components/MobileHomeAiChatSection.tsx b/packages/twenty-front/src/modules/ai/components/MobileHomeAiChatSection.tsxindex 6f419871c6c..7fccd28a0e1 100644--- a/packages/twenty-front/src/modules/ai/components/MobileHomeAiChatSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/MobileHomeAiChatSection.tsx@@ -1,3 +1,4 @@+import { AgentChatThreadsFetchMoreTrigger } from '@/ai/components/AgentChatThreadsFetchMoreTrigger';import { NavigationDrawerAiChatThreadSection } from '@/ai/components/NavigationDrawerAiChatThreadSection';import { useAiChatThreadClick } from '@/ai/hooks/useAiChatThreadClick';import { useChatThreads } from '@/ai/hooks/useChatThreads';@@ -21,12 +22,15 @@ export const MobileHomeAiChatSection = () => {}return (- <NavigationDrawerAiChatThreadSection- sectionId={MOBILE_HOME_AI_CHAT_SECTION_ID}- title={t`Conversations`}- threads={threads}- currentThreadId={currentAiChatThread}- onThreadClick={handleThreadClick}- />+ <>+ <NavigationDrawerAiChatThreadSection+ sectionId={MOBILE_HOME_AI_CHAT_SECTION_ID}+ title={t`Conversations`}+ threads={threads}+ currentThreadId={currentAiChatThread}+ onThreadClick={handleThreadClick}+ />+ <AgentChatThreadsFetchMoreTrigger />+ </>);};diff --git a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatContent.tsx b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatContent.tsxindex 6ce55d81219..42fa460c062 100644--- a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatContent.tsx+++ b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatContent.tsx@@ -9,6 +9,7 @@ import { NavigationDrawerAiChatThreadSection } from '@/ai/components/NavigationDimport { AGENT_CHAT_THREAD_GROUP_BY } from '@/ai/constants/AgentChatThreadGroupBy';import { AI_CHAT_THREAD_ACTIONS_SURFACE } from '@/ai/constants/AiChatThreadActionsSurface';import { useAiChatThreadClick } from '@/ai/hooks/useAiChatThreadClick';+import { AgentChatThreadsFetchMoreTrigger } from '@/ai/components/AgentChatThreadsFetchMoreTrigger';import { useChatThreads } from '@/ai/hooks/useChatThreads';import { agentChatThreadGroupByState } from '@/ai/states/agentChatThreadGroupByState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';@@ -45,12 +46,6 @@ const StyledEmptyState = styled.div`justify-content: center;`;-const StyledFetchMoreTrigger = styled.div`- height: 1px;- min-height: 1px;- width: 100%;-`;-const AI_CHAT_RECENTS_NAVIGATION_SECTION_ID = 'AiChatRecents';export const NavigationDrawerAiChatContent = () => {@@ -63,7 +58,7 @@ export const NavigationDrawerAiChatContent = () => {});const agentChatThreadGroupBy = useAtomStateValue(agentChatThreadGroupByState);- const { threads, hasNextPage, loading, fetchMoreRef } = useChatThreads();+ const { threads, loading } = useChatThreads();if (loading && threads.length === 0) {return (@@ -114,7 +109,7 @@ export const NavigationDrawerAiChatContent = () => {{threads.length === 0 && isExpanded ? (<StyledEmptyState>{t`No chat`}</StyledEmptyState>) : null}- {hasNextPage ? <StyledFetchMoreTrigger ref={fetchMoreRef} /> : null}+ <AgentChatThreadsFetchMoreTrigger /></StyledThreadList></StyledContainer>);diff --git a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsxindex 366d6344d50..d69a593cc8e 100644--- a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx+++ b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadItem.tsx@@ -10,12 +10,12 @@ import { isDropdownOpenComponentState } from '@/ui/layout/dropdown/states/isDropimport { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';import { NavigationDrawerInput } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerInput';import { NavigationDrawerItem } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerItem';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';type NavigationDrawerAiChatThreadItemProps = {- thread: AgentChatThread;+ thread: AgentChatThreadRecord;isActive: boolean;- onClick: (thread: AgentChatThread) => void;+ onClick: (thread: AgentChatThreadRecord) => void;};export const NavigationDrawerAiChatThreadItem = ({diff --git a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadSection.tsx b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadSection.tsxindex d25b773e89c..8a4c9566a35 100644--- a/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/NavigationDrawerAiChatThreadSection.tsx@@ -1,14 +1,14 @@import { type ReactNode } from 'react';import { NavigationDrawerAiChatThreadItem } from '@/ai/components/NavigationDrawerAiChatThreadItem';import { CollapsibleNavigationDrawerSection } from '@/ui/navigation/navigation-drawer/components/CollapsibleNavigationDrawerSection';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';export type NavigationDrawerAiChatThreadSectionProps = {sectionId: string;title: string;- threads: AgentChatThread[];+ threads: AgentChatThreadRecord[];currentThreadId: string | null;- onThreadClick: (thread: AgentChatThread) => void;+ onThreadClick: (thread: AgentChatThreadRecord) => void;rightIcon?: ReactNode;alwaysShowRightIcon?: boolean;};diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsxindex e79c6ac2953..2fd99597064 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadInitializationEffect.test.tsx@@ -1,7 +1,12 @@import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';+import {+ type CurrentWorkspace,+ currentWorkspaceState,+} from '@/auth/states/currentWorkspaceState';import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { WorkspaceActivationStatus } from 'twenty-shared/workspace';import { act, render } from '@testing-library/react';import { createStore, Provider as JotaiProvider } from 'jotai';@@ -20,6 +25,20 @@ jest.mock('@/settings/roles/hooks/useHasPermissionFlag', () => ({useHasPermissionFlag: () => true,}));+const buildStore = () => {+ const store = createStore();++ // The workspace is persisted in local storage, shared across stores+ store.set(currentWorkspaceState.atom, null);+ store.set(metadataStoreState.atomFamily('fieldMetadataItems'), {+ current: [],+ draft: [],+ status: 'up-to-date',+ });++ return store;+};+describe('AgentChatThreadInitializationEffect', () => {beforeEach(() => {jest.useFakeTimers();@@ -36,7 +55,7 @@ describe('AgentChatThreadInitializationEffect', () => {.mockResolvedValueOnce([]);render(- <JotaiProvider store={createStore()}>+ <JotaiProvider store={buildStore()}><AgentChatComponentInstanceContext.Providervalue={{ instanceId: 'agent-chat-initialization-test' }}>@@ -58,9 +77,58 @@ describe('AgentChatThreadInitializationEffect', () => {expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(2);});+ it('waits for the chat fields before reading chats through the record API', async () => {+ const store = createStore();+ store.set(metadataStoreState.atomFamily('fieldMetadataItems'), {+ current: [],+ draft: [],+ status: 'empty',+ });++ render(+ <JotaiProvider store={store}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'agent-chat-initialization-test' }}+ >+ <AgentChatThreadInitializationEffect />+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>,+ );++ await act(async () => {+ await Promise.resolve();+ });++ expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();+ });++ it('does not read chats in a suspended workspace, which the record API refuses', async () => {+ const store = buildStore();+ store.set(currentWorkspaceState.atom, {+ id: 'workspace-id',+ activationStatus: WorkspaceActivationStatus.SUSPENDED,+ } as CurrentWorkspace);++ render(+ <JotaiProvider store={store}>+ <AgentChatComponentInstanceContext.Provider+ value={{ instanceId: 'agent-chat-initialization-test' }}+ >+ <AgentChatThreadInitializationEffect />+ </AgentChatComponentInstanceContext.Provider>+ </JotaiProvider>,+ );++ await act(async () => {+ await Promise.resolve();+ });++ expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();+ });+it('seeds an already-selected deep link when metadata arrives', async () => {refreshAgentChatThreadsMock.mockResolvedValue([]);- const store = createStore();+ const store = buildStore();const threadId = '9ebfd0b0-a703-4478-8859-9b01c2eef391';store.set(currentAiChatThreadState.atom, threadId);const usageAtom = agentChatUsageComponentFamilyState.atomFamily({@@ -77,31 +145,29 @@ describe('AgentChatThreadInitializationEffect', () => {</JotaiProvider>,);expect(store.get(usageAtom)).toBeNull();- const metadataAtom = metadataStoreState.atomFamily('agentChatThreads');await act(async () => {- store.set(metadataAtom, {- ...store.get(metadataAtom),- status: 'up-to-date',- current: [- {- id: threadId,- deletedAt: '2026-09-01',- createdAt: '2026-08-01',- updatedAt: '2026-09-01',- conversationSize: 120,- totalInputTokens: 250,- totalOutputTokens: 30,- totalCacheReadTokens: 80,- contextWindowTokens: 1000,- totalInputCredits: 0.125,- totalOutputCredits: 0.05,- } satisfies AgentChatThread,- ],- });+ setAgentChatThreadList(store, [+ {+ __typename: 'AgentChatThread',+ id: threadId,+ title: null,+ deletedAt: '2026-09-01',+ createdAt: '2026-08-01',+ updatedAt: '2026-09-01',+ conversationSize: 120,+ totalInputTokens: 250,+ totalOutputTokens: 30,+ totalCacheReadTokens: 80,+ contextWindowTokens: 1000,+ totalInputCredits: 125000,+ totalOutputCredits: 50000,+ },+ ]);});expect(store.get(usageAtom)).toMatchObject({inputTokens: 250,cachedInputTokens: 80,+ inputCredits: 0.125,lastMessage: null,});expect(store.get(currentAiChatThreadState.atom)).toBe(threadId);diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadRecordOperationsEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadRecordOperationsEffect.test.tsxindex 3b47a322702..077a0933946 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadRecordOperationsEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadRecordOperationsEffect.test.tsx@@ -2,6 +2,7 @@ import { act, render } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { AgentChatThreadRecordOperationsEffect } from '@/ai/components/AgentChatThreadRecordOperationsEffect';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';import {@@ -20,12 +21,16 @@ const OTHER_OBJECT_METADATA_ITEM = {const CHAT_ID = '20202020-0000-4000-8000-0000000000aa';const applyAgentChatThreadUpdate = jest.fn();+const addAgentChatThread = jest.fn();const refreshAgentChatThreads = jest.fn();const leaveRemovedAiChatThread = jest.fn();const useListenToEventsForQuery = jest.fn();jest.mock('@/ai/hooks/useApplyAgentChatThreadUpdate', () => ({- useApplyAgentChatThreadUpdate: () => ({ applyAgentChatThreadUpdate }),+ useApplyAgentChatThreadUpdate: () => ({+ applyAgentChatThreadUpdate,+ addAgentChatThread,+ }),}));jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({useRefreshAgentChatThreads: () => ({ refreshAgentChatThreads }),@@ -61,6 +66,11 @@ describe('AgentChatThreadRecordOperationsEffect', () => {beforeEach(() => {jest.clearAllMocks();resetJotaiStore();+ jotaiStore.set(agentChatThreadListState.atom, {+ threadIds: [CHAT_ID],+ hasNextPage: true,+ endCursor: 'page-1',+ });refreshAgentChatThreads.mockResolvedValue([]);render(<JotaiProvider store={jotaiStore}>@@ -81,7 +91,7 @@ describe('AgentChatThreadRecordOperationsEffect', () => {);});- it('applies a rename to the listed chat, ignoring fields the list does not hold', () => {+ it('applies renames and usage updates to the stored chat', () => {dispatchChatOperation({type: 'update-one',result: {@@ -95,21 +105,42 @@ describe('AgentChatThreadRecordOperationsEffect', () => {expect(applyAgentChatThreadUpdate).toHaveBeenCalledWith({id: CHAT_ID,title: 'Renamed',+ totalInputTokens: 12,});+ expect(refreshAgentChatThreads).not.toHaveBeenCalled();});- it('ignores updates that do not change the list', () => {+ it('reloads the list when a chat past the loaded pages is updated', () => {dispatchChatOperation({type: 'update-one',result: {updateInput: {- recordId: CHAT_ID,- updatedFields: [{ totalInputTokens: 12 }],+ recordId: 'older-chat',+ updatedFields: [{ title: 'Renamed' }],},},});- expect(applyAgentChatThreadUpdate).not.toHaveBeenCalled();+ expect(refreshAgentChatThreads).toHaveBeenCalledTimes(1);+ });++ it('lists a created chat but leaves a workflow run conversation to its run', () => {+ dispatchChatOperation({+ type: 'create-one',+ createdRecord: { id: CHAT_ID, workflowRunId: null },+ });++ expect(addAgentChatThread).toHaveBeenCalledWith({+ id: CHAT_ID,+ workflowRunId: null,+ });++ dispatchChatOperation({+ type: 'create-one',+ createdRecord: { id: 'run-conversation', workflowRunId: 'run' },+ });++ expect(addAgentChatThread).toHaveBeenCalledTimes(1);});it('marks deleted chats and clears the mark on restore', () => {@@ -131,7 +162,9 @@ describe('AgentChatThreadRecordOperationsEffect', () => {});});- it('reads the chats again after a destroy and leaves a chat that is gone', async () => {+ it('reads the chats again after a destroy and leaves a chat that is gone, even when the reload fails', async () => {+ refreshAgentChatThreads.mockResolvedValue(undefined);+dispatchChatOperation({ type: 'destroy-one' });await act(async () => {@@ -142,6 +175,15 @@ describe('AgentChatThreadRecordOperationsEffect', () => {expect(leaveRemovedAiChatThread).toHaveBeenCalledTimes(1);});+ it('reads the chats again after the event stream reconnects', async () => {+ const { onSseReconnected } = useListenToEventsForQuery.mock.calls[0][0];++ await act(() => onSseReconnected());++ expect(refreshAgentChatThreads).toHaveBeenCalledTimes(1);+ expect(leaveRemovedAiChatThread).toHaveBeenCalledTimes(1);+ });+it('ignores operations on other objects', () => {dispatchChatOperation({ type: 'delete-one', deletedRecordId: CHAT_ID },diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsxindex 47a273c1e8d..aaf72403ea5 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatPageThreadUrlSyncEffect.test.tsx@@ -6,7 +6,8 @@ import { AppPath } from 'twenty-shared/types';import { AiChatPageThreadUrlSyncEffect } from '@/ai/components/AiChatPageThreadUrlSyncEffect';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import {jotaiStore,resetJotaiStore,@@ -16,7 +17,7 @@ const switchThreadWithDraftMock = jest.fn((toThreadId: string) => {jotaiStore.set(currentAiChatThreadState.atom, toThreadId);});const switchToNewChatMock = jest.fn();-const refreshAgentChatThreadsMock = jest.fn();+const loadAgentChatThreadMock = jest.fn();jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({useSwitchToNewAiChat: () => ({ switchToNewChat: switchToNewChatMock }),@@ -24,7 +25,7 @@ jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({useRefreshAgentChatThreads: () => ({- refreshAgentChatThreads: refreshAgentChatThreadsMock,+ loadAgentChatThread: loadAgentChatThreadMock,}),}));@@ -37,6 +38,18 @@ jest.mock('@/ai/hooks/useSwitchAgentChatThreadWithDraft', () => ({const THREAD_A = '11111111-1111-4111-8111-111111111111';const THREAD_B = '22222222-2222-4222-8222-222222222222';+const buildChat = (+ id: string,+ deletedAt: string | null = null,+): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id,+ title: null,+ deletedAt,+ createdAt: '2026-09-01T00:00:00Z',+ updatedAt: '2026-09-07T00:00:00Z',+});+let navigateToThread: ((threadId: string) => void) | undefined;const RouteUnderTest = () => {@@ -66,7 +79,7 @@ const renderEffectAt = (initialPath: string) =>describe('AiChatPageThreadUrlSyncEffect', () => {beforeEach(() => {jest.clearAllMocks();- refreshAgentChatThreadsMock.mockResolvedValue([]);+ loadAgentChatThreadMock.mockResolvedValue(null);resetJotaiStore();navigateToThread = undefined;});@@ -79,51 +92,54 @@ describe('AiChatPageThreadUrlSyncEffect', () => {expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);});- it('recovers a missing chat only after refreshing the loaded thread list', async () => {+ it('recovers a missing chat only once the thread list has loaded', async () => {renderEffectAt(`/chat/${THREAD_A}`);expect(switchToNewChatMock).not.toHaveBeenCalled();- expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();+ expect(loadAgentChatThreadMock).not.toHaveBeenCalled();await act(async () => {- jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [],- draft: [],- status: 'up-to-date',- });+ setAgentChatThreadList(jotaiStore, []);});- expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(1);+ expect(loadAgentChatThreadMock).toHaveBeenCalledWith(THREAD_A);expect(switchToNewChatMock).toHaveBeenCalledTimes(1);});- it('keeps a valid chat URL found by refreshing a stale thread list', async () => {- refreshAgentChatThreadsMock.mockResolvedValue([{ id: THREAD_A }]);- jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [{ id: THREAD_B }],- draft: [],- status: 'up-to-date',+ it('keeps a chat URL that sits past the loaded pages', async () => {+ loadAgentChatThreadMock.mockResolvedValue(buildChat(THREAD_A));+ setAgentChatThreadList(jotaiStore, [buildChat(THREAD_B)], {+ hasNextPage: true,});await act(async () => {renderEffectAt(`/chat/${THREAD_A}`);});- expect(refreshAgentChatThreadsMock).toHaveBeenCalledTimes(1);+ expect(loadAgentChatThreadMock).toHaveBeenCalledWith(THREAD_A);expect(switchToNewChatMock).not.toHaveBeenCalled();});- it('keeps an archived chat URL when the thread exists in metadata', () => {- jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [{ id: THREAD_A, deletedAt: '2026-09-07T00:00:00Z' }],- draft: [],- status: 'up-to-date',+ it('keeps the chat URL when the chat cannot be looked up', async () => {+ loadAgentChatThreadMock.mockResolvedValue(undefined);+ setAgentChatThreadList(jotaiStore, [buildChat(THREAD_B)]);++ await act(async () => {+ renderEffectAt(`/chat/${THREAD_A}`);});+ expect(switchToNewChatMock).not.toHaveBeenCalled();+ });++ it('keeps a deleted chat URL when the chat is listed', () => {+ setAgentChatThreadList(jotaiStore, [+ buildChat(THREAD_A, '2026-09-07T00:00:00Z'),+ ]);+renderEffectAt(`/chat/${THREAD_A}`);expect(switchThreadWithDraftMock).toHaveBeenCalledWith(THREAD_A);- expect(refreshAgentChatThreadsMock).not.toHaveBeenCalled();+ expect(loadAgentChatThreadMock).not.toHaveBeenCalled();expect(switchToNewChatMock).not.toHaveBeenCalled();});diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.tsnew file mode 100644index 00000000000..aea8261207b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.ts@@ -0,0 +1,14 @@+export const AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS = {+ id: true,+ title: true,+ deletedAt: true,+ createdAt: true,+ updatedAt: true,+ totalInputTokens: true,+ totalOutputTokens: true,+ totalCacheReadTokens: true,+ contextWindowTokens: true,+ conversationSize: true,+ totalInputCredits: true,+ totalOutputCredits: true,+};diff --git a/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadFragment.ts b/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadFragment.tsindex b67839364b0..974089134bd 100644--- a/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadFragment.ts+++ b/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadFragment.ts@@ -12,7 +12,6 @@ export const AGENT_CHAT_THREAD_FRAGMENT = gql`totalInputCreditstotalOutputCreditsdeletedAt- lastMessageAtcreatedAtupdatedAt}diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.tsdeleted file mode 100644index 5ea4fbcaa2e..00000000000--- a/packages/twenty-front/src/modules/ai/graphql/queries/getChatThreads.ts+++ /dev/null@@ -1,12 +0,0 @@-import { gql } from '@apollo/client';--import { AGENT_CHAT_THREAD_FRAGMENT } from '@/ai/graphql/fragments/agentChatThreadFragment';--export const GET_CHAT_THREADS = gql`- ${AGENT_CHAT_THREAD_FRAGMENT}- query GetChatThreads {- chatThreads {- ...AgentChatThreadFields- }- }-`;diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsxindex d3ed661e54e..ea9293e5568 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useChatThreadsForRecord.test.tsx@@ -50,6 +50,7 @@ const buildLink = ({id: threadId,title,deletedAt: null,+ createdAt: '2026-09-28T10:00:00.000Z',updatedAt: '2026-09-28T10:00:00.000Z',},});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsxindex 4a81957decf..979c88e6f02 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useLeaveRemovedAiChatThread.test.tsx@@ -9,60 +9,59 @@ import {} from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import {jotaiStore,resetJotaiStore,} from '@/ui/utilities/state/jotai/jotaiStore';const projectAiChatThreadToUrl = jest.fn();+const loadAgentChatThread = jest.fn();jest.mock('@/ai/hooks/useProjectAiChatThreadToUrl', () => ({useProjectAiChatThreadToUrl: () => ({ projectAiChatThreadToUrl }),}));+jest.mock('@/ai/hooks/useRefreshAgentChatThreads', () => ({+ useRefreshAgentChatThreads: () => ({ loadAgentChatThread }),+}));+const REMOVED_CHAT_ID = '20202020-0000-4000-8000-0000000000aa';const OLDER_CHAT_ID = '20202020-0000-4000-8000-0000000000bb';const RECENT_CHAT_ID = '20202020-0000-4000-8000-0000000000cc';-const buildChat = (id: string, updatedAt: string) =>- ({- id,- title: id,- updatedAt,- createdAt: updatedAt,- deletedAt: null,- }) as FlatAgentChatThread;--const setChats = (chats: FlatAgentChatThread[]) =>- jotaiStore.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: chats,- draft: chats,- status: 'up-to-date',- });+const buildChat = (id: string, updatedAt: string): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id,+ title: id,+ updatedAt,+ createdAt: updatedAt,+ deletedAt: null,+});const Wrapper = ({ children }: { children: ReactNode }) => (<JotaiProvider store={jotaiStore}>{children}</JotaiProvider>);-const leave = () => {+const leave = async () => {const { result } = renderHook(() => useLeaveRemovedAiChatThread(), {wrapper: Wrapper,});- act(() => result.current.leaveRemovedAiChatThread());+ await act(() => result.current.leaveRemovedAiChatThread());};describe('useLeaveRemovedAiChatThread', () => {beforeEach(() => {jest.clearAllMocks();resetJotaiStore();+ loadAgentChatThread.mockResolvedValue(null);jotaiStore.set(currentAiChatThreadState.atom, REMOVED_CHAT_ID);});- it('moves to the most recent chat with its draft when the current one is gone', () => {- setChats([+ it('moves to the most recent chat with its draft when the current one is gone', async () => {+ setAgentChatThreadList(jotaiStore, [buildChat(OLDER_CHAT_ID, '2026-09-01T00:00:00.000Z'),buildChat(RECENT_CHAT_ID, '2026-09-20T00:00:00.000Z'),]);@@ -70,28 +69,46 @@ describe('useLeaveRemovedAiChatThread', () => {[RECENT_CHAT_ID]: 'Pending question',});- leave();+ await leave();expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(RECENT_CHAT_ID);expect(jotaiStore.get(agentChatInputState.atom)).toBe('Pending question');expect(projectAiChatThreadToUrl).toHaveBeenCalledWith(RECENT_CHAT_ID);});- it('opens a new chat when no chat is left', () => {- setChats([]);+ it('opens a new chat when no chat is left', async () => {+ setAgentChatThreadList(jotaiStore, []);- leave();+ await leave();expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(AGENT_CHAT_NEW_THREAD_DRAFT_KEY,);});- it('stays on a chat that still exists', () => {- setChats([buildChat(REMOVED_CHAT_ID, '2026-09-01T00:00:00.000Z')]);+ it('stays on a chat that is still listed', async () => {+ setAgentChatThreadList(jotaiStore, [+ buildChat(REMOVED_CHAT_ID, '2026-09-01T00:00:00.000Z'),+ ]);++ await leave();++ expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(REMOVED_CHAT_ID);+ expect(loadAgentChatThread).not.toHaveBeenCalled();+ expect(projectAiChatThreadToUrl).not.toHaveBeenCalled();+ });++ it('stays on an older chat that exists past the loaded pages', async () => {+ setAgentChatThreadList(jotaiStore, [+ buildChat(RECENT_CHAT_ID, '2026-09-20T00:00:00.000Z'),+ ]);+ loadAgentChatThread.mockResolvedValue(+ buildChat(REMOVED_CHAT_ID, '2025-01-01T00:00:00.000Z'),+ );- leave();+ await leave();+ expect(loadAgentChatThread).toHaveBeenCalledWith(REMOVED_CHAT_ID);expect(jotaiStore.get(currentAiChatThreadState.atom)).toBe(REMOVED_CHAT_ID);expect(projectAiChatThreadToUrl).not.toHaveBeenCalled();});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsxindex 2dbfbd9d81f..0514040095f 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx@@ -1,48 +1,95 @@import { act, renderHook } from '@testing-library/react';-import { createStore, Provider as JotaiProvider } from 'jotai';+import { atom, createStore, Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';-import { clearMetadataStoreStorage } from '@/metadata-store/storage/metadataStoreStorage';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';+import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';const queryMock = jest.fn();-const mockApolloClient = { query: queryMock };+const mockApolloCoreClient = { query: queryMock };-jest.mock('@apollo/client/react', () => ({- ...jest.requireActual('@apollo/client/react'),- useApolloClient: () => mockApolloClient,+jest.mock('@/object-metadata/hooks/useApolloCoreClient', () => ({+ useApolloCoreClient: () => mockApolloCoreClient,}));-const buildThread = (id: string, title: string): AgentChatThread => ({+const chatObjectMetadataItemAtom = atom<unknown>({+ id: 'chat-object',+ nameSingular: 'agentChatThread',+ namePlural: 'agentChatThreads',+ fields: [{ name: 'title' }],+ readableFields: [{ name: 'title' }],+});++jest.mock('@/object-metadata/states/objectMetadataItemFamilySelector', () => ({+ objectMetadataItemFamilySelector: {+ selectorFamily: () => chatObjectMetadataItemAtom,+ },+}));++jest.mock('@/object-record/utils/generateFindManyRecordsQuery', () => ({+ generateFindManyRecordsQuery: () => 'find-many-agent-chat-threads',+}));++const refreshAgentChatThreadPermissions = jest.fn();++jest.mock('@/ai/hooks/useRefreshAgentChatThreadPermissions', () => ({+ useRefreshAgentChatThreadPermissions: () => ({+ refreshAgentChatThreadPermissions,+ }),+}));++const buildThread = (id: string, title: string): AgentChatThreadRecord => ({__typename: 'AgentChatThread',id,title,+ deletedAt: null,createdAt: '2026-09-07T00:00:00.000Z',updatedAt: '2026-09-07T00:00:00.000Z',- lastMessageAt: '2026-09-07T00:00:00.000Z',- totalInputTokens: 0,- totalOutputTokens: 0,- totalCacheReadTokens: 0,- conversationSize: 0,- totalInputCredits: 0,- totalOutputCredits: 0,});+const buildPage = (+ threads: AgentChatThreadRecord[],+ { hasNextPage = false, endCursor = 'end' } = {},+) => ({+ data: {+ agentChatThreads: {+ edges: threads.map((thread) => ({ node: thread, cursor: thread.id })),+ pageInfo: {+ hasNextPage,+ hasPreviousPage: false,+ startCursor: 'start',+ endCursor,+ },+ totalCount: threads.length,+ },+ },+});++const buildStore = () => createStore();+const getWrapper = (store: ReturnType<typeof createStore>) =>function Wrapper({ children }: { children: ReactNode }) {return <JotaiProvider store={store}>{children}</JotaiProvider>;};+const renderRefresh = (store: ReturnType<typeof createStore>) =>+ renderHook(() => useRefreshAgentChatThreads(), {+ wrapper: getWrapper(store),+ }).result;+describe('useRefreshAgentChatThreads', () => {- beforeEach(async () => {- await clearMetadataStoreStorage();+ beforeEach(() => {jest.clearAllMocks();+ refreshAgentChatThreadPermissions.mockResolvedValue(undefined);});it('keeps the refresh callback stable so render updates do not restart subscriptions', () => {- const store = createStore();+ const store = buildStore();const { result, rerender } = renderHook(() => useRefreshAgentChatThreads(),{ wrapper: getWrapper(store) },@@ -52,34 +99,79 @@ describe('useRefreshAgentChatThreads', () => {expect(result.current.refreshAgentChatThreads).toBe(refresh);});- it('loads chat threads into an empty store', async () => {- const store = createStore();+ it('loads the most recently updated chats through the record API', async () => {+ const store = buildStore();const thread = buildThread('thread-1', 'Loaded thread');- queryMock.mockResolvedValue({ data: { chatThreads: [thread] } });- const { result } = renderHook(() => useRefreshAgentChatThreads(), {- wrapper: getWrapper(store),+ queryMock.mockResolvedValue(buildPage([thread], { hasNextPage: true }));+ const result = renderRefresh(store);++ await act(async () => {+ await result.current.refreshAgentChatThreads();});+ expect(queryMock).toHaveBeenCalledWith(+ expect.objectContaining({+ variables: expect.objectContaining({+ orderBy: [{ updatedAt: 'DescNullsLast' }],+ lastCursor: null,+ }),+ fetchPolicy: 'network-only',+ }),+ );+ expect(store.get(agentChatThreadListState.atom)).toEqual({+ threadIds: ['thread-1'],+ hasNextPage: true,+ endCursor: 'end',+ });+ expect(store.get(agentChatThreadsSelector.atom)).toMatchObject([+ { id: 'thread-1', title: 'Loaded thread' },+ ]);+ });++ it('appends the next page after the loaded chats', async () => {+ const store = buildStore();+ queryMock+ .mockResolvedValueOnce(+ buildPage([buildThread('thread-1', 'First')], {+ hasNextPage: true,+ endCursor: 'page-1',+ }),+ )+ .mockResolvedValueOnce(+ buildPage([buildThread('thread-2', 'Second')], { endCursor: 'page-2' }),+ );+ const result = renderRefresh(store);+await act(async () => {await result.current.refreshAgentChatThreads();+ await result.current.fetchMoreAgentChatThreads();});- expect(- store.get(metadataStoreState.atomFamily('agentChatThreads')),- ).toMatchObject({- current: [thread],- status: 'up-to-date',+ expect(queryMock).toHaveBeenLastCalledWith(+ expect.objectContaining({+ variables: expect.objectContaining({ lastCursor: 'page-1' }),+ }),+ );+ expect(store.get(agentChatThreadListState.atom)).toEqual({+ threadIds: ['thread-1', 'thread-2'],+ hasNextPage: false,+ endCursor: 'page-2',+ });++ await act(async () => {+ expect(await result.current.fetchMoreAgentChatThreads()).toBeUndefined();});+ expect(queryMock).toHaveBeenCalledTimes(2);});- it('retries when the store changes during the request', async () => {- const store = createStore();- const newerThread = buildThread('thread-1', 'Newer title');- const staleThread = buildThread('thread-1', 'Stale title');- const serverOnlyThread = buildThread('thread-2', 'Server thread');- let resolveQuery: (value: {- data: { chatThreads: AgentChatThread[] };- }) => void = () => undefined;+ it('retries when a record event changes the list during the request', async () => {+ const store = buildStore();+ const serverThreads = [+ buildThread('thread-1', 'Newer title'),+ buildThread('thread-2', 'Server thread'),+ ];+ let resolveQuery: (value: ReturnType<typeof buildPage>) => void = () =>+ undefined;queryMock.mockReturnValueOnce(@@ -87,104 +179,234 @@ describe('useRefreshAgentChatThreads', () => {resolveQuery = resolve;}),)- .mockResolvedValueOnce({- data: { chatThreads: [newerThread, serverOnlyThread] },- });- const { result } = renderHook(() => useRefreshAgentChatThreads(), {- wrapper: getWrapper(store),- });+ .mockResolvedValueOnce(buildPage(serverThreads));+ const result = renderRefresh(store);const refreshPromise = result.current.refreshAgentChatThreads();act(() => {- store.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [newerThread],- draft: [],- status: 'up-to-date',+ store.set(agentChatThreadListState.atom, {+ threadIds: ['thread-1'],+ hasNextPage: false,+ endCursor: null,});});- let refreshedThreads: AgentChatThread[] | undefined;+ let refreshedThreads: AgentChatThreadRecord[] | undefined;await act(async () => {- resolveQuery({ data: { chatThreads: [staleThread] } });+ resolveQuery(buildPage([buildThread('thread-1', 'Stale title')]));refreshedThreads = await refreshPromise;});- expect(refreshedThreads).toEqual([newerThread, serverOnlyThread]);+ expect(refreshedThreads).toMatchObject([+ { id: 'thread-1', title: 'Newer title' },+ { id: 'thread-2' },+ ]);expect(queryMock).toHaveBeenCalledTimes(2);- expect(- store.get(metadataStoreState.atomFamily('agentChatThreads')).current,- ).toEqual([newerThread, serverOnlyThread]);+ expect(store.get(agentChatThreadListState.atom)?.threadIds).toEqual([+ 'thread-1',+ 'thread-2',+ ]);});- it('stops retrying when streaming continually updates the store', async () => {- const store = createStore();- const newerThread = buildThread('thread-1', 'Streaming title');+ it('retries rather than overwrite a chat updated during the request', async () => {+ const store = buildStore();+ let resolveQuery: (value: ReturnType<typeof buildPage>) => void = () =>+ undefined;++ queryMock+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveQuery = resolve;+ }),+ )+ .mockResolvedValueOnce(+ buildPage([buildThread('thread-1', 'Renamed meanwhile')]),+ );+ const result = renderRefresh(store);++ const refreshPromise = result.current.refreshAgentChatThreads();++ act(() => {+ store.set(agentChatThreadRecordUpdateCountState.atom, 1);+ });++ await act(async () => {+ resolveQuery(buildPage([buildThread('thread-1', 'Stale title')]));+ await refreshPromise;+ });++ expect(queryMock).toHaveBeenCalledTimes(2);+ expect(store.get(agentChatThreadsSelector.atom)).toMatchObject([+ { id: 'thread-1', title: 'Renamed meanwhile' },+ ]);+ });++ it('stops retrying when record events keep changing the list', async () => {+ const store = buildStore();+ let changeCount = 0;queryMock.mockImplementation(async () => {- store.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [newerThread],- draft: [],- status: 'up-to-date',+ changeCount++;+ store.set(agentChatThreadListState.atom, {+ threadIds: [`thread-${changeCount}`],+ hasNextPage: false,+ endCursor: null,});- return {- data: { chatThreads: [buildThread('thread-1', 'Stale title')] },- };- });- const { result } = renderHook(() => useRefreshAgentChatThreads(), {- wrapper: getWrapper(store),+ return buildPage([buildThread('thread-1', 'Stale title')]);});+ const result = renderRefresh(store);+await act(async () => {expect(await result.current.refreshAgentChatThreads()).toBeUndefined();});+expect(queryMock).toHaveBeenCalledTimes(2);- expect(- store.get(metadataStoreState.atomFamily('agentChatThreads')).current,- ).toEqual([newerThread]);+ expect(store.get(agentChatThreadListState.atom)?.threadIds).toEqual([+ 'thread-2',+ ]);});- it('applies server updates and removals when the store has not changed', async () => {- const store = createStore();- const staleThread = buildThread('thread-1', 'Stale title');- const refreshedThread = buildThread('thread-1', 'Refreshed title');- const removedThread = buildThread('thread-2', 'Removed thread');- store.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [staleThread, removedThread],- draft: [],- status: 'up-to-date',- });- queryMock.mockResolvedValue({- data: { chatThreads: [refreshedThread] },- });- const { result } = renderHook(() => useRefreshAgentChatThreads(), {- wrapper: getWrapper(store),+ it('drops chats the server no longer lists', async () => {+ const store = buildStore();+ store.set(agentChatThreadListState.atom, {+ threadIds: ['thread-1', 'thread-2'],+ hasNextPage: false,+ endCursor: null,});+ queryMock.mockResolvedValue(+ buildPage([buildThread('thread-1', 'Refreshed title')]),+ );+ const result = renderRefresh(store);await act(async () => {await result.current.refreshAgentChatThreads();});- expect(- store.get(metadataStoreState.atomFamily('agentChatThreads')).current,- ).toEqual([refreshedThread]);+ expect(store.get(agentChatThreadListState.atom)?.threadIds).toEqual([+ 'thread-1',+ ]);});- it('keeps the store empty so initialization can retry a failed request', async () => {- const store = createStore();+ it('leaves the list unloaded so initialization can retry a failed request', async () => {+ const store = buildStore();queryMock.mockRejectedValue(new Error('Network error'));- const { result } = renderHook(() => useRefreshAgentChatThreads(), {- wrapper: getWrapper(store),- });+ const result = renderRefresh(store);await act(async () => {await result.current.refreshAgentChatThreads();});+ expect(store.get(agentChatThreadListState.atom)).toBeNull();+ });++ it('adds a chat opened past the loaded pages, and tells a missing chat from a failed lookup', async () => {+ const store = buildStore();+ store.set(agentChatThreadListState.atom, {+ threadIds: ['thread-1'],+ hasNextPage: true,+ endCursor: 'page-1',+ });+ const result = renderRefresh(store);++ queryMock.mockResolvedValueOnce(+ buildPage([buildThread('old-thread', 'Old chat')]),+ );+ await act(async () => {+ expect(+ await result.current.loadAgentChatThread('old-thread'),+ ).toMatchObject({ id: 'old-thread' });+ });+ expect(queryMock).toHaveBeenLastCalledWith(+ expect.objectContaining({+ variables: expect.objectContaining({+ filter: expect.objectContaining({+ and: expect.arrayContaining([{ id: { eq: 'old-thread' } }]),+ }),+ }),+ }),+ );+ expect(store.get(agentChatThreadListState.atom)?.threadIds).toEqual([+ 'old-thread',+ 'thread-1',+ ]);++ queryMock.mockResolvedValueOnce(buildPage([]));+ await act(async () => {+ expect(await result.current.loadAgentChatThread('gone')).toBeNull();+ });++ queryMock.mockRejectedValueOnce(new Error('Network error'));+ await act(async () => {+ expect(+ await result.current.loadAgentChatThread('unknown'),+ ).toBeUndefined();+ });+ });++ it('restores the usage of a chat opened past the loaded pages', async () => {+ const store = buildStore();+ queryMock.mockResolvedValueOnce(+ buildPage([+ {+ ...buildThread('old-thread', 'Old chat'),+ conversationSize: 3,+ contextWindowTokens: 1000,+ totalInputTokens: 42,+ },+ ]),+ );+ const result = renderRefresh(store);++ await act(async () => {+ await result.current.loadAgentChatThread('old-thread');+ });+expect(- store.get(metadataStoreState.atomFamily('agentChatThreads')),- ).toMatchObject({- current: [],- status: 'empty',+ store.get(+ agentChatUsageComponentFamilyState.atomFamily({+ instanceId: AGENT_CHAT_INSTANCE_ID,+ familyKey: { threadId: 'old-thread' },+ }),+ ),+ ).toMatchObject({ inputTokens: 42 });+ });++ it('looks a chat up again rather than overwrite an update applied during the request', async () => {+ const store = buildStore();+ let resolveQuery: (value: ReturnType<typeof buildPage>) => void = () =>+ undefined;++ queryMock+ .mockReturnValueOnce(+ new Promise((resolve) => {+ resolveQuery = resolve;+ }),+ )+ .mockResolvedValueOnce(+ buildPage([buildThread('old-thread', 'Renamed meanwhile')]),+ );+ store.set(agentChatThreadListState.atom, {+ threadIds: [],+ hasNextPage: true,+ endCursor: 'page-1',+ });+ const result = renderRefresh(store);++ const loadPromise = result.current.loadAgentChatThread('old-thread');++ act(() => {+ store.set(agentChatThreadRecordUpdateCountState.atom, 1);+ });++ await act(async () => {+ resolveQuery(buildPage([buildThread('old-thread', 'Stale title')]));+ await loadPromise;});++ expect(queryMock).toHaveBeenCalledTimes(2);+ expect(store.get(agentChatThreadsSelector.atom)).toMatchObject([+ { id: 'old-thread', title: 'Renamed meanwhile' },+ ]);});});diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsxindex abd9661da9d..2fd1ce0563d 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useSelectAiChatThread.test.tsx@@ -1,7 +1,7 @@import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { act, renderHook } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';@@ -62,8 +62,10 @@ describe('useSelectAiChatThread', () => {);});it('restores usage from an archived thread and preserves it on reselection', () => {- const thread = {+ const thread: AgentChatThreadRecord = {+ __typename: 'AgentChatThread',id: 'archived-thread',+ title: null,deletedAt: '2026-09-01',createdAt: '2026-08-01',updatedAt: '2026-09-01',@@ -72,14 +74,10 @@ describe('useSelectAiChatThread', () => {totalInputTokens: 250,totalOutputTokens: 30,totalCacheReadTokens: 80,- totalInputCredits: 0.125,- totalOutputCredits: 0.05,- } satisfies AgentChatThread;- const metadataAtom = metadataStoreState.atomFamily('agentChatThreads');- jotaiStore.set(metadataAtom, {- ...jotaiStore.get(metadataAtom),- current: [thread],- });+ totalInputCredits: 125000,+ totalOutputCredits: 50000,+ };+ setAgentChatThreadList(jotaiStore, [thread]);const usageAtom = agentChatUsageComponentFamilyState.atomFamily({instanceId: AGENT_CHAT_INSTANCE_ID,familyKey: { threadId: thread.id },diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.tsindex da46bf2d95f..d62b312cdc4 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatThreadClick.ts@@ -5,7 +5,7 @@ import { useOpenAskAiPageInSidePanel } from '@/side-panel/hooks/useOpenAskAiPageimport { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useStore } from 'jotai';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { isCurrentPathAiChatPage } from '~/utils/isCurrentPathAiChatPage';export type UseAiChatThreadClickOptions = {@@ -26,7 +26,9 @@ export const useAiChatThreadClick = (const store = useStore();const { openAskAiPage } = useOpenAskAiPageInSidePanel();- const handleThreadClick = (thread: Pick<AgentChatThread, 'id' | 'title'>) => {+ const handleThreadClick = (+ thread: Pick<AgentChatThreadRecord, 'id' | 'title'>,+ ) => {setThreadIdCreatedFromDraft(null);selectAiChatThread(thread.id);diff --git a/packages/twenty-front/src/modules/ai/hooks/useApplyAgentChatThreadUpdate.ts b/packages/twenty-front/src/modules/ai/hooks/useApplyAgentChatThreadUpdate.tsindex a38b29e27d8..0c247fbdce8 100644--- a/packages/twenty-front/src/modules/ai/hooks/useApplyAgentChatThreadUpdate.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useApplyAgentChatThreadUpdate.ts@@ -1,17 +1,53 @@-import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { useCallback } from 'react';-type AgentChatThreadDraftUpdate = Partial<FlatAgentChatThread> & {+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';+import { useStore } from 'jotai';++type AgentChatThreadUpdate = Partial<AgentChatThreadRecord> & {id: string;};export const useApplyAgentChatThreadUpdate = () => {- const { updateInDraft, applyChanges } = useUpdateMetadataStoreDraft();+ const store = useStore();+ const { upsertRecordsInStore } = useUpsertRecordsInStore();++ // A list page requested before this update must not overwrite it+ const applyAgentChatThreadUpdate = useCallback(+ (update: AgentChatThreadUpdate) => {+ upsertRecordsInStore({+ partialRecords: [{ __typename: 'AgentChatThread', ...update }],+ });+ store.set(+ agentChatThreadRecordUpdateCountState.atom,+ (updateCount) => updateCount + 1,+ );+ },+ [store, upsertRecordsInStore],+ );++ const addAgentChatThread = useCallback(+ (thread: AgentChatThreadUpdate) => {+ applyAgentChatThreadUpdate(thread);++ const agentChatThreadList = store.get(agentChatThreadListState.atom);++ if (+ agentChatThreadList === null ||+ agentChatThreadList.threadIds.includes(thread.id)+ ) {+ return;+ }- const applyAgentChatThreadUpdate = (update: AgentChatThreadDraftUpdate) => {- updateInDraft('agentChatThreads', [update as FlatAgentChatThread]);- applyChanges();- };+ store.set(agentChatThreadListState.atom, {+ ...agentChatThreadList,+ threadIds: [thread.id, ...agentChatThreadList.threadIds],+ });+ },+ [applyAgentChatThreadUpdate, store],+ );- return { applyAgentChatThreadUpdate };+ return { applyAgentChatThreadUpdate, addAgentChatThread };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useChatThreads.tsindex f5e42ea44bc..f437533a540 100644--- a/packages/twenty-front/src/modules/ai/hooks/useChatThreads.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useChatThreads.ts@@ -1,22 +1,16 @@-import { useAtomValue } from 'jotai';-+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';export const useChatThreads = () => {const agentChatVisibleThreads = useAtomStateValue(agentChatVisibleThreadsSelector,);- const storeEntry = useAtomValue(- metadataStoreState.atomFamily('agentChatThreads'),- );+ const agentChatThreadList = useAtomStateValue(agentChatThreadListState);return {threads: sortChatThreadsByLastActivityDesc(agentChatVisibleThreads),- hasNextPage: false,- loading: storeEntry.status === 'empty',- fetchMoreRef: undefined,+ loading: agentChatThreadList === null,};};diff --git a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.tsindex e5780114f79..1196478a641 100644--- a/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useCreateAgentChatThread.ts@@ -1,3 +1,4 @@+import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';import { useStore } from 'jotai';@@ -14,8 +15,6 @@ import { isCreatingChatThreadState } from '@/ai/states/isCreatingChatThreadStateimport { isCreatingForFirstSendState } from '@/ai/states/isCreatingForFirstSendState';import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';import { threadIdCreatedFromDraftState } from '@/ai/states/threadIdCreatedFromDraftState';-import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { tipTapDocumentToMarkdown } from 'twenty-shared/utils';@@ -33,27 +32,19 @@ export const useCreateAgentChatThread = () => {const store = useStore();const { refreshAgentChatThreadPermissions } =useRefreshAgentChatThreadPermissions();- const { addToDraft, applyChanges } = useUpdateMetadataStoreDraft();+ const { addAgentChatThread } = useApplyAgentChatThreadUpdate();const [createChatThread] = useMutation(CreateChatThreadDocument, {onCompleted: (data) => {- const newThread: FlatAgentChatThread = {+ const newThread = {id: data.createChatThread.id,-title: data.createChatThread.title ?? null,createdAt: data.createChatThread.createdAt,updatedAt: data.createChatThread.updatedAt,- conversationSize: 0,- contextWindowTokens: null,- totalInputTokens: 0,- totalOutputTokens: 0,- totalCacheReadTokens: 0,- totalInputCredits: 0,- totalOutputCredits: 0,+ deletedAt: null,};- addToDraft({ key: 'agentChatThreads', items: [newThread] });- applyChanges();+ addAgentChatThread(newThread);void refreshAgentChatThreadPermissions([newThread.id]);if (store.get(isCreatingForFirstSendState.atom)) {diff --git a/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts b/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.tsindex b2b4501aa4b..9de7e2a8d7c 100644--- a/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useLeaveRemovedAiChatThread.ts@@ -7,26 +7,26 @@ import {} from 'twenty-shared/utils';import { useProjectAiChatThreadToUrl } from '@/ai/hooks/useProjectAiChatThreadToUrl';+import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import {AGENT_CHAT_NEW_THREAD_DRAFT_KEY,agentChatDraftsByThreadIdState,} from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { sortChatThreadsByLastActivityDesc } from '@/ai/utils/sortChatThreadsByLastActivityDesc';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';export const useLeaveRemovedAiChatThread = () => {const store = useStore();const { projectAiChatThreadToUrl } = useProjectAiChatThreadToUrl();+ const { loadAgentChatThread } = useRefreshAgentChatThreads();- const leaveRemovedAiChatThread = useCallback(() => {+ const leaveRemovedAiChatThread = useCallback(async () => {const currentThreadId = store.get(currentAiChatThreadState.atom);- const threads = store.get(metadataStoreState.atomFamily('agentChatThreads'))- .current as FlatAgentChatThread[];+ const threads = store.get(agentChatThreadsSelector.atom);if (!isDefined(currentThreadId) ||@@ -36,6 +36,14 @@ export const useLeaveRemovedAiChatThread = () => {return;}+ // Only the first page is reloaded, so an older chat is looked up first+ if (+ (await loadAgentChatThread(currentThreadId)) !== null ||+ store.get(currentAiChatThreadState.atom) !== currentThreadId+ ) {+ return;+ }+store.set(shouldOpenAiChatAfterOnboardingState.atom, false);const nextThreadId =@@ -50,7 +58,7 @@ export const useLeaveRemovedAiChatThread = () => {agentChatInputState.atom,tipTapDocumentToMarkdown(draftsByThreadId[nextThreadId] ?? ''),);- }, [store, projectAiChatThreadToUrl]);+ }, [store, projectAiChatThreadToUrl, loadAgentChatThread]);return { leaveRemovedAiChatThread };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.tsindex d0711d53e59..fc2a1eb3f05 100644--- a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts@@ -1,8 +1,7 @@import { useStore } from 'jotai';import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';export const useOptimisticallyRestoreOnSend = () => {const { applyAgentChatThreadUpdate } = useApplyAgentChatThreadUpdate();@@ -12,11 +11,9 @@ export const useOptimisticallyRestoreOnSend = () => {threadId: string,optimisticUpdatedAt: string,): (() => void) | null => {- const entry = store.get(metadataStoreState.atomFamily('agentChatThreads'));- const threads = (- entry.status === 'draft-pending' ? entry.draft : entry.current- ) as FlatAgentChatThread[];- const thread = threads.find((t) => t.id === threadId);+ const thread = store+ .get(agentChatThreadsSelector.atom)+ .find(({ id }) => id === threadId);if (!thread?.deletedAt) {return null;@@ -24,13 +21,11 @@ export const useOptimisticallyRestoreOnSend = () => {const previousDeletedAt = thread.deletedAt;const previousUpdatedAt = thread.updatedAt;- const previousLastMessageAt = thread.lastMessageAt;applyAgentChatThreadUpdate({id: threadId,deletedAt: null,updatedAt: optimisticUpdatedAt,- lastMessageAt: optimisticUpdatedAt,});return () => {@@ -38,7 +33,6 @@ export const useOptimisticallyRestoreOnSend = () => {id: threadId,deletedAt: previousDeletedAt,updatedAt: previousUpdatedAt,- lastMessageAt: previousLastMessageAt,});};};diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.tsindex 5e7f6eaf0ba..be3433d7909 100644--- a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts@@ -1,91 +1,261 @@import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';+import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';+import { AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS } from '@/ai/constants/AgentChatThreadListRecordGqlFields';import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';+import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { buildAgentChatThreadListFilter } from '@/ai/utils/buildAgentChatThreadListFilter';+import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';-import { useApolloClient } from '@apollo/client/react';+import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';+import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';+import { getRecordsFromRecordConnection } from '@/object-record/cache/utils/getRecordsFromRecordConnection';+import { type RecordGqlOperationFindManyResult } from '@/object-record/graphql/types/RecordGqlOperationFindManyResult';+import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';+import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';+import { generateFindManyRecordsQuery } from '@/object-record/utils/generateFindManyRecordsQuery';import { useStore } from 'jotai';import { useCallback } from 'react';+import { QUERY_MAX_RECORDS } from 'twenty-shared/constants';+import {+ CoreObjectNameSingular,+ type RecordGqlOperationFilter,+} from 'twenty-shared/types';import { isDefined, isValidUuid } from 'twenty-shared/utils';-import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { GetChatThreadsDocument } from '~/generated-metadata/graphql';-export const useRefreshAgentChatThreads = () => {- const client = useApolloClient();+ const apolloCoreClient = useApolloCoreClient();const store = useStore();+ const { objectPermissionsByObjectMetadataId } = useObjectPermissions();+ const { upsertRecordsInStore } = useUpsertRecordsInStore();const { refreshAgentChatThreadPermissions } =useRefreshAgentChatThreadPermissions();- const { replaceDraft, applyChanges } = useUpdateMetadataStoreDraft();-- const refreshAgentChatThreads = useCallback(async () => {- const workspaceId = store.get(currentWorkspaceState.atom)?.id;- const userWorkspace = store.get(currentUserWorkspaceState.atom);- const workspaceMemberId = store.get(currentWorkspaceMemberState.atom)?.id;- for (let attempt = 0; attempt < 2; attempt++) {- const storeEntryBeforeRequest = store.get(- metadataStoreState.atomFamily('agentChatThreads'),+ const { addAgentChatThread } = useApplyAgentChatThreadUpdate();++ const fetchAgentChatThreadsPage = useCallback(+ async ({+ lastCursor,+ threadIdFilter,+ }: {+ lastCursor: string | null;+ threadIdFilter?: RecordGqlOperationFilter;+ }) => {+ const chatObjectMetadataItem = store.get(+ objectMetadataItemFamilySelector.selectorFamily({+ objectName: CoreObjectNameSingular.AgentChatThread,+ objectNameType: 'singular',+ }),);- const result = await client- .query({- query: GetChatThreadsDocument,++ if (+ !isDefined(chatObjectMetadataItem) ||+ chatObjectMetadataItem.readableFields.length === 0+ ) {+ return undefined;+ }++ const result = await apolloCoreClient+ .query<RecordGqlOperationFindManyResult>({+ query: generateFindManyRecordsQuery({+ objectMetadataItem: chatObjectMetadataItem,+ objectMetadataItems: store.get(objectMetadataItemsSelector.atom),+ recordGqlFields: AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS,+ objectPermissionsByObjectMetadataId,+ }),+ variables: {+ filter: isDefined(threadIdFilter)+ ? {+ and: [+ buildAgentChatThreadListFilter(chatObjectMetadataItem),+ threadIdFilter,+ ],+ }+ : buildAgentChatThreadListFilter(chatObjectMetadataItem),+ orderBy: [{ updatedAt: 'DescNullsLast' }],+ limit: QUERY_MAX_RECORDS,+ lastCursor,+ },fetchPolicy: 'network-only',}).catch(() => undefined);- const agentChatThreads = result?.data?.chatThreads;+ const connection = result?.data?.[chatObjectMetadataItem.namePlural];- if (- !isDefined(agentChatThreads) ||- store.get(currentWorkspaceState.atom)?.id !== workspaceId ||- store.get(currentWorkspaceMemberState.atom)?.id !== workspaceMemberId ||- store.get(currentUserWorkspaceState.atom) !== userWorkspace- ) {+ if (!isDefined(connection)) {return undefined;}- // Retry once rather than overwrite newer subscription updates. Continuous- // streaming must not keep a refresh alive indefinitely.- if (- store.get(metadataStoreState.atomFamily('agentChatThreads')) !==- storeEntryBeforeRequest- ) {- continue;- }+ return {+ threads: getRecordsFromRecordConnection<AgentChatThreadRecord>({+ recordConnection: connection,+ }),+ hasNextPage: connection.pageInfo.hasNextPage ?? false,+ endCursor: connection.pageInfo.endCursor ?? null,+ };+ },+ [apolloCoreClient, objectPermissionsByObjectMetadataId, store],+ );- const selectedThreadId = store.get(currentAiChatThreadState.atom);- await refreshAgentChatThreadPermissions([- ...agentChatThreads.map(({ id }) => id),- ...(isDefined(selectedThreadId) && isValidUuid(selectedThreadId)- ? [selectedThreadId]- : []),- ]);- if (- store.get(currentWorkspaceState.atom)?.id !== workspaceId ||- store.get(currentWorkspaceMemberState.atom)?.id !== workspaceMemberId ||- store.get(currentUserWorkspaceState.atom) !== userWorkspace- ) {- return undefined;+ const loadAgentChatThreads = useCallback(+ async (mode: 'refresh' | 'fetch-more') => {+ const workspaceId = store.get(currentWorkspaceState.atom)?.id;+ const userWorkspace = store.get(currentUserWorkspaceState.atom);+ const workspaceMemberId = store.get(currentWorkspaceMemberState.atom)?.id;+ const isSameSession = () =>+ store.get(currentWorkspaceState.atom)?.id === workspaceId &&+ store.get(currentWorkspaceMemberState.atom)?.id === workspaceMemberId &&+ store.get(currentUserWorkspaceState.atom) === userWorkspace;++ for (let attempt = 0; attempt < 2; attempt++) {+ const listBeforeRequest = store.get(agentChatThreadListState.atom);+ const updateCountBeforeRequest = store.get(+ agentChatThreadRecordUpdateCountState.atom,+ );+ const hasChangedSinceRequest = () =>+ store.get(agentChatThreadListState.atom) !== listBeforeRequest ||+ store.get(agentChatThreadRecordUpdateCountState.atom) !==+ updateCountBeforeRequest;++ if (mode === 'fetch-more' && !listBeforeRequest?.hasNextPage) {+ return undefined;+ }++ const page = await fetchAgentChatThreadsPage({+ lastCursor:+ mode === 'fetch-more'+ ? (listBeforeRequest?.endCursor ?? null)+ : null,+ });++ if (!isDefined(page) || !isSameSession()) {+ return undefined;+ }++ // Retry once rather than overwrite a record event applied while the+ // request was in flight+ if (hasChangedSinceRequest()) {+ continue;+ }++ const selectedThreadId = store.get(currentAiChatThreadState.atom);+ await refreshAgentChatThreadPermissions([+ ...page.threads.map(({ id }) => id),+ ...(isDefined(selectedThreadId) && isValidUuid(selectedThreadId)+ ? [selectedThreadId]+ : []),+ ]);++ if (!isSameSession() || hasChangedSinceRequest()) {+ continue;+ }++ upsertRecordsInStore({ partialRecords: page.threads });++ const pageThreadIds = page.threads.map(({ id }) => id);+ const previousThreadIds =+ mode === 'fetch-more' ? (listBeforeRequest?.threadIds ?? []) : [];++ store.set(agentChatThreadListState.atom, {+ threadIds: [+ ...previousThreadIds,+ ...pageThreadIds.filter(+ (threadId) => !previousThreadIds.includes(threadId),+ ),+ ],+ hasNextPage: page.hasNextPage,+ endCursor: page.endCursor,+ });++ return page.threads;}- if (- store.get(metadataStoreState.atomFamily('agentChatThreads')) !==- storeEntryBeforeRequest- ) {- continue;++ return undefined;+ },+ [+ fetchAgentChatThreadsPage,+ refreshAgentChatThreadPermissions,+ store,+ upsertRecordsInStore,+ ],+ );++ const refreshAgentChatThreads = useCallback(+ () => loadAgentChatThreads('refresh'),+ [loadAgentChatThreads],+ );++ const fetchMoreAgentChatThreads = useCallback(+ () => loadAgentChatThreads('fetch-more'),+ [loadAgentChatThreads],+ );++ // A chat opened by URL may sit past the loaded pages. Resolves to null+ // when the chat is not listed for this member, undefined when unknown+ const loadAgentChatThread = useCallback(+ async (threadId: string) => {+ for (let attempt = 0; attempt < 2; attempt++) {+ const updateCountBeforeRequest = store.get(+ agentChatThreadRecordUpdateCountState.atom,+ );+ const page = await fetchAgentChatThreadsPage({+ lastCursor: null,+ threadIdFilter: { id: { eq: threadId } },+ });++ if (!isDefined(page)) {+ return undefined;+ }++ const thread = page.threads[0];++ if (!isDefined(thread)) {+ return null;+ }++ await refreshAgentChatThreadPermissions([thread.id]);++ if (+ store.get(agentChatThreadRecordUpdateCountState.atom) !==+ updateCountBeforeRequest+ ) {+ continue;+ }++ addAgentChatThread(thread);++ // The chat may have been selected before its record was loaded, so+ // its usage could not be restored then+ const usageAtom = agentChatUsageComponentFamilyState.atomFamily({+ instanceId: AGENT_CHAT_INSTANCE_ID,+ familyKey: { threadId: thread.id },+ });++ if (!isDefined(store.get(usageAtom))) {+ store.set(usageAtom, getAgentChatUsageFromThread(thread));+ }++ return thread;}- replaceDraft('agentChatThreads', agentChatThreads);- applyChanges();-- return agentChatThreads;- }- }, [- client,- store,- replaceDraft,- applyChanges,- refreshAgentChatThreadPermissions,- ]);-- return { refreshAgentChatThreads };++ return undefined;+ },+ [+ addAgentChatThread,+ fetchAgentChatThreadsPage,+ refreshAgentChatThreadPermissions,+ store,+ ],+ );++ return {+ refreshAgentChatThreads,+ fetchMoreAgentChatThreads,+ loadAgentChatThread,+ };};diff --git a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.tsindex 37b88c94a36..c5d28dbe868 100644--- a/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useSwitchAgentChatThreadWithDraft.ts@@ -1,9 +1,8 @@import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';import { useAtomComponentFamilyStateCallbackState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentFamilyStateCallbackState';-import { type AgentChatThread } from '~/generated-metadata/graphql';import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';import { agentChatInputState } from '@/ai/states/agentChatInputState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';@@ -31,10 +30,9 @@ export const useSwitchAgentChatThreadWithDraft = () => {setCurrentAiChatThread(toThreadId);if (!isSameThread) {- const threads = store.get(- metadataStoreState.atomFamily('agentChatThreads'),- ).current as AgentChatThread[];- const thread = threads.find(({ id }) => id === toThreadId);+ const thread = store+ .get(agentChatThreadsSelector.atom)+ .find(({ id }) => id === toThreadId);store.set(usageFamilyCallback({ threadId: toThreadId }),isDefined(thread) ? getAgentChatUsageFromThread(thread) : null,diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadListState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadListState.tsnew file mode 100644index 00000000000..e8d69b2026c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/agentChatThreadListState.ts@@ -0,0 +1,13 @@+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';++export type AgentChatThreadList = {+ threadIds: string[];+ hasNextPage: boolean;+ endCursor: string | null;+};++export const agentChatThreadListState =+ createAtomState<AgentChatThreadList | null>({+ key: 'agentChatThreadListState',+ defaultValue: null,+ });diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadRecordUpdateCountState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadRecordUpdateCountState.tsnew file mode 100644index 00000000000..80c5c77dcae--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/agentChatThreadRecordUpdateCountState.ts@@ -0,0 +1,6 @@+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';++export const agentChatThreadRecordUpdateCountState = createAtomState<number>({+ key: 'agentChatThreadRecordUpdateCountState',+ defaultValue: 0,+});diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadsSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadsSelector.tsnew file mode 100644index 00000000000..0cc74477309--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadsSelector.ts@@ -0,0 +1,21 @@+import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';+import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';+import { isDefined } from 'twenty-shared/utils';++export const agentChatThreadsSelector = createAtomSelector<+ AgentChatThreadRecord[]+>({+ key: 'agentChatThreadsSelector',+ get: ({ get }) =>+ (get(agentChatThreadListState)?.threadIds ?? [])+ .map(+ (threadId) =>+ get(recordStoreFamilyState, threadId) as+ | AgentChatThreadRecord+ | null+ | undefined,+ )+ .filter(isDefined),+});diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatVisibleThreadsSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatVisibleThreadsSelector.tsindex cac3bee93a6..c42fcb63569 100644--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatVisibleThreadsSelector.ts+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatVisibleThreadsSelector.ts@@ -2,19 +2,18 @@ import { AGENT_CHAT_THREAD_FILTER_STATUS } from '@/ai/constants/AgentChatThreadFimport { AGENT_CHAT_THREAD_LAST_ACTIVITY_FILTER_DAYS } from '@/ai/constants/AgentChatThreadLastActivityFilterDays';import { agentChatThreadFilterStatusState } from '@/ai/states/agentChatThreadFilterStatusState';import { agentChatThreadLastActivityFilterState } from '@/ai/states/agentChatThreadLastActivityFilterState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;export const agentChatVisibleThreadsSelector = createAtomSelector<- FlatAgentChatThread[]+ AgentChatThreadRecord[]>({key: 'agentChatVisibleThreadsSelector',get: ({ get }) => {- const storeItem = get(metadataStoreState, 'agentChatThreads');- const allThreads = storeItem.current as FlatAgentChatThread[];+ const allThreads = get(agentChatThreadsSelector);const filterStatus = get(agentChatThreadFilterStatusState);const lastActivityFilter = get(agentChatThreadLastActivityFilterState);const lastActivityDays =@@ -38,9 +37,7 @@ export const agentChatVisibleThreadsSelector = createAtomSelector<}if (cutoffMs !== null) {- const lastActivityMs = new Date(- thread.lastMessageAt ?? thread.updatedAt,- ).getTime();+ const lastActivityMs = new Date(thread.updatedAt).getTime();if (lastActivityMs < cutoffMs) return false;}diff --git a/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.tsindex 8195c138e5a..310775c1aae 100644--- a/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.ts+++ b/packages/twenty-front/src/modules/ai/states/selectors/currentAiChatThreadDataSelector.ts@@ -1,17 +1,17 @@import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';+import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';export const currentAiChatThreadDataSelector = createAtomSelector<- FlatAgentChatThread | undefined+ AgentChatThreadRecord | undefined>({key: 'currentAiChatThreadDataSelector',get: ({ get }) => {const currentThreadId = get(currentAiChatThreadState);- const storeItem = get(metadataStoreState, 'agentChatThreads');- const threads = storeItem.current as FlatAgentChatThread[];- return threads.find((thread) => thread.id === currentThreadId);+ return get(agentChatThreadsSelector).find(+ (thread) => thread.id === currentThreadId,+ );},});diff --git a/packages/twenty-front/src/modules/ai/testing/setAgentChatThreadList.ts b/packages/twenty-front/src/modules/ai/testing/setAgentChatThreadList.tsnew file mode 100644index 00000000000..829ae373837--- /dev/null+++ b/packages/twenty-front/src/modules/ai/testing/setAgentChatThreadList.ts@@ -0,0 +1,21 @@+import { type createStore } from 'jotai';++import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';++export const setAgentChatThreadList = (+ store: ReturnType<typeof createStore>,+ threads: AgentChatThreadRecord[],+ { hasNextPage = false }: { hasNextPage?: boolean } = {},+) => {+ for (const thread of threads) {+ store.set(recordStoreFamilyState.atomFamily(thread.id), thread);+ }++ store.set(agentChatThreadListState.atom, {+ threadIds: threads.map(({ id }) => id),+ hasNextPage,+ endCursor: hasNextPage ? 'cursor' : null,+ });+};diff --git a/packages/twenty-front/src/modules/ai/types/AgentChatThreadRecord.ts b/packages/twenty-front/src/modules/ai/types/AgentChatThreadRecord.tsindex 5b94fc186e6..0702cd884e1 100644--- a/packages/twenty-front/src/modules/ai/types/AgentChatThreadRecord.ts+++ b/packages/twenty-front/src/modules/ai/types/AgentChatThreadRecord.ts@@ -3,5 +3,13 @@ import { type ObjectRecord } from '@/object-record/types/ObjectRecord';export type AgentChatThreadRecord = ObjectRecord & {title: string | null;deletedAt: string | null;+ createdAt: string;updatedAt: string;+ totalInputTokens?: number;+ totalOutputTokens?: number;+ totalCacheReadTokens?: number;+ contextWindowTokens?: number | null;+ conversationSize?: number;+ totalInputCredits?: number | string;+ totalOutputCredits?: number | string;};diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.tsnew file mode 100644index 00000000000..a9a4c701464--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/buildAgentChatThreadListFilter.test.ts@@ -0,0 +1,27 @@+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';+import { buildAgentChatThreadListFilter } from '@/ai/utils/buildAgentChatThreadListFilter';++const INCLUDE_DELETED_FILTER = {+ or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],+};++const buildChatObject = (fieldNames: string[]) =>+ ({+ fields: fieldNames.map((name) => ({ name })),+ }) as Pick<EnrichedObjectMetadataItem, 'fields'>;++describe('buildAgentChatThreadListFilter', () => {+ it('lists deleted chats so they can be restored', () => {+ expect(buildAgentChatThreadListFilter(buildChatObject(['title']))).toEqual(+ INCLUDE_DELETED_FILTER,+ );+ });++ it('leaves workflow run conversations out once chats can name a run', () => {+ expect(+ buildAgentChatThreadListFilter(buildChatObject(['title', 'workflowRun'])),+ ).toEqual({+ and: [{ workflowRunId: { is: 'NULL' } }, INCLUDE_DELETED_FILTER],+ });+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.tsindex ee4920e110a..f899acdff02 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatUsageFromThread.test.ts@@ -6,12 +6,12 @@ const storedThread = {totalInputTokens: 250,totalOutputTokens: 30,totalCacheReadTokens: 80,- totalInputCredits: 0.125,- totalOutputCredits: 0.05,+ totalInputCredits: '125000',+ totalOutputCredits: 50000,};describe('getAgentChatUsageFromThread', () => {- it('restores cumulative usage without restoring the last message', () => {+ it('restores cumulative usage in display credits without the last message', () => {expect(getAgentChatUsageFromThread(storedThread)).toEqual({conversationSize: 120,contextWindowTokens: 1000,diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.tsindex bf0b2ab69dc..5c893dea570 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/groupThreadsByDate.test.ts@@ -1,4 +1,4 @@-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { groupThreadsByDate } from '@/ai/utils/groupThreadsByDate';describe('groupThreadsByDate', () => {@@ -17,26 +17,13 @@ describe('groupThreadsByDate', () => {const eightDaysAgo = getDateDaysAgo(8);const fourteenDaysAgo = getDateDaysAgo(14);- const baseThread: Omit<- AgentChatThread,- 'updatedAt' | 'id' | 'lastMessageAt'- > = {+ const buildThread = (id: string, updatedAt: Date): AgentChatThreadRecord => ({+ __typename: 'AgentChatThread',+ id,title: 'Test Thread',createdAt: twoDaysAgo.toISOString(),- totalInputTokens: 0,- totalOutputTokens: 0,- totalCacheReadTokens: 0,- contextWindowTokens: null,- conversationSize: 0,- totalInputCredits: 0,- totalOutputCredits: 0,- };-- const buildThread = (id: string, lastMessageAt: Date): AgentChatThread => ({- ...baseThread,- id,- lastMessageAt: lastMessageAt.toISOString(),- updatedAt: lastMessageAt.toISOString(),+ deletedAt: null,+ updatedAt: updatedAt.toISOString(),});it('groups threads into Today, Yesterday, Previous 7 days, and month sections', () => {@@ -45,7 +32,7 @@ describe('groupThreadsByDate', () => {year: 'numeric',});- const threads: AgentChatThread[] = [+ const threads: AgentChatThreadRecord[] = [buildThread('1', today),buildThread('2', yesterday),buildThread('3', twoDaysAgo),@@ -83,15 +70,8 @@ describe('groupThreadsByDate', () => {expect(groupThreadsByDate([], today)).toEqual([]);});- it('falls back to updatedAt when lastMessageAt is null', () => {- const thread: AgentChatThread = {- ...baseThread,- id: '1',- lastMessageAt: null,- updatedAt: yesterday.toISOString(),- };-- const [group] = groupThreadsByDate([thread], today);+ it('groups a thread by its last update', () => {+ const [group] = groupThreadsByDate([buildThread('1', yesterday)], today);expect(group.id).toBe('yesterday');});diff --git a/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.tsnew file mode 100644index 00000000000..7d2ae616c19--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/buildAgentChatThreadListFilter.ts@@ -0,0 +1,20 @@+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';+import { type RecordGqlOperationFilter } from 'twenty-shared/types';++// Deleted chats stay listed so they can be restored. Anyone who reads a+// workflow run reads its agent's conversations, which belong to the run+// rather than to the chat list+export const buildAgentChatThreadListFilter = (+ chatObjectMetadataItem: Pick<EnrichedObjectMetadataItem, 'fields'>,+): RecordGqlOperationFilter => {+ const includeDeletedFilter: RecordGqlOperationFilter = {+ or: [{ deletedAt: { is: 'NULL' } }, { deletedAt: { is: 'NOT_NULL' } }],+ };+ const canNameWorkflowRun = chatObjectMetadataItem.fields.some(+ ({ name }) => name === 'workflowRun',+ );++ return canNameWorkflowRun+ ? { and: [{ workflowRunId: { is: 'NULL' } }, includeDeletedFilter] }+ : includeDeletedFilter;+};diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.tsindex 7f0789bfff5..f60bca7e1c2 100644--- a/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.ts+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatUsageFromThread.ts@@ -1,30 +1,38 @@+import { INTERNAL_CREDITS_PER_DISPLAY_CREDIT } from 'twenty-shared/constants';import { isDefined } from 'twenty-shared/utils';+import { type AgentChatUsageState } from '@/ai/states/agentChatUsageComponentFamilyState';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';++const toDisplayCredits = (internalCredits: number | string | undefined) =>+ Number(internalCredits ?? 0) / INTERNAL_CREDITS_PER_DISPLAY_CREDIT;export const getAgentChatUsageFromThread = (thread: Pick<- AgentChatThread,- | 'totalCacheReadTokens'+ AgentChatThreadRecord,| 'conversationSize'| 'contextWindowTokens'+ | 'totalCacheReadTokens'| 'totalInputTokens'| 'totalOutputTokens'| 'totalInputCredits'| 'totalOutputCredits'>,): AgentChatUsageState | null => {- if (thread.conversationSize <= 0 || !isDefined(thread.contextWindowTokens)) {+ const conversationSize = thread.conversationSize ?? 0;++ if (conversationSize <= 0 || !isDefined(thread.contextWindowTokens)) {return null;}+return {lastMessage: null,- cachedInputTokens: thread.totalCacheReadTokens,- conversationSize: thread.conversationSize,+ cachedInputTokens: thread.totalCacheReadTokens ?? 0,+ conversationSize,contextWindowTokens: thread.contextWindowTokens,- inputTokens: thread.totalInputTokens,- outputTokens: thread.totalOutputTokens,- inputCredits: thread.totalInputCredits,- outputCredits: thread.totalOutputCredits,+ inputTokens: thread.totalInputTokens ?? 0,+ outputTokens: thread.totalOutputTokens ?? 0,+ inputCredits: toDisplayCredits(thread.totalInputCredits),+ outputCredits: toDisplayCredits(thread.totalOutputCredits),};};diff --git a/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts b/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.tsindex 084a3c718a4..a6a25bc5861 100644--- a/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts+++ b/packages/twenty-front/src/modules/ai/utils/groupThreadsByDate.ts@@ -1,12 +1,12 @@import { t } from '@lingui/core/macro';import { differenceInCalendarDays } from 'date-fns';-import { type AgentChatThread } from '~/generated-metadata/graphql';+import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';export type AgentChatThreadDateGroup = {id: string;title: string;- threads: AgentChatThread[];+ threads: AgentChatThreadRecord[];};const getLocalDayDifference = (date: Date, today: Date) =>@@ -55,14 +55,14 @@ const getThreadDateGroup = (};export const groupThreadsByDate = (- threads: AgentChatThread[],+ threads: AgentChatThreadRecord[],today = new Date(),): AgentChatThreadDateGroup[] => {const groupedThreadsByDate = new Map<string, AgentChatThreadDateGroup>();for (const thread of threads) {const threadDateGroup = getThreadDateGroup(- new Date(thread.lastMessageAt ?? thread.updatedAt),+ new Date(thread.updatedAt),today,);const existingThreadDateGroup = groupedThreadsByDate.get(diff --git a/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts b/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.tsindex 95f62586240..1a69299a85d 100644--- a/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts+++ b/packages/twenty-front/src/modules/ai/utils/sortChatThreadsByLastActivityDesc.ts@@ -1,10 +1,11 @@type ThreadWithLastActivity = {- lastMessageAt?: string | Date | null;updatedAt: string | Date;};+// Sending a message touches its conversation, so updatedAt is its last+// activityconst getLastActivityMs = (thread: ThreadWithLastActivity): number =>- new Date(thread.lastMessageAt ?? thread.updatedAt).getTime();+ new Date(thread.updatedAt).getTime();export const sortChatThreadsByLastActivityDesc = <T extends ThreadWithLastActivity,diff --git a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.tsindex d5a957f9e01..bb1aa2f926c 100644--- a/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts+++ b/packages/twenty-front/src/modules/browser-event/types/BroadcastEntityName.ts@@ -4,7 +4,6 @@ import { type AllMetadataName } from 'twenty-shared/metadata';// event stream via WorkspaceEventBroadcaster, but are NOT part of the// workspace migration / syncable entity system (ALL_METADATA_NAME).const ALL_NON_SYNCABLE_BROADCAST_ENTITY_NAME = {- agentChatThread: 'agentChatThread',application: 'application',applicationRegistration: 'applicationRegistration',} as const;diff --git a/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts b/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.tsindex a286bb0dea3..77d25915af6 100644--- a/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts+++ b/packages/twenty-front/src/modules/browser-event/types/MetadataOperationBrowserEventDetail.ts@@ -5,7 +5,7 @@ import { type BroadcastEntityName } from '@/browser-event/types/BroadcastEntityN// (MetadataOperation, MetadataOperationBrowserEventDetail, etc.) because it// originally only carried events for syncable metadata entities (views, fields,// etc.). With WorkspaceEventBroadcaster, non-syncable entities like-// agentChatThread also broadcast through the same SSE stream.+// applications also broadcast through the same SSE stream.// BroadcastEntityName captures this distinction at the type level, but the// naming of the surrounding types/hooks/files still says "Metadata." A future// rename of this layer (e.g. Metadata* → Entity* or Broadcast*) would makediff --git a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.tsindex ef0bf783fc4..8847ecd6d48 100644--- a/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts+++ b/packages/twenty-front/src/modules/metadata-store/states/metadataStoreState.ts@@ -33,7 +33,6 @@ export const ALL_METADATA_ENTITY_KEYS = ['rowLevelPermissionPredicateGroups',// TODO: clarify what really is metadata (syncable entity?)// vs 'core engine entity' or 'broadcastable entity'- 'agentChatThreads','applications',] as const;diff --git a/packages/twenty-front/src/modules/metadata-store/types/FlatAgentChatThread.ts b/packages/twenty-front/src/modules/metadata-store/types/FlatAgentChatThread.tsdeleted file mode 100644index aa9f7d128b8..00000000000--- a/packages/twenty-front/src/modules/metadata-store/types/FlatAgentChatThread.ts+++ /dev/null@@ -1,3 +0,0 @@-import { type AgentChatThread } from '~/generated-metadata/graphql';--export type FlatAgentChatThread = AgentChatThread;diff --git a/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts b/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.tsindex 85446445c77..2170e11aead 100644--- a/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts+++ b/packages/twenty-front/src/modules/metadata-store/types/MetadataEntityTypeMap.ts@@ -1,5 +1,4 @@import { type FlatAgent } from '@/metadata-store/types/FlatAgent';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';import { type FlatApplication } from '@/metadata-store/types/FlatApplication';import { type FlatCommandMenuItem } from '@/metadata-store/types/FlatCommandMenuItem';import { type FlatFieldMetadataItem } from '@/metadata-store/types/FlatFieldMetadataItem';@@ -50,6 +49,5 @@ export type MetadataEntityTypeMap = {skills: FlatSkill;rowLevelPermissionPredicates: FlatRowLevelPermissionPredicate;rowLevelPermissionPredicateGroups: FlatRowLevelPermissionPredicateGroup;- agentChatThreads: FlatAgentChatThread;applications: FlatApplication;};diff --git a/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts b/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.tsindex d1a2fe187c9..1ce87553d2e 100644--- a/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts+++ b/packages/twenty-front/src/modules/metadata-store/utils/mapAllMetadataNameToEntityKey.ts@@ -25,7 +25,6 @@ const METADATA_NAME_TO_ENTITY_KEY: Record<string, MetadataEntityKey> = {navigationMenuItem: 'navigationMenuItems',frontComponent: 'frontComponents',webhook: 'webhooks',- agentChatThread: 'agentChatThreads',application: 'applications',};diff --git a/packages/twenty-front/src/modules/navigation/components/__stories__/MainNavigationDrawerContent.stories.tsx b/packages/twenty-front/src/modules/navigation/components/__stories__/MainNavigationDrawerContent.stories.tsxindex 596ef2163ba..068fa734a27 100644--- a/packages/twenty-front/src/modules/navigation/components/__stories__/MainNavigationDrawerContent.stories.tsx+++ b/packages/twenty-front/src/modules/navigation/components/__stories__/MainNavigationDrawerContent.stories.tsx@@ -7,9 +7,9 @@ import { ComponentDecorator } from 'twenty-ui/testing';import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';import { setAgentChatThreadPermissions } from '@/ai/testing/setAgentChatThreadPermissions';import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';-import { metadataStoreState } from '@/metadata-store/states/metadataStoreState';import { MainNavigationDrawerContent } from '@/navigation/components/MainNavigationDrawerContent';import { isNavigationDrawerExpandedState } from '@/ui/navigation/states/isNavigationDrawerExpanded';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';@@ -17,23 +17,20 @@ import { PermissionFlagType } from '~/generated-metadata/graphql';import { IconsProviderDecorator } from '~/testing/decorators/IconsProviderDecorator';import { ToastDecorator } from '~/testing/decorators/ToastDecorator';+const THREAD_PERMISSIONS = {+ canRead: true,+ canUpdate: true,+ canDelete: true,+ canSoftDelete: true,+};+const THREAD = {- permissions: {- canRead: true,- canUpdate: true,- canDelete: true,- canSoftDelete: true,- },+ __typename: 'AgentChatThread',id: '3a36fc8c-c8e2-4f16-a283-24dc05e3704b',title: 'Pipeline summary',+ deletedAt: null,createdAt: '2026-01-01T12:00:00.000Z',updatedAt: '2026-01-01T12:00:00.000Z',- conversationSize: 0,- totalCacheReadTokens: 0,- totalInputCredits: 0,- totalInputTokens: 0,- totalOutputCredits: 0,- totalOutputTokens: 0,};const ContentWithCollapseControl = () => {@@ -61,17 +58,13 @@ const AiNavigationContent = () => {isImpersonating: false,twoFactorAuthenticationMethodSummary: null,});- initialStore.set(metadataStoreState.atomFamily('agentChatThreads'), {- current: [THREAD],- draft: [],- status: 'up-to-date',- });+ setAgentChatThreadList(initialStore, [THREAD]);return initialStore;});// Persisted auth atoms must hydrate before capturing the permission snapshot.useEffect(() => {- setAgentChatThreadPermissions(store, THREAD.id, THREAD.permissions);+ setAgentChatThreadPermissions(store, THREAD.id, THREAD_PERMISSIONS);}, [store]);return (diff --git a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx b/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsxindex 069900d480a..2e903571bfe 100644--- a/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx+++ b/packages/twenty-front/src/modules/onboarding/effect-components/WorkspaceSetupChatKickoffEffect.tsx@@ -1,3 +1,4 @@+import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';import { useMutation } from '@apollo/client/react';import { useStore } from 'jotai';@@ -10,8 +11,6 @@ import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { currentAiChatThreadTitleComponentFamilyState } from '@/ai/states/currentAiChatThreadTitleComponentFamilyState';import { hasInitializedAgentChatThreadsState } from '@/ai/states/hasInitializedAgentChatThreadsState';import { skipMessagesSkeletonUntilLoadedState } from '@/ai/states/skipMessagesSkeletonUntilLoadedState';-import { useUpdateMetadataStoreDraft } from '@/metadata-store/hooks/useUpdateMetadataStoreDraft';-import { type FlatAgentChatThread } from '@/metadata-store/types/FlatAgentChatThread';import { WORKSPACE_SETUP_CHAT_ENRICHMENT_MAX_WAIT_MS } from '@/onboarding/constants/WorkspaceSetupChatEnrichmentMaxWaitMs';import { shouldOpenAiChatAfterOnboardingState } from '@/onboarding/states/shouldOpenAiChatAfterOnboardingState';import { companyEnrichmentState } from '@/onboarding/states/companyEnrichmentState';@@ -31,7 +30,7 @@ export const WorkspaceSetupChatKickoffEffect = () => {const store = useStore();const { refreshAgentChatThreadPermissions } =useRefreshAgentChatThreadPermissions();- const { addToDraft, applyChanges } = useUpdateMetadataStoreDraft();+ const { addAgentChatThread } = useApplyAgentChatThreadUpdate();const isCompanyEnrichmentFetchInFlight = useAtomStateValue(isCompanyEnrichmentFetchInFlightState,);@@ -89,23 +88,13 @@ export const WorkspaceSetupChatKickoffEffect = () => {return;}- const workspaceSetupThread: FlatAgentChatThread = {+ addAgentChatThread({id: thread.id,-title: thread.title ?? null,createdAt: thread.createdAt,updatedAt: thread.updatedAt,- conversationSize: thread.conversationSize,- contextWindowTokens: thread.contextWindowTokens ?? null,- totalCacheReadTokens: thread.totalCacheReadTokens,- totalInputTokens: thread.totalInputTokens,- totalOutputTokens: thread.totalOutputTokens,- totalInputCredits: thread.totalInputCredits,- totalOutputCredits: thread.totalOutputCredits,- };-- addToDraft({ key: 'agentChatThreads', items: [workspaceSetupThread] });- applyChanges();+ deletedAt: null,+ });void refreshAgentChatThreadPermissions([thread.id]);store.set(@@ -141,8 +130,7 @@ export const WorkspaceSetupChatKickoffEffect = () => {startWorkspaceSetupChatMutation,refreshAgentChatThreadPermissions,store,- addToDraft,- applyChanges,+ addAgentChatThread,isCompanyEnrichmentFetchInFlight,hasWaitedForCompanyEnrichment,]);diff --git a/packages/twenty-front/src/modules/onboarding/effect-components/__tests__/WorkspaceSetupChatKickoffEffect.test.tsx b/packages/twenty-front/src/modules/onboarding/effect-components/__tests__/WorkspaceSetupChatKickoffEffect.test.tsxindex 85830cd28d7..5ad7c1d6c49 100644--- a/packages/twenty-front/src/modules/onboarding/effect-components/__tests__/WorkspaceSetupChatKickoffEffect.test.tsx+++ b/packages/twenty-front/src/modules/onboarding/effect-components/__tests__/WorkspaceSetupChatKickoffEffect.test.tsx@@ -83,7 +83,6 @@ const buildKickoffMock = ({totalInputCredits: 0,totalOutputCredits: 0,deletedAt: null,- lastMessageAt: null,createdAt: '2026-07-21T10:00:00.000Z',updatedAt: '2026-07-21T10:00:00.000Z',},diff --git a/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts b/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.tsindex 31bbafe7f1d..ba349176245 100644--- a/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts+++ b/packages/twenty-front/src/modules/onboarding/graphql/mutations/startWorkspaceSetupChat.ts@@ -21,7 +21,6 @@ export const START_WORKSPACE_SETUP_CHAT = gql`totalInputCreditstotalOutputCreditsdeletedAt- lastMessageAtcreatedAtupdatedAt}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 e6793382d89..248161b31e7 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@@ -231,7 +231,6 @@ const SCHEMA = getWorkspaceSchemaName(WORKSPACE_ID);),{} as never,{} as never,- { broadcast: jest.fn().mockResolvedValue(undefined) } as never,{getThreadWithAccess: ({workspaceId,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.tsindex ebacf77bfa7..246c2c934e1 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread.dto.ts@@ -39,7 +39,4 @@ export class AgentChatThreadDTO {@Field(() => Date, { nullable: true })deletedAt: Date | null;-- @Field(() => Date, { nullable: true })- lastMessageAt: Date | null;}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.tsindex 0f39473b89a..b439ef3ff1a 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/__tests__/agent-chat.resolver.sharing.spec.ts@@ -58,7 +58,6 @@ const buildResolver = () => {new AiException('Thread not found', AiExceptionCode.THREAD_NOT_FOUND),),};- const broadcaster = { broadcast: jest.fn() };const recordEvents = {emitThreadCreated: jest.fn(),emitThreadUpdated: jest.fn(),@@ -71,7 +70,6 @@ const buildResolver = () => {{} as never,{} as never,{} as never,- broadcaster as never,sharing as never,recordEvents as never,);@@ -120,7 +118,6 @@ const buildResolver = () => {streaming,events,redis,- broadcaster,recordEvents,};};@@ -144,7 +141,6 @@ describe('Shared conversation API boundaries', () => {workspaceId: WORKSPACE_ID,}),).rejects.toThrow('restore failed');- expect(context.broadcaster.broadcast).not.toHaveBeenCalled();expect(context.recordEvents.emitThreadUpdated).not.toHaveBeenCalled();});@@ -238,7 +234,6 @@ describe('Shared conversation API boundaries', () => {}expect(context.threadRepository.update).not.toHaveBeenCalled();expect(context.threadRepository.delete).not.toHaveBeenCalled();- expect(context.broadcaster.broadcast).not.toHaveBeenCalled();expect(context.recordEvents.emitThreadUpdated).not.toHaveBeenCalled();expect(context.messages.delete).not.toHaveBeenCalled();expect(context.streaming.streamAgentChat).not.toHaveBeenCalled();diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.tsindex 603e1d8e1d3..324b4af487b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat.resolver.ts@@ -22,7 +22,6 @@ import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-displayimport { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';-import { AllowSuspendedWorkspace } from 'src/engine/decorators/auth/allow-suspended-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';import { AgentMessageDTO } from 'src/engine/metadata-modules/ai/ai-agent-execution/dtos/agent-message.dto';@@ -71,18 +70,6 @@ export class AgentChatResolver {private readonly threadLifecycleService: AgentChatThreadLifecycleService,) {}- @Query(() => [AgentChatThreadDTO])- @AllowSuspendedWorkspace()- async chatThreads(- @AuthWorkspaceMemberId() workspaceMemberId: string,- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,- ) {- return this.agentChatService.getThreadsForMember({- workspaceMemberId,- workspaceId,- });- }-@Query(() => AgentChatThreadDTO)async chatThread(@Args('id', { type: () => UUIDScalarType }) id: string,@@ -397,20 +384,4 @@ export class AgentChatResolver {totalOutputCredits(@Parent() thread: AgentChatThreadWorkspaceEntity): number {return toDisplayCredits(Number(thread.totalOutputCredits));}-- @ResolveField('lastMessageAt', () => Date, { nullable: true })- async lastMessageAt(- @Parent()- thread: AgentChatThreadWorkspaceEntity & { lastMessageAt?: Date | null },- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,- ): Promise<Date | null> {- if (thread.lastMessageAt !== undefined) {- return thread.lastMessageAt;- }-- return this.agentChatService.getLastMessageAtForThread({- threadId: thread.id,- workspaceId,- });- }}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.tsindex b39a6e2b2f7..f4fbadee29e 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts@@ -183,14 +183,6 @@ describe('Conversation common record access', () => {});});- it('lists soft deleted conversations so they can be restored', async () => {- const { service, repository } = buildService();- await service.getReadableThreadIds(args);- expect(repository.find).toHaveBeenCalledWith(- expect.objectContaining({ withDeleted: true }),- );- });-it('restores a soft deleted conversation through the restore permission', async () => {const { service, query, repository } = buildService();const deletedThread = {@@ -318,27 +310,8 @@ describe('Conversation common record access', () => {});});- it.each([MetadataReadability.SYSTEM, MetadataReadability.PRIVATE])(- 'bounds the readable thread list before ranking for %s metadata',- async (readability) => {- const { service, repository, objectMetadata, sharing } = buildService();- objectMetadata.readability = readability;- await service.getReadableThreadIds(args);- expect(repository.find).toHaveBeenCalledWith(- expect.objectContaining({- take: 1000,- order: { updatedAt: 'DESC', id: 'DESC' },- }),- );- expect(sharing.getPermissionsForRecords).not.toHaveBeenCalled();- },- );-- it('batches capabilities and lists only records admitted by the ordinary repository', async () => {+ it('batches capabilities', async () => {const { service, sharing } = buildService();- await expect(service.getReadableThreadIds(args)).resolves.toEqual([- THREAD_ID,- ]);await service.getPermissionsForThreads({ ...args, threadIds: [THREAD_ID] });expect(sharing.getPermissionsForRecords).toHaveBeenCalledTimes(1);});@@ -353,21 +326,4 @@ describe('Conversation common record access', () => {).resolves.toBe(thread);},);-- it('leaves workflow run conversations out of the chat list once threads can name a run', async () => {- const { service, repository, flatFieldMetadataMaps } = buildService();- await service.getReadableThreadIds(args);- expect(repository.find).toHaveBeenLastCalledWith(- expect.objectContaining({ where: undefined }),- );- flatFieldMetadataMaps.byUniversalIdentifier[- STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier- ] = {};- await service.getReadableThreadIds(args);- expect(repository.find).toHaveBeenLastCalledWith(- expect.objectContaining({- where: { workflowRunId: expect.objectContaining({ _type: 'isNull' }) },- }),- );- });});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.tsindex cbc5b2839c1..80af64f135b 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.get-messages.spec.ts@@ -17,7 +17,6 @@ const buildService = () => {{} as never,{} as never,{} as never,- {} as never,{getThreadWithAccess: jest.fn().mockResolvedValue({ id: THREAD_ID }),getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.tsindex 22bebe0a095..44dc483b605 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat.service.kickoff-message.spec.ts@@ -34,7 +34,6 @@ const buildService = ({ existingHiddenMessage = null as unknown } = {}) => {messagePartRepository as never,{} as never,{} as never,- {} as never,{getReadableThread: jest.fn().mockResolvedValue({ id: THREAD_ID }),} as never,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.tsindex c66df8dc644..c02ebf14ce0 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts@@ -1,5 +1,4 @@import { lockAgentChatThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util';-import { IsNull } from 'typeorm';import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';import { AuthException } from 'src/engine/core-modules/auth/auth.exception';import { randomUUID } from 'node:crypto';@@ -16,7 +15,6 @@ import { type RecordPermissionsDTO } from 'src/engine/core-modules/record-share/import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';-import { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import {AiException,@@ -27,8 +25,6 @@ import { type OperationType } from 'src/engine/twenty-orm/repository/permissionsimport { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';-const MAX_CHAT_THREADS = 1000;-type ThreadAccessArgs = {workspaceId: string;workspaceMemberId: string;@@ -106,33 +102,6 @@ export class AgentChatSharingService {});}- async getReadableThreadIds(- args: Omit<ThreadAccessArgs, 'threadId'>,- ): Promise<string[]> {- const authContext = await this.getAuthContext(args);- const { flatFieldMetadataMaps } =- await this.workspaceCacheService.getOrRecompute(args.workspaceId, [- 'flatFieldMetadataMaps',- ]);-- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const records = await this.workspaceOrmManager- .getRepositoryWithContextPermissions('agentChatThread')- .find({- // Anyone who reads a run reads its agent's conversations, so without- // this every run would crowd into every member's own chats.- where: hasWorkflowRunThreadFields(flatFieldMetadataMaps)- ? { workflowRunId: IsNull() }- : undefined,- select: { id: true },- withDeleted: true,- order: { updatedAt: 'DESC', id: 'DESC' },- take: MAX_CHAT_THREADS,- });- return records.map(({ id }) => id);- }, authContext);- }-async createThread(args: {workspaceId: string;workspaceMemberId: string;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.tsindex c4dcfbfd701..d8b9fc8a485 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat.service.ts@@ -26,14 +26,11 @@ import {AiException,AiExceptionCode,} from 'src/engine/metadata-modules/ai/ai.exception';-import { WorkspaceEventBroadcaster } from 'src/engine/subscriptions/workspace-event-broadcaster/workspace-event-broadcaster.service';import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';-import { serializeAgentChatThreadForBroadcast } from 'src/engine/metadata-modules/ai/ai-chat/utils/serialize-agent-chat-thread-for-broadcast.util';import { AiChatFileAttachment } from 'src/engine/metadata-modules/ai/ai-chat/types/ai-chat-file-attachment.type';import { AgentChatThreadRecordEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-record-event.service';import { AgentTitleGenerationService } from './agent-title-generation.service';-import { AgentChatThreadDTO } from '../dtos/agent-chat-thread.dto';import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';@Injectable()@@ -52,7 +49,6 @@ export class AgentChatService {@InjectWorkspaceScopedRepository(FileEntity)private readonly fileRepository: WorkspaceScopedRepository<FileEntity>,private readonly titleGenerationService: AgentTitleGenerationService,- private readonly workspaceEventBroadcaster: WorkspaceEventBroadcaster,private readonly sharingService: AgentChatSharingService,private readonly threadRecordEventService: AgentChatThreadRecordEventService,) {}@@ -68,10 +64,6 @@ export class AgentChatService {id?: string;title?: string;}) {- const authContext = await this.sharingService.getAuthContext({- workspaceId,- workspaceMemberId,- });const savedThread = await this.sharingService.createThread({workspaceId,workspaceMemberId,@@ -79,24 +71,6 @@ export class AgentChatService {title,});- await this.workspaceEventBroadcaster.broadcast({- workspaceId,- events: [- {- type: 'created',- entityName: 'agentChatThread',- recordId: savedThread.id,- recipientUserWorkspaceIds: [authContext.userWorkspaceId],- properties: {- after: serializeAgentChatThreadForBroadcast({- thread: savedThread,- lastMessageAt: null,- }),- },- },- ],- });-await this.threadRecordEventService.emitThreadCreated({workspaceId,threadId: savedThread.id,@@ -143,80 +117,6 @@ export class AgentChatService {});}- async getThreadsForMember({- workspaceMemberId,- workspaceId,- }: {- workspaceMemberId: string;- workspaceId: string;- }): Promise<- (AgentChatThreadWorkspaceEntity & { lastMessageAt: Date | null })[]- > {- const readableThreadIds = await this.sharingService.getReadableThreadIds({- workspaceId,- workspaceMemberId,- });- const rankedThreads = await this.threadRepository.query(- workspaceId,- ({ manager, table }) =>- manager.query<{ id: string; last_message_at: Date | null }[]>(- `SELECT thread.id, MAX(message."createdAt") AS last_message_at- FROM ${table('agentChatThread')} thread- LEFT JOIN ${table('agentMessage')} message ON message."threadId" = thread.id AND message."isHidden" = false- WHERE thread.id = ANY($1::uuid[])- GROUP BY thread.id ORDER BY last_message_at DESC NULLS LAST, thread."updatedAt" DESC`,- [readableThreadIds],- ),- );-- if (rankedThreads.length === 0) {- return [];- }-- const rankedThreadIds = rankedThreads.map(- (rankedThread) => rankedThread.id,- );-- const threads = await this.threadRepository.find(workspaceId, {- where: { id: In(rankedThreadIds) },- });-- const threadById = new Map(threads.map((thread) => [thread.id, thread]));-- return rankedThreads.flatMap((rankedThread) => {- const thread = threadById.get(rankedThread.id);-- return isDefined(thread)- ? [- {- ...thread,- lastMessageAt: rankedThread.last_message_at ?? null,- },- ]- : [];- });- }-- async getLastMessageAtForThread({- threadId,- workspaceId,- }: {- threadId: string;- workspaceId: string;- }): Promise<Date | null> {- const [result] = await this.messageRepository.query(- workspaceId,- ({ manager, table }) =>- manager.query<{ last_message_at: Date | null }[]>(- `SELECT MAX("createdAt") AS last_message_at FROM ${table('agentMessage')}- WHERE "threadId" = $1 AND "isHidden" = false`,- [threadId],- ),- );-- return result?.last_message_at ?? null;- }-private getMessageSenderValues({workspaceId,userWorkspaceId,@@ -754,12 +654,6 @@ export class AgentChatService {workspaceId,});- await this.broadcastThreadUpdated(- thread,- workspaceId,- ['deletedAt'],- workspaceMemberId,- );if (isDefined(threadBefore)) {await this.threadRecordEventService.emitThreadUpdated({workspaceId,@@ -796,12 +690,6 @@ export class AgentChatService {{ updatedAt: threadAfter.updatedAt },);- await this.broadcastThreadUpdated(- threadAfter,- workspaceId,- ['lastMessageAt'],- workspaceMemberId,- );await this.threadRecordEventService.emitThreadUpdated({workspaceId,threadBefore: thread,@@ -825,19 +713,6 @@ export class AgentChatService {workspaceId,});- await this.broadcastThreadUpdated(- thread,- workspaceId,- [- 'totalInputTokens',- 'totalOutputTokens',- 'totalInputCredits',- 'totalOutputCredits',- 'conversationSize',- 'contextWindowTokens',- ],- workspaceMemberId,- );await this.threadRecordEventService.emitThreadUpdated({workspaceId,threadBefore,@@ -845,49 +720,6 @@ export class AgentChatService {});}- private async broadcastThreadUpdated(- thread: AgentChatThreadWorkspaceEntity,- workspaceId: string,- updatedFields: (keyof AgentChatThreadDTO)[],- workspaceMemberId: string,- ): Promise<void> {- const authContext = await this.sharingService.getAuthContext({- workspaceId,- workspaceMemberId,- });- const permissions = await this.sharingService.getPermissions({- workspaceId,- workspaceMemberId,- threadId: thread.id,- });- if (!permissions.canRead) {- return;- }- const lastMessageAt = await this.getLastMessageAtForThread({- threadId: thread.id,- workspaceId,- });-- await this.workspaceEventBroadcaster.broadcast({- workspaceId,- events: [- {- type: 'updated',- entityName: 'agentChatThread',- recordId: thread.id,- recipientUserWorkspaceIds: [authContext.userWorkspaceId],- properties: {- updatedFields,- after: serializeAgentChatThreadForBroadcast({- thread,- lastMessageAt,- }),- },- },- ],- });- }-async generateTitleIfNeeded({threadId,messageContent,@@ -923,12 +755,6 @@ export class AgentChatService {{ title },);- await this.broadcastThreadUpdated(- { ...thread, title },- workspaceId,- ['title'],- workspaceMemberId,- );await this.threadRecordEventService.emitThreadUpdated({workspaceId,threadBefore: thread,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/serialize-agent-chat-thread-for-broadcast.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/serialize-agent-chat-thread-for-broadcast.util.spec.tsdeleted file mode 100644index 4950b1664a6..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/__tests__/serialize-agent-chat-thread-for-broadcast.util.spec.ts+++ /dev/null@@ -1,19 +0,0 @@-import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';-import { serializeAgentChatThreadForBroadcast } from 'src/engine/metadata-modules/ai/ai-chat/utils/serialize-agent-chat-thread-for-broadcast.util';--describe('Thread broadcasts', () => {- it('contains thread data without viewer-specific permissions', () => {- const thread = Object.assign(new AgentChatThreadWorkspaceEntity(), {- id: 'thread',- userWorkspaceId: 'owner',- totalInputCredits: 0,- totalOutputCredits: 0,- });- const broadcast = serializeAgentChatThreadForBroadcast({- thread,- lastMessageAt: null,- });- expect(broadcast).toMatchObject({ id: 'thread' });- expect(broadcast).not.toHaveProperty('permissions');- });-});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/serialize-agent-chat-thread-for-broadcast.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/serialize-agent-chat-thread-for-broadcast.util.tsdeleted file mode 100644index 51cb8b6f6ff..00000000000--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/serialize-agent-chat-thread-for-broadcast.util.ts+++ /dev/null@@ -1,26 +0,0 @@-import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';-import { toDisplayCredits } from 'src/engine/core-modules/usage/utils/to-display-credits.util';--export const serializeAgentChatThreadForBroadcast = ({- thread,- lastMessageAt,-}: {- thread: AgentChatThreadWorkspaceEntity;- lastMessageAt: Date | null;-}) => ({- id: thread.id,-- title: thread.title,- totalInputTokens: thread.totalInputTokens,- totalOutputTokens: thread.totalOutputTokens,- totalCacheReadTokens: Number(thread.totalCacheReadTokens),- totalCacheCreationTokens: Number(thread.totalCacheCreationTokens),- contextWindowTokens: thread.contextWindowTokens,- conversationSize: thread.conversationSize,- totalInputCredits: toDisplayCredits(Number(thread.totalInputCredits)),- totalOutputCredits: toDisplayCredits(Number(thread.totalOutputCredits)),- deletedAt: thread.deletedAt,- lastMessageAt,- createdAt: thread.createdAt,- updatedAt: thread.updatedAt,-});diff --git a/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts b/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.tsindex de167fdce5c..3f9a68da541 100644--- a/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts+++ b/packages/twenty-server/src/engine/subscriptions/workspace-event-broadcaster/types/workspace-broadcast-event.type.ts@@ -12,8 +12,8 @@ export type WorkspaceBroadcastEvent = {};// Restricts delivery to streams whose authContext.userWorkspaceId is in this// list. Omit for workspace-wide events (shared metadata like views, objects,- // fields). Set for user-scoped entities (e.g. agentChatThread) so other users- // in the same workspace don't receive them.+ // fields). Set for user-scoped entities so other users in the same+ // workspace don't receive them.recipientUserWorkspaceIds?: string[];// Restricts delivery to streams whose user holds this settings permission// flag. Metadata events are workspace-wide by default; entities whosediff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.tsindex ae73534ad86..5fc6bd76bf5 100644--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts@@ -8,6 +8,7 @@ import { updateOneOperationFactory } from 'test/integration/graphql/utils/updateimport { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';import { setManualRecordShare } from 'test/integration/utils/set-manual-record-share.util';import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';+import { listChatThreadIds } from 'test/integration/utils/list-chat-thread-ids.util';import { type AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-actor.service';import { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';import { type RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';@@ -197,16 +198,8 @@ describe('Conversation sharing through the authenticated API', () => {title: 'Private sharing regression',});const read = () => readThread(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN);- const listedThreadIds = async () => {- const response = await makeMetadataApiRequest(- { query: parse('query ReadableThreads { chatThreads { id } }') },- APPLE_JONY_MEMBER_ACCESS_TOKEN,- );- expect(response.body.errors).toBeUndefined();- return response.body.data.chatThreads.map(- ({ id }: { id: string }) => id,- );- };+ const listedThreadIds = () =>+ listChatThreadIds(APPLE_JONY_MEMBER_ACCESS_TOKEN);const changeShare = (enabled: boolean) =>makeMetadataApiRequest({query: SET_SHARE,@@ -586,11 +579,9 @@ describe('Conversation sharing through the authenticated API', () => {expect((await chatService.getWritableThread(owner)).deletedAt,).not.toBeNull();- expect(- (await chatService.getThreadsForMember(owner)).some(- ({ id }) => id === owner.threadId,- ),- ).toBe(true);+ expect(await listChatThreadIds(APPLE_JANE_ADMIN_ACCESS_TOKEN)).toContain(+ owner.threadId,+ );expect((await readThread(owner.threadId)).body.errors).toBeUndefined();const restoredTwice = await Promise.all([chatService.restoreThread(owner),diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.tsindex 2416ccbb403..91af1e7bbe8 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts@@ -7,6 +7,7 @@ import { WorkflowVisibility } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';import { createOneRole } from 'test/integration/metadata/suites/role/utils/create-one-role.util';+import { listChatThreadIds } from 'test/integration/utils/list-chat-thread-ids.util';import { deleteOneRole } from 'test/integration/metadata/suites/role/utils/delete-one-role.util';import { findOneRoleByLabel } from 'test/integration/metadata/suites/role/utils/find-one-role-by-label.util';import { updateWorkspaceMemberRole } from 'test/integration/metadata/suites/role/utils/update-workspace-member-role.util';@@ -893,14 +894,8 @@ describe('core workflow visibility (e2e)', () => {});it('keeps it out of the chat list of someone who can read it', async () => {- const response = await metadataRequestAs(- APPLE_JANE_ADMIN_ACCESS_TOKEN,- 'query ReadableThreads { chatThreads { id } }',- );-- expect(response.body.errors).toBeUndefined();expect(- response.body.data.chatThreads.map(({ id }: { id: string }) => id),+ await listChatThreadIds(APPLE_JANE_ADMIN_ACCESS_TOKEN),).not.toContain(threadId);});diff --git a/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.tsnew file mode 100644index 00000000000..1fe5040a3d3--- /dev/null+++ b/packages/twenty-server/test/integration/utils/list-chat-thread-ids.util.ts@@ -0,0 +1,42 @@+import { isDefined } from 'twenty-shared/utils';++import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';++// Mirrors the chat list query: deleted chats stay listed so they can be+// restored, and workflow run conversations are left to their run+export const listChatThreadIds = async (+ token = APPLE_JANE_ADMIN_ACCESS_TOKEN,+): Promise<string[]> => {+ const response = await makeGraphqlApiRequest(+ findManyOperationFactory({+ objectMetadataSingularName: 'agentChatThread',+ objectMetadataPluralName: 'agentChatThreads',+ gqlFields: 'id',+ filter: {+ and: [+ { workflowRunId: { is: 'NULL' } },+ {+ or: [+ { deletedAt: { is: 'NULL' } },+ { deletedAt: { is: 'NOT_NULL' } },+ ],+ },+ ],+ },+ orderBy: [{ updatedAt: 'DescNullsLast' }],+ first: 200,+ }),+ token,+ );++ if (isDefined(response.body.errors)) {+ throw new Error(+ `Could not list chats: ${JSON.stringify(response.body.errors)}`,+ );+ }++ return response.body.data.agentChatThreads.edges.map(+ ({ node }: { node: { id: string } }) => node.id,+ );+};