The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(ai): unread badge on the inbox, with inbox state sent as record events (#27221)
Félix Malfait08b868e26244
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 9e200ae293e..848c3f8143d 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3535,10 +3535,12 @@ type SendChatMessageResult {}type AgentChatThreadParticipant {+ id: UUID!threadId: UUID!lastReadAt: DateTimearchivedAt: DateTimesnoozedUntil: DateTime+ updatedAt: DateTime!}type AgentChatEvent {diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex d4984e21bb4..fe57003f6d3 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3096,10 +3096,12 @@ export interface SendChatMessageResult {}export interface AgentChatThreadParticipant {+ id: Scalars['UUID']threadId: Scalars['UUID']lastReadAt?: Scalars['DateTime']archivedAt?: Scalars['DateTime']snoozedUntil?: Scalars['DateTime']+ updatedAt: Scalars['DateTime']__typename: 'AgentChatThreadParticipant'}@@ -7043,10 +7045,12 @@ export interface SendChatMessageResultGenqlSelection{}export interface AgentChatThreadParticipantGenqlSelection{+ id?: boolean | numberthreadId?: boolean | numberlastReadAt?: boolean | numberarchivedAt?: boolean | numbersnoozedUntil?: boolean | number+ updatedAt?: boolean | number__typename?: boolean | number__scalar?: boolean | number}diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex bab66e5527d..c40ea7260e6 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -6940,6 +6940,9 @@ export default {]},"AgentChatThreadParticipant": {+ "id": [+ 3+ ],"threadId": [3],@@ -6952,6 +6955,9 @@ export default {"snoozedUntil": [4],+ "updatedAt": [+ 4+ ],"__typename": [1]diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 93e7559ae11..30c5f5aabfa 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -77,9 +77,11 @@ export type AgentChatThread = {export type AgentChatThreadParticipant = {__typename?: 'AgentChatThreadParticipant';archivedAt?: Maybe<Scalars['DateTime']['output']>;+ id: Scalars['UUID']['output'];lastReadAt?: Maybe<Scalars['DateTime']['output']>;snoozedUntil?: Maybe<Scalars['DateTime']['output']>;threadId: Scalars['UUID']['output'];+ updatedAt: Scalars['DateTime']['output'];};export type AgentIdInput = {@@ -8002,7 +8004,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 AgentChatThreadParticipantFieldsFragment = { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null };+export type AgentChatThreadParticipantFieldsFragment = { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, 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 };@@ -8020,7 +8022,7 @@ export type ArchiveAgentChatThreadMutationVariables = Exact<{}>;-export type ArchiveAgentChatThreadMutation = { __typename?: 'Mutation', archiveAgentChatThread: { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null } };+export type ArchiveAgentChatThreadMutation = { __typename?: 'Mutation', archiveAgentChatThread: { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string } };export type AssignRoleToAgentMutationVariables = Exact<{agentId: Scalars['UUID']['input'];@@ -8089,21 +8091,21 @@ export type MarkAgentChatThreadAsReadMutationVariables = Exact<{}>;-export type MarkAgentChatThreadAsReadMutation = { __typename?: 'Mutation', markAgentChatThreadAsRead: { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null } };+export type MarkAgentChatThreadAsReadMutation = { __typename?: 'Mutation', markAgentChatThreadAsRead: { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string } };export type MarkAgentChatThreadAsUnreadMutationVariables = Exact<{threadId: Scalars['UUID']['input'];}>;-export type MarkAgentChatThreadAsUnreadMutation = { __typename?: 'Mutation', markAgentChatThreadAsUnread: { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null } };+export type MarkAgentChatThreadAsUnreadMutation = { __typename?: 'Mutation', markAgentChatThreadAsUnread: { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string } };export type MoveAgentChatThreadToInboxMutationVariables = Exact<{threadId: Scalars['UUID']['input'];}>;-export type MoveAgentChatThreadToInboxMutation = { __typename?: 'Mutation', moveAgentChatThreadToInbox: { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null } };+export type MoveAgentChatThreadToInboxMutation = { __typename?: 'Mutation', moveAgentChatThreadToInbox: { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string } };export type RemoveRoleFromAgentMutationVariables = Exact<{agentId: Scalars['UUID']['input'];@@ -8146,7 +8148,7 @@ export type SnoozeAgentChatThreadMutationVariables = Exact<{}>;-export type SnoozeAgentChatThreadMutation = { __typename?: 'Mutation', snoozeAgentChatThread: { __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null } };+export type SnoozeAgentChatThreadMutation = { __typename?: 'Mutation', snoozeAgentChatThread: { __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string } };export type StopAgentChatStreamMutationVariables = Exact<{threadId: Scalars['UUID']['input'];@@ -8225,7 +8227,7 @@ export type GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{export type GetMyAgentChatThreadParticipantsQueryVariables = Exact<{ [key: string]: never; }>;-export type GetMyAgentChatThreadParticipantsQuery = { __typename?: 'Query', myAgentChatThreadParticipants: Array<{ __typename?: 'AgentChatThreadParticipant', threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null }> };+export type GetMyAgentChatThreadParticipantsQuery = { __typename?: 'Query', myAgentChatThreadParticipants: Array<{ __typename?: 'AgentChatThreadParticipant', id: string, threadId: string, lastReadAt?: string | null, archivedAt?: string | null, snoozedUntil?: string | null, updatedAt: string }> };export type GetToolIndexQueryVariables = Exact<{ [key: string]: never; }>;@@ -10634,7 +10636,7 @@ export type FindManyMarketplaceAppsForToolTableQueryVariables = Exact<{ [key: stexport type FindManyMarketplaceAppsForToolTableQuery = { __typename?: 'Query', findManyMarketplaceApps: Array<{ __typename?: 'MarketplaceApp', id: string, logoUrl?: string | null }> };-export const AgentChatThreadParticipantFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<AgentChatThreadParticipantFieldsFragment, unknown>;+export const AgentChatThreadParticipantFieldsFragmentDoc = {"kind":"Document","definitions":[{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<AgentChatThreadParticipantFieldsFragment, 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":"sharingReach"}},{"kind":"Field","name":{"kind":"Name","value":"readability"}},{"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>;@@ -10695,7 +10697,7 @@ export const ResetTimelineActivityTypeDocument = {"kind":"Document","definitionsexport const UpdateTimelineActivityTypeIsActiveDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateTimelineActivityTypeIsActive"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateTimelineActivityTypeInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateTimelineActivityType"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<UpdateTimelineActivityTypeIsActiveMutation, UpdateTimelineActivityTypeIsActiveMutationVariables>;export const FindManyTimelineActivityTypesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"FindManyTimelineActivityTypes"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"timelineActivityTypes"},"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":"name"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"icon"}},{"kind":"Field","name":{"kind":"Name","value":"emit"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"on"}},{"kind":"Field","name":{"kind":"Name","value":"objectUniversalIdentifier"}}]}},{"kind":"Field","name":{"kind":"Name","value":"frontComponentUniversalIdentifier"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}}]}}]}}]} as unknown as DocumentNode<FindManyTimelineActivityTypesQuery, FindManyTimelineActivityTypesQueryVariables>;export const ActivateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ActivateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"activateSkill"},"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":"SkillFields"}}]}}]}},{"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<ActivateSkillMutation, ActivateSkillMutationVariables>;-export const ArchiveAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ArchiveAgentChatThread"},"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":"archiveAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<ArchiveAgentChatThreadMutation, ArchiveAgentChatThreadMutationVariables>;+export const ArchiveAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ArchiveAgentChatThread"},"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":"archiveAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<ArchiveAgentChatThreadMutation, ArchiveAgentChatThreadMutationVariables>;export const AssignRoleToAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"AssignRoleToAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"assignRoleToAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}},{"kind":"Argument","name":{"kind":"Name","value":"roleId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"roleId"}}}]}]}}]} as unknown as DocumentNode<AssignRoleToAgentMutation, AssignRoleToAgentMutationVariables>;export const CreateChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createChatThread"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"title"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateChatThreadMutation, CreateChatThreadMutationVariables>;export const CreateOneAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateOneAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateAgentInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createOneAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}}]}},{"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<CreateOneAgentMutation, CreateOneAgentMutationVariables>;@@ -10705,14 +10707,14 @@ export const DeleteOneAgentDocument = {"kind":"Document","definitions":[{"kind":export const DeleteQueuedChatMessageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteQueuedChatMessage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteQueuedChatMessage"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"messageId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}}}]}]}}]} as unknown as DocumentNode<DeleteQueuedChatMessageMutation, DeleteQueuedChatMessageMutationVariables>;export const DeleteSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteSkill"},"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":"SkillFields"}}]}}]}},{"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<DeleteSkillMutation, DeleteSkillMutationVariables>;export const EvaluateAgentTurnDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"EvaluateAgentTurn"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"turnId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"evaluateAgentTurn"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"turnId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"turnId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"turnId"}},{"kind":"Field","name":{"kind":"Name","value":"score"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<EvaluateAgentTurnMutation, EvaluateAgentTurnMutationVariables>;-export const MarkAgentChatThreadAsReadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkAgentChatThreadAsRead"},"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":"markAgentChatThreadAsRead"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<MarkAgentChatThreadAsReadMutation, MarkAgentChatThreadAsReadMutationVariables>;-export const MarkAgentChatThreadAsUnreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkAgentChatThreadAsUnread"},"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":"markAgentChatThreadAsUnread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<MarkAgentChatThreadAsUnreadMutation, MarkAgentChatThreadAsUnreadMutationVariables>;-export const MoveAgentChatThreadToInboxDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MoveAgentChatThreadToInbox"},"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":"moveAgentChatThreadToInbox"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<MoveAgentChatThreadToInboxMutation, MoveAgentChatThreadToInboxMutationVariables>;+export const MarkAgentChatThreadAsReadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkAgentChatThreadAsRead"},"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":"markAgentChatThreadAsRead"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<MarkAgentChatThreadAsReadMutation, MarkAgentChatThreadAsReadMutationVariables>;+export const MarkAgentChatThreadAsUnreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MarkAgentChatThreadAsUnread"},"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":"markAgentChatThreadAsUnread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<MarkAgentChatThreadAsUnreadMutation, MarkAgentChatThreadAsUnreadMutationVariables>;+export const MoveAgentChatThreadToInboxDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"MoveAgentChatThreadToInbox"},"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":"moveAgentChatThreadToInbox"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<MoveAgentChatThreadToInboxMutation, MoveAgentChatThreadToInboxMutationVariables>;export const RemoveRoleFromAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RemoveRoleFromAgent"},"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":"removeRoleFromAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}}]}]}}]} as unknown as DocumentNode<RemoveRoleFromAgentMutation, RemoveRoleFromAgentMutationVariables>;export const RetryChatMessageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RetryChatMessage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"retryChatMessage"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"modelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"queued"}},{"kind":"Field","name":{"kind":"Name","value":"streamId"}}]}}]}}]} as unknown as DocumentNode<RetryChatMessageMutation, RetryChatMessageMutationVariables>;export const RunEvaluationInputDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RunEvaluationInput"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"runEvaluationInput"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}},{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"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"}}]}}]}}]}}]} as unknown as DocumentNode<RunEvaluationInputMutation, RunEvaluationInputMutationVariables>;export const SendChatMessageDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SendChatMessage"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"text"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"browsingContext"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"JSON"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"fileAttachments"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"FileAttachmentInput"}}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"sendChatMessage"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"text"},"value":{"kind":"Variable","name":{"kind":"Name","value":"text"}}},{"kind":"Argument","name":{"kind":"Name","value":"messageId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"messageId"}}},{"kind":"Argument","name":{"kind":"Name","value":"browsingContext"},"value":{"kind":"Variable","name":{"kind":"Name","value":"browsingContext"}}},{"kind":"Argument","name":{"kind":"Name","value":"modelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"modelId"}}},{"kind":"Argument","name":{"kind":"Name","value":"fileAttachments"},"value":{"kind":"Variable","name":{"kind":"Name","value":"fileAttachments"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"messageId"}},{"kind":"Field","name":{"kind":"Name","value":"queued"}},{"kind":"Field","name":{"kind":"Name","value":"streamId"}}]}}]}}]} as unknown as DocumentNode<SendChatMessageMutation, SendChatMessageMutationVariables>;-export const SnoozeAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SnoozeAgentChatThread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"snoozedUntil"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DateTime"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"snoozeAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"snoozedUntil"},"value":{"kind":"Variable","name":{"kind":"Name","value":"snoozedUntil"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<SnoozeAgentChatThreadMutation, SnoozeAgentChatThreadMutationVariables>;+export const SnoozeAgentChatThreadDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"SnoozeAgentChatThread"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"snoozedUntil"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DateTime"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"snoozeAgentChatThread"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}},{"kind":"Argument","name":{"kind":"Name","value":"snoozedUntil"},"value":{"kind":"Variable","name":{"kind":"Name","value":"snoozedUntil"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<SnoozeAgentChatThreadMutation, SnoozeAgentChatThreadMutationVariables>;export const StopAgentChatStreamDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"StopAgentChatStream"},"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":"stopAgentChatStream"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"threadId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"threadId"}}}]}]}}]} as unknown as DocumentNode<StopAgentChatStreamMutation, StopAgentChatStreamMutationVariables>;export const UpdateOneAgentDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateOneAgent"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateAgentInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateOneAgent"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentFields"}}]}}]}},{"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<UpdateOneAgentMutation, UpdateOneAgentMutationVariables>;export const UpdateSkillDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateSkill"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateSkillInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateSkill"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SkillFields"}}]}}]}},{"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<UpdateSkillMutation, UpdateSkillMutationVariables>;@@ -10725,7 +10727,7 @@ 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":"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":"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 GetMyAgentChatThreadParticipantsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetMyAgentChatThreadParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myAgentChatThreadParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}}]}}]} as unknown as DocumentNode<GetMyAgentChatThreadParticipantsQuery, GetMyAgentChatThreadParticipantsQueryVariables>;+export const GetMyAgentChatThreadParticipantsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetMyAgentChatThreadParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myAgentChatThreadParticipants"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AgentChatThreadParticipantFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AgentChatThreadParticipant"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"lastReadAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"snoozedUntil"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]} as unknown as DocumentNode<GetMyAgentChatThreadParticipantsQuery, GetMyAgentChatThreadParticipantsQueryVariables>;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>;diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsxindex ebc661f9532..cac5bbf0eb0 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatProvider.tsx@@ -1,8 +1,8 @@import { type ReactNode, Suspense } from 'react';import { AgentChatRuntimeEffects } from '@/ai/components/AgentChatRuntimeEffects';-import { AgentChatThreadInboxClockEffect } from '@/ai/components/AgentChatThreadInboxClockEffect';import { AgentChatThreadInitializationEffect } from '@/ai/components/AgentChatThreadInitializationEffect';+import { AgentChatThreadParticipantOperationsEffect } from '@/ai/components/AgentChatThreadParticipantOperationsEffect';import { AgentChatThreadRecordOperationsEffect } from '@/ai/components/AgentChatThreadRecordOperationsEffect';import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { AgentChatComponentInstanceContext } from '@/ai/contexts/AgentChatComponentInstanceContext';@@ -18,7 +18,7 @@ export const AgentChatProvider = ({ children }: AgentChatProviderProps) => (><AgentChatThreadInitializationEffect /><AgentChatThreadRecordOperationsEffect />- <AgentChatThreadInboxClockEffect />+ <AgentChatThreadParticipantOperationsEffect /><AgentChatRuntimeEffects />{children}</AgentChatComponentInstanceContext.Provider>diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInboxClockEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadInboxClockEffect.tsxdeleted file mode 100644index d10856d8d68..00000000000--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadInboxClockEffect.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { millisecondsInMinute } from 'date-fns/constants';-import { useEffect } from 'react';--import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';-import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';--// Snoozes end without any event announcing it-export const AgentChatThreadInboxClockEffect = () => {- const setAgentChatThreadInboxNow = useSetAtomState(- agentChatThreadInboxNowState,- );-- useEffect(() => {- const intervalId = window.setInterval(- () => setAgentChatThreadInboxNow(Date.now()),- millisecondsInMinute,- );-- return () => window.clearInterval(intervalId);- }, [setAgentChatThreadInboxNow]);-- return null;-};diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsxindex b9b4988884c..0c7f8336931 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadMarkAsReadEffect.tsx@@ -76,7 +76,6 @@ export const AgentChatThreadMarkAsReadEffect = () => {const { isUnread } = getAgentChatThreadInboxStatus({lastActivityAt,participant,- now: new Date(),});const visit = store.get(agentChatThreadVisitState.atom);diff --git a/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsxnew file mode 100644index 00000000000..15c5089c9b8--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsx@@ -0,0 +1,136 @@+import { useStore } from 'jotai';+import { useCallback, useMemo } from 'react';+import { CoreObjectNameSingular } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { useAgentChatThreadParticipants } from '@/ai/hooks/useAgentChatThreadParticipants';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';+import { getAgentChatThreadParticipantFromRecord } from '@/ai/utils/getAgentChatThreadParticipantFromRecord';+import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { useListenToObjectRecordOperationBrowserEvent } from '@/browser-event/hooks/useListenToObjectRecordOperationBrowserEvent';+import { type ObjectRecordOperationBrowserEventDetail } from '@/browser-event/types/ObjectRecordOperationBrowserEventDetail';+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';+import { useListenToEventsForQuery } from '@/sse-db-event/hooks/useListenToEventsForQuery';+import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';++// The member's inbox state follows what they do in their other tabs and+// devices, and snoozes the server ends+export const AgentChatThreadParticipantOperationsEffect = () => {+ const store = useStore();+ const participantObjectMetadataItem = useAtomFamilySelectorValue(+ objectMetadataItemFamilySelector,+ {+ objectName: CoreObjectNameSingular.AgentChatThreadParticipant,+ objectNameType: 'singular',+ },+ );+ const currentWorkspaceMemberId = useAtomStateValue(+ currentWorkspaceMemberState,+ )?.id;+ const { refreshAgentChatThreadParticipants } =+ useAgentChatThreadParticipants();+ const isEnabled =+ isDefined(participantObjectMetadataItem) &&+ isDefined(currentWorkspaceMemberId);++ // Roles that read every record could receive every member's rows, so only+ // the member's own are asked for+ const operationSignature = useMemo(+ () => ({+ objectNameSingular: CoreObjectNameSingular.AgentChatThreadParticipant,+ variables: {+ filter: { workspaceMemberId: { eq: currentWorkspaceMemberId } },+ },+ }),+ [currentWorkspaceMemberId],+ );++ useListenToEventsForQuery({+ queryId: 'agent-chat-thread-participant-operations',+ operationSignature,+ skip: !isEnabled,+ });++ const handleRecordOperation = useCallback(+ ({ operation }: ObjectRecordOperationBrowserEventDetail) => {+ // Also kept aside, so a load already on its way cannot undo them+ const applyParticipants = (+ participants: AgentChatThreadParticipantFieldsFragment[],+ ) => {+ store.set(+ agentChatThreadStreamedParticipantsState.atom,+ (streamedParticipants) =>+ mergeAgentChatThreadParticipants(+ streamedParticipants,+ participants,+ ),+ );+ store.set(agentChatThreadParticipantsState.atom, (loadedParticipants) =>+ isDefined(loadedParticipants)+ ? mergeAgentChatThreadParticipants(loadedParticipants, participants)+ : loadedParticipants,+ );+ };++ switch (operation.type) {+ case 'create-one': {+ applyParticipants([+ getAgentChatThreadParticipantFromRecord(operation.createdRecord),+ ]);+ return;+ }+ case 'update-one':+ case 'update-many': {+ const updateInputs =+ operation.type === 'update-one'+ ? [operation.result.updateInput]+ : operation.result.updateInputs;+ const participants = store.get(agentChatThreadParticipantsState.atom);+ const participantsById = new Map(+ Object.values(participants ?? {}).map((participant) => [+ participant.id,+ participant,+ ]),+ );+ const updatedParticipants = updateInputs.map(+ ({ recordId, updatedFields }) => {+ const participant = participantsById.get(recordId);++ return isDefined(participant)+ ? { ...participant, ...Object.assign({}, ...updatedFields) }+ : undefined;+ },+ );++ // Updates only carry what changed, so a row not loaded yet is+ // read again whole+ if (+ !isDefined(participants) ||+ !updatedParticipants.every(isDefined)+ ) {+ void refreshAgentChatThreadParticipants();+ return;+ }++ applyParticipants(updatedParticipants);+ return;+ }+ default:+ void refreshAgentChatThreadParticipants();+ }+ },+ [refreshAgentChatThreadParticipants, store],+ );++ useListenToObjectRecordOperationBrowserEvent({+ onObjectRecordOperationBrowserEvent: handleRecordOperation,+ objectMetadataItemId: participantObjectMetadataItem?.id,+ enabled: isEnabled,+ });++ return null;+};diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsxindex 3f9724b7bcb..79e61c2675c 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadMarkAsReadEffect.test.tsx@@ -44,6 +44,8 @@ describe('AgentChatThreadMarkAsReadEffect', () => {lastReadAt: '2026-10-01T09:00:00.000Z',archivedAt: null,snoozedUntil: null,+ id: 'participant-id',+ updatedAt: '2026-10-01T10:00:00.000Z',},});jotaiStore.set(agentChatDisplayedThreadState.atom, THREAD_ID);diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadParticipantOperationsEffect.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadParticipantOperationsEffect.test.tsxnew file mode 100644index 00000000000..470bb358a82--- /dev/null+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadParticipantOperationsEffect.test.tsx@@ -0,0 +1,240 @@+import { act, render } from '@testing-library/react';+import { createStore, Provider as JotaiProvider } from 'jotai';+import { CoreObjectNameSingular } from 'twenty-shared/types';++import { AgentChatThreadParticipantOperationsEffect } from '@/ai/components/AgentChatThreadParticipantOperationsEffect';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';+import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';+import { dispatchObjectRecordOperationBrowserEvent } from '@/browser-event/utils/dispatchObjectRecordOperationBrowserEvent';+import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';+import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';++const PARTICIPANT_OBJECT_METADATA_ITEM = {+ id: 'participant-object-metadata-id',+ nameSingular: CoreObjectNameSingular.AgentChatThreadParticipant,+};++jest.mock('@/sse-db-event/hooks/useListenToEventsForQuery', () => ({+ useListenToEventsForQuery: jest.fn(),+}));++const mockRefreshAgentChatThreadParticipants = jest.fn();++jest.mock('@/ai/hooks/useAgentChatThreadParticipants', () => ({+ useAgentChatThreadParticipants: () => ({+ refreshAgentChatThreadParticipants: mockRefreshAgentChatThreadParticipants,+ }),+}));++jest.mock(+ '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue',+ () => ({+ useAtomFamilySelectorValue: (selector: unknown) =>+ selector === objectMetadataItemFamilySelector+ ? PARTICIPANT_OBJECT_METADATA_ITEM+ : undefined,+ }),+);++const THREAD_ID = '20202020-0000-4000-8000-0000000000aa';+const PARTICIPANT_ID = '20202020-0000-4000-8000-0000000000bb';++const READ_PARTICIPANT: AgentChatThreadParticipantFieldsFragment = {+ id: PARTICIPANT_ID,+ threadId: THREAD_ID,+ lastReadAt: '2026-10-01T10:00:00.000Z',+ archivedAt: null,+ snoozedUntil: null,+ updatedAt: '2026-10-01T10:00:00.000Z',+};++const renderEffect = (+ participants: Record<string, AgentChatThreadParticipantFieldsFragment> | null,+) => {+ const store = createStore();++ store.set(agentChatThreadParticipantsState.atom, participants);+ store.set(currentWorkspaceMemberState.atom, {+ id: 'workspace-member-id',+ } as never);++ render(+ <JotaiProvider store={store}>+ <AgentChatThreadParticipantOperationsEffect />+ </JotaiProvider>,+ );++ return { store };+};++const receiveCreatedParticipant = (+ participant: AgentChatThreadParticipantFieldsFragment,+) =>+ act(() =>+ dispatchObjectRecordOperationBrowserEvent({+ objectMetadataItem: PARTICIPANT_OBJECT_METADATA_ITEM as never,+ operation: {+ type: 'create-one',+ createdRecord: {+ ...participant,+ __typename: 'AgentChatThreadParticipant',+ workspaceMemberId: 'workspace-member-id',+ },+ },+ }),+ );++const receiveParticipantUpdate = (+ recordId: string,+ updatedFields: Partial<AgentChatThreadParticipantFieldsFragment>,+) =>+ act(() =>+ dispatchObjectRecordOperationBrowserEvent({+ objectMetadataItem: PARTICIPANT_OBJECT_METADATA_ITEM as never,+ operation: {+ type: 'update-one',+ result: {+ updateInput: {+ recordId,+ updatedFields: Object.entries(updatedFields).map(+ ([fieldName, value]) => ({ [fieldName]: value }),+ ),+ },+ },+ },+ }),+ );++describe('AgentChatThreadParticipantOperationsEffect', () => {+ beforeEach(() => {+ mockRefreshAgentChatThreadParticipants.mockClear();+ });++ it('adds a row the member created elsewhere', () => {+ const { store } = renderEffect({});++ receiveCreatedParticipant(READ_PARTICIPANT);++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: READ_PARTICIPANT,+ });+ });++ it('applies a change the member made elsewhere', () => {+ const { store } = renderEffect({ [THREAD_ID]: READ_PARTICIPANT });++ const change = {+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ };++ receiveParticipantUpdate(PARTICIPANT_ID, change);++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: { ...READ_PARTICIPANT, ...change },+ });+ });++ it('applies the end of a snooze', () => {+ const snoozedParticipant = {+ ...READ_PARTICIPANT,+ archivedAt: '2026-10-01T11:00:00.000Z',+ snoozedUntil: '2026-10-02T09:00:00.000Z',+ };+ const { store } = renderEffect({ [THREAD_ID]: snoozedParticipant });++ const change = {+ archivedAt: null,+ updatedAt: '2026-10-02T09:00:00.000Z',+ };++ receiveParticipantUpdate(PARTICIPANT_ID, change);++ expect(+ store.get(agentChatThreadParticipantsState.atom)?.[THREAD_ID],+ ).toEqual({ ...snoozedParticipant, ...change });+ });++ it('keeps a change for a load already on its way, with its new version', () => {+ // Archived through an earlier change, so its version is still T0+ const { store } = renderEffect({+ [THREAD_ID]: {+ ...READ_PARTICIPANT,+ archivedAt: '2026-10-01T10:01:00.000Z',+ },+ });+ const loadedArchivedParticipant = {+ ...READ_PARTICIPANT,+ archivedAt: '2026-10-01T10:01:00.000Z',+ updatedAt: '2026-10-01T10:01:00.000Z',+ };++ receiveParticipantUpdate(PARTICIPANT_ID, {+ archivedAt: null,+ updatedAt: '2026-10-01T10:02:00.000Z',+ });++ // A load that read the archived row (T1) merges this change (T2) over it+ expect(+ mergeAgentChatThreadParticipants(+ { [THREAD_ID]: loadedArchivedParticipant },+ Object.values(store.get(agentChatThreadStreamedParticipantsState.atom)),+ )[THREAD_ID],+ ).toEqual({+ ...READ_PARTICIPANT,+ archivedAt: null,+ updatedAt: '2026-10-01T10:02:00.000Z',+ });+ });++ it('ignores a change older than the version it has', () => {+ const { store } = renderEffect({ [THREAD_ID]: READ_PARTICIPANT });++ receiveParticipantUpdate(PARTICIPANT_ID, {+ archivedAt: '2026-10-01T09:58:00.000Z',+ updatedAt: '2026-10-01T09:59:00.000Z',+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: READ_PARTICIPANT,+ });+ });++ it('reloads the rows when a change is for a row it does not have', () => {+ const { store } = renderEffect({ [THREAD_ID]: READ_PARTICIPANT });++ receiveParticipantUpdate('another-participant-id', { lastReadAt: null });++ expect(mockRefreshAgentChatThreadParticipants).toHaveBeenCalledTimes(1);+ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: READ_PARTICIPANT,+ });+ });++ it('ignores a copy older than the one it has', () => {+ const { store } = renderEffect({ [THREAD_ID]: READ_PARTICIPANT });++ receiveCreatedParticipant({+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T09:59:00.000Z',+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: READ_PARTICIPANT,+ });+ });++ it('keeps a row that arrives before the first load for that load', () => {+ const { store } = renderEffect(null);++ receiveCreatedParticipant(READ_PARTICIPANT);++ expect(store.get(agentChatThreadParticipantsState.atom)).toBeNull();+ expect(store.get(agentChatThreadStreamedParticipantsState.atom)).toEqual({+ [THREAD_ID]: READ_PARTICIPANT,+ });+ });+});diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/NavigationDrawerAiChatTriageSection.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/NavigationDrawerAiChatTriageSection.test.tsxindex fb795fe2c53..30b5c579275 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/NavigationDrawerAiChatTriageSection.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/NavigationDrawerAiChatTriageSection.test.tsx@@ -69,6 +69,8 @@ describe('NavigationDrawerAiChatTriageSection', () => {lastReadAt: '2026-10-01T10:00:00.000Z',archivedAt: null,snoozedUntil: null,+ id: 'participant-id',+ updatedAt: '2026-10-01T10:00:00.000Z',},}));diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatThreadParticipantUnsavedUpdatedAt.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadParticipantUnsavedUpdatedAt.tsnew file mode 100644index 00000000000..d8adf300549--- /dev/null+++ b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadParticipantUnsavedUpdatedAt.ts@@ -0,0 +1,5 @@+// The version of a row built here before the server wrote one, older than any+// row the server sends+export const AGENT_CHAT_THREAD_PARTICIPANT_UNSAVED_UPDATED_AT = new Date(+ 0,+).toISOString();diff --git a/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadParticipantFragment.ts b/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadParticipantFragment.tsindex 89e00ee4adf..a38f65b43bb 100644--- a/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadParticipantFragment.ts+++ b/packages/twenty-front/src/modules/ai/graphql/fragments/agentChatThreadParticipantFragment.ts@@ -2,9 +2,11 @@ import { gql } from '@apollo/client';export const AGENT_CHAT_THREAD_PARTICIPANT_FRAGMENT = gql`fragment AgentChatThreadParticipantFields on AgentChatThreadParticipant {+ idthreadIdlastReadAtarchivedAtsnoozedUntil+ updatedAt}`;diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsxindex 0518b67fa17..b30a8650bf0 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAgentChatThreadParticipants.test.tsx@@ -4,6 +4,7 @@ import { type ReactNode } from 'react';import { useAgentChatThreadParticipants } from '@/ai/hooks/useAgentChatThreadParticipants';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import { agentChatThreadVisitState } from '@/ai/states/agentChatThreadVisitState';import { recordStoreFamilyState } from '@/object-record/record-store/states/recordStoreFamilyState';@@ -14,6 +15,8 @@ const READ_PARTICIPANT = {lastReadAt: LAST_ACTIVITY_AT,archivedAt: null,snoozedUntil: null,+ id: 'participant-id',+ updatedAt: '2026-10-01T10:00:00.000Z',};const query = jest.fn();@@ -71,6 +74,65 @@ describe('useAgentChatThreadParticipants', () => {});});+ it('keeps a change the server sent while the member state was loading', async () => {+ const { result, store } = renderParticipants();+ const unreadParticipant = {+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ };++ query.mockImplementation(async () => {+ store.set(agentChatThreadStreamedParticipantsState.atom, {+ [THREAD_ID]: unreadParticipant,+ });++ return { data: { myAgentChatThreadParticipants: [READ_PARTICIPANT] } };+ });++ await act(async () => {+ await result.current.refreshAgentChatThreadParticipants();+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: unreadParticipant,+ });+ });++ it('keeps the latest load when an earlier one answers after it', async () => {+ const { result, store } = renderParticipants();+ const unreadParticipant = {+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ };+ let answerFirstLoad: (value: unknown) => void = () => undefined;++ query+ .mockReturnValueOnce(+ new Promise((resolve) => {+ answerFirstLoad = resolve;+ }),+ )+ .mockResolvedValueOnce({+ data: { myAgentChatThreadParticipants: [unreadParticipant] },+ });++ await act(async () => {+ const firstLoad = result.current.refreshAgentChatThreadParticipants();++ await result.current.refreshAgentChatThreadParticipants();+ answerFirstLoad({+ data: { myAgentChatThreadParticipants: [READ_PARTICIPANT] },+ });+ await firstLoad;+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ [THREAD_ID]: unreadParticipant,+ });+ });+it('reads a thread up to its last activity before the server answers', async () => {mutate.mockReturnValue(new Promise(() => undefined));const { result, store } = renderParticipants();diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsxindex 04af04f7ff4..294de1bd3d6 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOptimisticallyRestoreOnSend.test.tsx@@ -13,6 +13,8 @@ const ARCHIVED_PARTICIPANT = {lastReadAt: LAST_ACTIVITY_AT,archivedAt: '2026-10-01T11:00:00.000Z',snoozedUntil: null,+ id: 'participant-id',+ updatedAt: '2026-10-01T11:00:00.000Z',};describe('useOptimisticallyRestoreOnSend', () => {@@ -53,6 +55,8 @@ describe('useOptimisticallyRestoreOnSend', () => {lastReadAt: sentAt,archivedAt: null,snoozedUntil: null,+ id: 'participant-id',+ updatedAt: ARCHIVED_PARTICIPANT.updatedAt,});act(() => rollback());diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.tsindex f1c8318c75a..a8bd9ed5545 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts@@ -5,12 +5,15 @@ import { useCallback } from 'react';import { isDefined } from 'twenty-shared/utils';import { useToast } from 'twenty-ui/components';+import { agentChatThreadParticipantsLoadCountState } from '@/ai/states/agentChatThreadParticipantsLoadCountState';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import {type AgentChatThreadVisit,agentChatThreadVisitState,} from '@/ai/states/agentChatThreadVisitState';import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';+import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';import { getToastOptionsFromError } from '@/error-handler/utils/getToastOptionsFromError';import {type AgentChatThreadParticipantFieldsFragment,@@ -28,6 +31,12 @@ export const useAgentChatThreadParticipants = () => {const { enqueueToast } = useToast();const refreshAgentChatThreadParticipants = useCallback(async () => {+ const loadCount =+ store.get(agentChatThreadParticipantsLoadCountState.atom) + 1;++ store.set(agentChatThreadParticipantsLoadCountState.atom, loadCount);+ store.set(agentChatThreadStreamedParticipantsState.atom, {});+const result = await client.query({query: GetMyAgentChatThreadParticipantsDocument,@@ -35,17 +44,23 @@ export const useAgentChatThreadParticipants = () => {}).catch(() => undefined);- if (!isDefined(result?.data)) {+ if (+ !isDefined(result?.data) ||+ store.get(agentChatThreadParticipantsLoadCountState.atom) !== loadCount+ ) {return;}store.set(agentChatThreadParticipantsState.atom,- Object.fromEntries(- result.data.myAgentChatThreadParticipants.map((participant) => [- participant.threadId,- participant,- ]),+ mergeAgentChatThreadParticipants(+ Object.fromEntries(+ result.data.myAgentChatThreadParticipants.map((participant) => [+ participant.threadId,+ participant,+ ]),+ ),+ Object.values(store.get(agentChatThreadStreamedParticipantsState.atom)),),);}, [client, store]);diff --git a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.tsindex d186a78cc97..7212e3c5522 100644--- a/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useOptimisticallyRestoreOnSend.ts@@ -1,6 +1,7 @@import { useStore } from 'jotai';import { isDefined } from 'twenty-shared/utils';+import { AGENT_CHAT_THREAD_PARTICIPANT_UNSAVED_UPDATED_AT } from '@/ai/constants/AgentChatThreadParticipantUnsavedUpdatedAt';import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';import { agentChatThreadVisitState } from '@/ai/states/agentChatThreadVisitState';@@ -47,10 +48,14 @@ export const useOptimisticallyRestoreOnSend = () => {? {...participants,[threadId]: {+ ...participants[threadId],threadId,lastReadAt: optimisticUpdatedAt,archivedAt: null,snoozedUntil: null,+ updatedAt:+ previousParticipant?.updatedAt ??+ AGENT_CHAT_THREAD_PARTICIPANT_UNSAVED_UPDATED_AT,},}: participants,diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadInboxNowState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadInboxNowState.tsdeleted file mode 100644index c9a292b61a4..00000000000--- a/packages/twenty-front/src/modules/ai/states/agentChatThreadInboxNowState.ts+++ /dev/null@@ -1,6 +0,0 @@-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';--export const agentChatThreadInboxNowState = createAtomState<number>({- key: 'ai/agentChatThreadInboxNowState',- defaultValue: Date.now(),-});diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.tsnew file mode 100644index 00000000000..8d706c985ab--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.ts@@ -0,0 +1,8 @@+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';++// Loads can overlap, and only the one requested last may replace the rows+export const agentChatThreadParticipantsLoadCountState =+ createAtomState<number>({+ key: 'ai/agentChatThreadParticipantsLoadCountState',+ defaultValue: 0,+ });diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadStreamedParticipantsState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadStreamedParticipantsState.tsnew file mode 100644index 00000000000..1bb85f597a4--- /dev/null+++ b/packages/twenty-front/src/modules/ai/states/agentChatThreadStreamedParticipantsState.ts@@ -0,0 +1,11 @@+import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';+import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';++// Rows the server sent since the member's rows were last requested, kept so+// the response cannot undo a change that came after it was read+export const agentChatThreadStreamedParticipantsState = createAtomState<+ Record<string, AgentChatThreadParticipantFieldsFragment>+>({+ key: 'ai/agentChatThreadStreamedParticipantsState',+ defaultValue: {},+});diff --git a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.tsindex 9e70225b956..544c17d80db 100644--- a/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts+++ b/packages/twenty-front/src/modules/ai/states/selectors/__tests__/agentChatVisibleThreadsSelector.test.ts@@ -2,15 +2,17 @@ import { createStore } from 'jotai';import { AGENT_CHAT_THREAD_FILTER_STATUS } from '@/ai/constants/AgentChatThreadFilterStatus';import { agentChatThreadFilterStatusState } from '@/ai/states/agentChatThreadFilterStatusState';-import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';import { agentChatVisibleThreadsSelector } from '@/ai/states/selectors/agentChatVisibleThreadsSelector';import { type AgentChatThreadFilterStatus } from '@/ai/types/AgentChatThreadFilterStatus';-const NOW = new Date('2026-10-01T12:00:00.000Z').getTime();const LAST_ACTIVITY_AT = '2026-10-01T10:00:00.000Z';-const READ = { lastReadAt: LAST_ACTIVITY_AT, snoozedUntil: null };+const READ = {+ lastReadAt: LAST_ACTIVITY_AT,+ snoozedUntil: null,+ updatedAt: LAST_ACTIVITY_AT,+};const ACTIVITY_AFTER_ARCHIVE_AT = '2026-10-01T11:30:00.000Z';@@ -23,6 +25,7 @@ const THREADS: {lastReadAt: string;archivedAt: string | null;snoozedUntil: string | null;+ updatedAt: string;}| undefined;}[] = [@@ -53,6 +56,15 @@ const THREADS: {snoozedUntil: '2026-10-02T09:00:00.000Z',},},+ {+ id: 'snooze-ended',+ deletedAt: null,+ participant: {+ ...READ,+ archivedAt: null,+ snoozedUntil: '2026-10-01T11:30:00.000Z',+ },+ },{id: 'archived',deletedAt: null,@@ -87,11 +99,10 @@ const getVisibleThreadIds = (filterStatus: AgentChatThreadFilterStatus) => {agentChatThreadParticipantsState.atom,Object.fromEntries(THREADS.filter(({ participant }) => participant !== undefined).map(- ({ id, participant }) => [id, { threadId: id, ...participant! }],+ ({ id, participant }) => [id, { id, threadId: id, ...participant! }],),),);- store.set(agentChatThreadInboxNowState.atom, NOW);store.set(agentChatThreadFilterStatusState.atom, filterStatus);return store.get(agentChatVisibleThreadsSelector.atom).map(({ id }) => id);@@ -101,7 +112,13 @@ describe('agentChatVisibleThreadsSelector', () => {it.each([[AGENT_CHAT_THREAD_FILTER_STATUS.ACTIVE,- ['read', 'archived-then-active', 'snoozed-then-active', 'unread'],+ [+ 'read',+ 'archived-then-active',+ 'snoozed-then-active',+ 'unread',+ 'snooze-ended',+ ],],[AGENT_CHAT_THREAD_FILTER_STATUS.SNOOZED, ['snoozed']],[AGENT_CHAT_THREAD_FILTER_STATUS.DONE, ['archived']],diff --git a/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusFamilySelector.ts b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusFamilySelector.tsindex efa4b4e1fbd..cd203d5f489 100644--- a/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusFamilySelector.ts+++ b/packages/twenty-front/src/modules/ai/states/selectors/agentChatThreadInboxStatusFamilySelector.ts@@ -1,6 +1,5 @@import { isDefined } from 'twenty-shared/utils';-import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';import { agentChatThreadVisitState } from '@/ai/states/agentChatThreadVisitState';import { agentChatThreadRecordFamilySelector } from '@/ai/states/selectors/agentChatThreadRecordFamilySelector';@@ -21,7 +20,6 @@ export const agentChatThreadInboxStatusFamilySelector =lastActivityAt: get(agentChatThreadRecordFamilySelector, threadId)?.lastActivityAt,participant: participants?.[threadId],- now: new Date(get(agentChatThreadInboxNowState)),});// Before the rows load every thread would read as unread. The threaddiff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.tsindex e480711c238..2e85bcc9964 100644--- a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatThreadInboxStatus.test.ts@@ -1,7 +1,6 @@import { getAgentChatThreadInboxStatus } from '@/ai/utils/getAgentChatThreadInboxStatus';const THREAD_ID = 'thread';-const NOW = new Date('2026-10-01T12:00:00.000Z');const ARCHIVED_AT = '2026-10-01T10:00:00.000Z';const getStatus = ({@@ -17,8 +16,14 @@ const getStatus = ({} = {}) =>getAgentChatThreadInboxStatus({lastActivityAt,- participant: { threadId: THREAD_ID, lastReadAt, archivedAt, snoozedUntil },- now: NOW,+ participant: {+ id: 'participant',+ threadId: THREAD_ID,+ lastReadAt,+ archivedAt,+ snoozedUntil,+ updatedAt: ARCHIVED_AT,+ },});describe('getAgentChatThreadInboxStatus', () => {@@ -27,7 +32,6 @@ describe('getAgentChatThreadInboxStatus', () => {getAgentChatThreadInboxStatus({lastActivityAt: '2026-10-01T09:00:00.000Z',participant: undefined,- now: NOW,}),).toEqual({ scope: 'INBOX', isUnread: true, event: null });});@@ -67,25 +71,26 @@ describe('getAgentChatThreadInboxStatus', () => {).toMatchObject({ scope: 'INBOX', event: null });});- it('snoozes a thread until its snooze time, then shows the snooze ended', () => {- expect(- getStatus({- archivedAt: ARCHIVED_AT,- snoozedUntil: '2026-10-02T09:00:00.000Z',- }),- ).toMatchObject({+ it('snoozes a thread until the server unarchives it', () => {+ const snoozedUntil = '2026-10-02T09:00:00.000Z';++ expect(getStatus({ archivedAt: ARCHIVED_AT, snoozedUntil })).toMatchObject({scope: 'SNOOZED',- event: { type: 'SNOOZED', at: '2026-10-02T09:00:00.000Z' },+ event: { type: 'SNOOZED', at: snoozedUntil },+ });+ expect(getStatus({ snoozedUntil })).toMatchObject({+ scope: 'INBOX',+ event: { type: 'SNOOZE_ENDED', at: snoozedUntil },});+ });++ it('stops showing an ended snooze once activity follows it', () => {expect(getStatus({- archivedAt: ARCHIVED_AT,- snoozedUntil: NOW.toISOString(),+ snoozedUntil: '2026-10-02T09:00:00.000Z',+ lastActivityAt: '2026-10-02T10:00:00.000Z',}),- ).toMatchObject({- scope: 'INBOX',- event: { type: 'SNOOZE_ENDED', at: NOW.toISOString() },- });+ ).toMatchObject({ scope: 'INBOX', event: null });});it('brings a snoozed thread back early when activity follows the snooze', () => {diff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/mergeAgentChatThreadParticipants.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/mergeAgentChatThreadParticipants.test.tsnew file mode 100644index 00000000000..37233cb2d3c--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/mergeAgentChatThreadParticipants.test.ts@@ -0,0 +1,50 @@+import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';++const READ_PARTICIPANT = {+ id: 'participant',+ threadId: 'thread',+ lastReadAt: '2026-10-01T10:00:00.000Z',+ archivedAt: null,+ snoozedUntil: null,+ updatedAt: '2026-10-01T10:00:00.000Z',+};++describe('mergeAgentChatThreadParticipants', () => {+ it('takes a newer copy and leaves the other threads alone', () => {+ const otherParticipant = { ...READ_PARTICIPANT, threadId: 'other' };+ const unreadParticipant = {+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ };++ expect(+ mergeAgentChatThreadParticipants(+ { thread: READ_PARTICIPANT, other: otherParticipant },+ [unreadParticipant],+ ),+ ).toEqual({ thread: unreadParticipant, other: otherParticipant });+ });++ it('takes a copy as recent as the one it has, like one a change was applied to', () => {+ const changedParticipant = { ...READ_PARTICIPANT, lastReadAt: null };++ expect(+ mergeAgentChatThreadParticipants({ thread: READ_PARTICIPANT }, [+ changedParticipant,+ ]),+ ).toEqual({ thread: changedParticipant });+ });++ it('keeps what it has over an older copy', () => {+ expect(+ mergeAgentChatThreadParticipants({ thread: READ_PARTICIPANT }, [+ {+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T09:59:00.000Z',+ },+ ]),+ ).toEqual({ thread: READ_PARTICIPANT });+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.tsindex 12e3628d5d9..809e449cc98 100644--- a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadInboxStatus.ts@@ -7,51 +7,49 @@ import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metad// Activity and archiving have different writers and are compared rather than// folded into a status, so a message landing right after an archive brings the// thread back whichever write committed last. Snooze is an archive with a-// wake-up time+// wake-up time; the server unarchives the thread when it passes and keeps the+// snooze as what brought it backexport const getAgentChatThreadInboxStatus = ({lastActivityAt,participant,- now,}: {lastActivityAt: string | null | undefined;participant: AgentChatThreadParticipantFieldsFragment | undefined;- now: Date;}): AgentChatThreadInboxStatus => {const isUnread =isDefined(lastActivityAt) &&(!isDefined(participant?.lastReadAt) ||isAfter(lastActivityAt, participant.lastReadAt));const archivedAt = participant?.archivedAt;-- if (- !isDefined(archivedAt) ||- (isDefined(lastActivityAt) && isAfter(lastActivityAt, archivedAt))- ) {- return { scope: 'INBOX', isUnread, event: null };- }-const snoozedUntil = participant?.snoozedUntil;- if (!isDefined(snoozedUntil)) {+ if (!isDefined(archivedAt)) {return {- scope: 'ARCHIVED',+ scope: 'INBOX',isUnread,- event: { type: 'DONE', at: archivedAt },+ event:+ isDefined(snoozedUntil) &&+ !(isDefined(lastActivityAt) && isAfter(lastActivityAt, snoozedUntil))+ ? { type: 'SNOOZE_ENDED', at: snoozedUntil }+ : null,};}- if (isAfter(snoozedUntil, now)) {+ if (isDefined(lastActivityAt) && isAfter(lastActivityAt, archivedAt)) {+ return { scope: 'INBOX', isUnread, event: null };+ }++ if (!isDefined(snoozedUntil)) {return {- scope: 'SNOOZED',+ scope: 'ARCHIVED',isUnread,- event: { type: 'SNOOZED', at: snoozedUntil },+ event: { type: 'DONE', at: archivedAt },};}- // Still archived with no newer activity: the snooze ran outreturn {- scope: 'INBOX',+ scope: 'SNOOZED',isUnread,- event: { type: 'SNOOZE_ENDED', at: snoozedUntil },+ event: { type: 'SNOOZED', at: snoozedUntil },};};diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadParticipantFromRecord.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadParticipantFromRecord.tsnew file mode 100644index 00000000000..6c5cf97eb43--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatThreadParticipantFromRecord.ts@@ -0,0 +1,14 @@+import { type ObjectRecord } from 'twenty-shared/types';+import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';++// Record events carry the whole row, along with fields the inbox has no use for+export const getAgentChatThreadParticipantFromRecord = (+ record: ObjectRecord,+): AgentChatThreadParticipantFieldsFragment => ({+ id: record.id,+ threadId: record.threadId,+ lastReadAt: record.lastReadAt ?? null,+ archivedAt: record.archivedAt ?? null,+ snoozedUntil: record.snoozedUntil ?? null,+ updatedAt: record.updatedAt,+});diff --git a/packages/twenty-front/src/modules/ai/utils/mergeAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/utils/mergeAgentChatThreadParticipants.tsnew file mode 100644index 00000000000..bb64521fd9b--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/mergeAgentChatThreadParticipants.ts@@ -0,0 +1,22 @@+import { isBefore } from 'date-fns';+import { isDefined } from 'twenty-shared/utils';++import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';++// Rows arrive from loads and from changes, possibly out of order, so a row+// only replaces one it is at least as recent as+export const mergeAgentChatThreadParticipants = (+ participants: Record<string, AgentChatThreadParticipantFieldsFragment>,+ incomingParticipants: AgentChatThreadParticipantFieldsFragment[],+): Record<string, AgentChatThreadParticipantFieldsFragment> =>+ incomingParticipants.reduce((mergedParticipants, incomingParticipant) => {+ const participant = mergedParticipants[incomingParticipant.threadId];++ return isDefined(participant?.updatedAt) &&+ isBefore(incomingParticipant.updatedAt, participant.updatedAt)+ ? mergedParticipants+ : {+ ...mergedParticipants,+ [incomingParticipant.threadId]: incomingParticipant,+ };+ }, participants);diff --git a/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx b/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsxindex ccc43e31e96..a41a1eea82b 100644--- a/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx+++ b/packages/twenty-front/src/modules/navigation/components/MainNavigationDrawerModeSwitcher.tsx@@ -5,12 +5,14 @@ import { motion, useReducedMotion } from 'framer-motion';import { Tooltip } from 'twenty-ui/primitives/surfaces';import { useTheme, themeCssVariables } from 'twenty-ui/theme';+import { agentChatOpenThreadsSummarySelector } from '@/ai/states/selectors/agentChatOpenThreadsSummarySelector';import { isLayoutCustomizationModeEnabledState } from '@/layout-customization/states/isLayoutCustomizationModeEnabledState';import { useActiveNavigationDrawerMode } from '@/navigation/hooks/useActiveNavigationDrawerMode';import { useIsNavigationDrawerContentExpanded } from '@/navigation/hooks/useIsNavigationDrawerContentExpanded';import { useNavigationDrawerModes } from '@/navigation/hooks/useNavigationDrawerModes';import { useSwitchNavigationDrawerMode } from '@/navigation/hooks/useSwitchNavigationDrawerMode';import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';+import { StyledNavigationDrawerUnreadDot } from '@/ui/navigation/navigation-drawer/components/StyledNavigationDrawerUnreadDot';import { NAVIGATION_DRAWER_TABS } from '@/ui/navigation/states/navigationDrawerTabs';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { useIsMobile } from 'twenty-ui/utilities';@@ -92,6 +94,7 @@ const StyledModeIcon = styled.span`flex-shrink: 0;height: ${themeCssVariables.spacing[4]};justify-content: center;+ position: relative;width: ${themeCssVariables.spacing[4]};`;@@ -118,6 +121,9 @@ export const MainNavigationDrawerModeSwitcher = () => {const activeNavigationDrawerMode = useActiveNavigationDrawerMode();const { switchNavigationDrawerMode } = useSwitchNavigationDrawerMode();const shouldReduceMotion = useReducedMotion();+ const { hasUnreadOpenThread } = useAtomStateValue(+ agentChatOpenThreadsSummarySelector,+ );if (modes.length === 0) {return null;@@ -133,6 +139,11 @@ export const MainNavigationDrawerModeSwitcher = () => {>{modes.map(({ Icon, label, mode }) => {const isActive = mode === activeNavigationDrawerMode;+ // Inside the inbox, its Open item already shows what is unread+ const isUnread =+ mode === NAVIGATION_DRAWER_TABS.AI_CHAT_HISTORY &&+ hasUnreadOpenThread &&+ !isActive;const isDisabled =mode !== NAVIGATION_DRAWER_TABS.NAVIGATION_MENU &&isLayoutCustomizationModeEnabled;@@ -156,7 +167,7 @@ export const MainNavigationDrawerModeSwitcher = () => {type="button"isActive={isActive}isExpanded={isExpanded}- aria-label={label}+ aria-label={isUnread ? t`${label}, unread` : label}aria-current={isActive}aria-disabled={isDisabled}onClick={() => {@@ -169,6 +180,7 @@ export const MainNavigationDrawerModeSwitcher = () => {><StyledModeIcon><Icon size={theme.icon.size.md} />+ {isUnread && <StyledNavigationDrawerUnreadDot />}</StyledModeIcon><StyledModeLabelinitial={false}diff --git a/packages/twenty-front/src/modules/navigation/components/__tests__/MainNavigationDrawerModeSwitcher.test.tsx b/packages/twenty-front/src/modules/navigation/components/__tests__/MainNavigationDrawerModeSwitcher.test.tsxindex 9a4dbac7ac9..b14d690190c 100644--- a/packages/twenty-front/src/modules/navigation/components/__tests__/MainNavigationDrawerModeSwitcher.test.tsx+++ b/packages/twenty-front/src/modules/navigation/components/__tests__/MainNavigationDrawerModeSwitcher.test.tsx@@ -5,6 +5,8 @@ import { act, render, screen } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { IconComment, IconHome, IconSettings } from 'twenty-ui/icon';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { setAgentChatThreadList } from '@/ai/testing/setAgentChatThreadList';import { isLayoutCustomizationModeEnabledState } from '@/layout-customization/states/isLayoutCustomizationModeEnabledState';import { MainNavigationDrawerModeSwitcher } from '@/navigation/components/MainNavigationDrawerModeSwitcher';import { useActiveNavigationDrawerMode } from '@/navigation/hooks/useActiveNavigationDrawerMode';@@ -25,6 +27,33 @@ jest.mock('twenty-ui/utilities', () => ({const mockSwitchNavigationDrawerMode = jest.fn();+const THREAD_ID = 'thread-1';+const LAST_ACTIVITY_AT = '2026-10-01T10:00:00.000Z';++const receiveOpenChat = (+ store: ReturnType<typeof createStore>,+ lastReadAt: string | null,+) => {+ setAgentChatThreadList(store, [+ {+ __typename: 'AgentChatThread',+ id: THREAD_ID,+ deletedAt: null,+ lastActivityAt: LAST_ACTIVITY_AT,+ } as never,+ ]);+ store.set(agentChatThreadParticipantsState.atom, {+ [THREAD_ID]: {+ threadId: THREAD_ID,+ lastReadAt,+ archivedAt: null,+ snoozedUntil: null,+ id: 'participant-id',+ updatedAt: LAST_ACTIVITY_AT,+ },+ });+};+const renderModeSwitcher = (isLayoutCustomizationModeEnabled = false) => {const store = createStore();@@ -137,6 +166,31 @@ describe('MainNavigationDrawerModeSwitcher', () => {},);+ it('marks the inbox while one of its open chats is unread', () => {+ const { store } = renderModeSwitcher();++ act(() => receiveOpenChat(store, null));++ expect(+ screen.getByRole('button', { name: 'AI, unread' }),+ ).toBeInTheDocument();++ act(() => receiveOpenChat(store, LAST_ACTIVITY_AT));++ expect(screen.getByRole('button', { name: 'AI' })).toBeInTheDocument();+ });++ it('does not mark the inbox while it is open', () => {+ jest+ .mocked(useActiveNavigationDrawerMode)+ .mockReturnValue(NAVIGATION_DRAWER_TABS.AI_CHAT_HISTORY);+ const { store } = renderModeSwitcher();++ act(() => receiveOpenChat(store, null));++ expect(screen.getByRole('button', { name: 'AI' })).toBeInTheDocument();+ });+it('renders nothing when no mode is available', () => {jest.mocked(useNavigationDrawerModes).mockReturnValue([]);diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsxindex cb942a85270..ac4de4e234b 100644--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker.tsx@@ -8,10 +8,8 @@ import { themeCssVariables } from 'twenty-ui/theme';import { useAgentChatThreadParticipants } from '@/ai/hooks/useAgentChatThreadParticipants';import { useFormatAgentChatThreadDate } from '@/ai/hooks/useFormatAgentChatThreadDate';-import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';import { DateTimePicker } from '@/ui/input/components/internal/date/components/DateTimePicker';import { useUserTimezone } from '@/ui/input/components/internal/date/hooks/useUserTimezone';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';const StyledContainer = styled.div`display: flex;@@ -35,9 +33,6 @@ export const SnoozeAiChatUntilDatePicker = ({const { formatAgentChatThreadDateTime } = useFormatAgentChatThreadDate();const { userTimezone } = useUserTimezone();const dateTimePickerInstanceId = useId();- const agentChatThreadInboxNow = useAtomStateValue(- agentChatThreadInboxNowState,- );// Starts on tomorrow morning, like the Tomorrow optionconst [snoozedUntil, setSnoozedUntil] = useState(() =>Temporal.Now.plainDateISO(userTimezone)@@ -48,21 +43,26 @@ export const SnoozeAiChatUntilDatePicker = ({}),);+ // Read on each interaction rather than on a clock, so a picked time that+ // passes while the picker is open shows as past once it is used+ const [checkedAt, setCheckedAt] = useState(() => Date.now());+const snoozedUntilDate = new Date(snoozedUntil.epochMilliseconds);- // The inbox clock ticks, so a time that passes while the picker is open turns the button off- const isInFuture =- snoozedUntil.epochMilliseconds >- Math.max(agentChatThreadInboxNow, Date.now());+ const isInFuture = snoozedUntil.epochMilliseconds > checkedAt;const snoozedUntilLabel = formatAgentChatThreadDateTime(snoozedUntilDate);const handleChange = (date: Temporal.ZonedDateTime | null) => {if (isDefined(date)) {setSnoozedUntil(date);+ setCheckedAt(Date.now());}};const handleSnooze = () => {- if (snoozedUntilDate <= new Date()) {+ const now = Date.now();++ if (snoozedUntil.epochMilliseconds <= now) {+ setCheckedAt(now);return;}diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsxindex 3d43e58ceff..8302f603b41 100644--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SidePanelSnoozeAiChatPage.test.tsx@@ -6,7 +6,6 @@ import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';import { MemoryRouter } from 'react-router-dom';-import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';import { SidePanelSnoozeAiChatPage } from '@/side-panel/pages/snooze-ai-chat/components/SidePanelSnoozeAiChatPage';import { snoozeAiChatThreadIdsComponentState } from '@/side-panel/pages/snooze-ai-chat/states/snoozeAiChatThreadIdsComponentState';import { SidePanelPageComponentInstanceContext } from '@/side-panel/states/contexts/SidePanelPageComponentInstanceContext';@@ -46,7 +45,6 @@ describe('SidePanelSnoozeAiChatPage', () => {jest.setSystemTime(new Date(2026, 9, 1, 17, 59));jest.clearAllMocks();resetJotaiStore();- jotaiStore.set(agentChatThreadInboxNowState.atom, Date.now());jotaiStore.set(snoozeAiChatThreadIdsComponentState.atomFamily({ instanceId: PAGE_ID }),['thread-1', 'thread-2'],diff --git a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsxindex 297432dafaf..e805b3e9df6 100644--- a/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx+++ b/packages/twenty-front/src/modules/side-panel/pages/snooze-ai-chat/components/__tests__/SnoozeAiChatUntilDatePicker.test.tsx@@ -1,11 +1,10 @@import { i18n } from '@lingui/core';import { I18nProvider } from '@lingui/react';-import { act, fireEvent, render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import { Provider as JotaiProvider } from 'jotai';import { type ReactNode } from 'react';import { Temporal } from 'temporal-polyfill';-import { agentChatThreadInboxNowState } from '@/ai/states/agentChatThreadInboxNowState';import { SnoozeAiChatUntilDatePicker } from '@/side-panel/pages/snooze-ai-chat/components/SnoozeAiChatUntilDatePicker';import {jotaiStore,@@ -61,7 +60,6 @@ describe('SnoozeAiChatUntilDatePicker', () => {jest.setSystemTime(new Date(2026, 9, 1, 17, 59));jest.clearAllMocks();resetJotaiStore();- jotaiStore.set(agentChatThreadInboxNowState.atom, Date.now());});afterEach(() => {@@ -107,7 +105,7 @@ describe('SnoozeAiChatUntilDatePicker', () => {expect(onSnoozed).not.toHaveBeenCalled();});- it('turns the button off once the picked time passes', () => {+ it('does not snooze once the picked time has passed, and says so', () => {render(<SnoozeAiChatUntilDatePickerthreadIds={['thread-1']}@@ -116,11 +114,12 @@ describe('SnoozeAiChatUntilDatePicker', () => {{ wrapper: Wrapper },);- act(() => {- jest.setSystemTime(new Date(2026, 9, 2, 9, 1));- jotaiStore.set(agentChatThreadInboxNowState.atom, Date.now());- });+ jest.setSystemTime(new Date(2026, 9, 2, 9, 1));++ fireEvent.click(screen.getByRole('button', { name: /Snooze until/ }));+ expect(snoozeAgentChatThreads).not.toHaveBeenCalled();+ expect(onSnoozed).not.toHaveBeenCalled();expect(screen.getByRole('button', { name: 'Pick a time in the future' }),).toBeDisabled();diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsxindex a8ae78dff1b..66f122095a0 100644--- a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/NavigationDrawerItem.tsx@@ -5,6 +5,7 @@ import { useIsNavigationDrawerContentExpanded } from '@/navigation/hooks/useIsNaimport { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';import { NavigationDrawerAnimatedCollapseWrapper } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerAnimatedCollapseWrapper';import { NavigationDrawerItemBreadcrumb } from '@/ui/navigation/navigation-drawer/components/NavigationDrawerItemBreadcrumb';+import { StyledNavigationDrawerUnreadDot } from '@/ui/navigation/navigation-drawer/components/StyledNavigationDrawerUnreadDot';import { NAVIGATION_DRAWER_COLLAPSED_BUTTON_SIZE } from '@/ui/navigation/navigation-drawer/constants/NavigationDrawerCollapsedButtonSize';import { NavigationDrawerItemEditingContext } from '@/ui/navigation/navigation-drawer/contexts/NavigationDrawerItemEditingContext';import { useNavigationDrawerTooltip } from '@/ui/navigation/navigation-drawer/hooks/useNavigationDrawerTooltip';@@ -167,17 +168,6 @@ const StyledIcon = styled.div`position: relative;`;-// A collapsed drawer hides the label, so an unread item is marked on its icon-const StyledCollapsedUnreadDot = styled.span`- background: ${themeCssVariables.color.blue};- border-radius: 50%;- height: 6px;- position: absolute;- right: -2px;- top: -2px;- width: 6px;-`;-const StyledRightOptionsContainer = styled.div`align-items: center;border-radius: ${themeCssVariables.border.radius.md};@@ -363,7 +353,9 @@ export const NavigationDrawerItem = ({: 'currentColor'}/>- {isUnread && !isExpanded && <StyledCollapsedUnreadDot />}+ {isUnread && !isExpanded && (+ <StyledNavigationDrawerUnreadDot />+ )}</StyledIcon>))}diff --git a/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/StyledNavigationDrawerUnreadDot.tsx b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/StyledNavigationDrawerUnreadDot.tsxnew file mode 100644index 00000000000..8fc59087fc0--- /dev/null+++ b/packages/twenty-front/src/modules/ui/navigation/navigation-drawer/components/StyledNavigationDrawerUnreadDot.tsx@@ -0,0 +1,14 @@+import { styled } from '@linaria/react';+import { themeCssVariables } from 'twenty-ui/theme';++// Marks an icon as unread where no label can show it, so its parent must be+// positioned+export const StyledNavigationDrawerUnreadDot = styled.span`+ background: ${themeCssVariables.color.blue};+ border-radius: 50%;+ height: 6px;+ position: absolute;+ right: -2px;+ top: -2px;+ width: 6px;+`;diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.tsindex 2901bf10aaa..012650fdc62 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module.ts@@ -6,6 +6,8 @@ import { AddAgentChatThreadParticipantObjectCommand } from 'src/database/commandimport { BackfillAgentChatThreadInboxStateCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.command';import { AddAiChatInboxCommandMenuItemsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019633-add-ai-chat-inbox-command-menu-items.command';import { AllowAiChatInboxCommandsOnSeveralChatsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791009973891-allow-ai-chat-inbox-commands-on-several-chats.command';+import { MakeAgentChatThreadParticipantsPrivateCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command';+import { ScheduleAgentChatThreadSnoozeEndsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command';import { UnpinNewAiChatCommandMenuItemCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1790942019634-unpin-new-ai-chat-command-menu-item.command';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@@ -25,6 +27,8 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspaceAddAiChatInboxCommandMenuItemsCommand,UnpinNewAiChatCommandMenuItemCommand,AllowAiChatInboxCommandsOnSeveralChatsCommand,+ MakeAgentChatThreadParticipantsPrivateCommand,+ ScheduleAgentChatThreadSnoozeEndsCommand,],})export class V2_46_UpgradeVersionCommandModule {}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command.tsnew file mode 100644index 00000000000..83df876d522--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command.ts@@ -0,0 +1,229 @@+import { Command } from 'nest-commander';+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { MetadataReadability } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { type EntityManager } from 'typeorm';++import { AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';++const getTables = (workspaceId: string) => {+ const schema = escapeIdentifier(getWorkspaceSchemaName(workspaceId));++ return {+ participant: `${schema}."agentChatThreadParticipant"`,+ recordShare: `${schema}."recordShare"`,+ workspaceMember: `${schema}."workspaceMember"`,+ };+};++// Every row a member of the workspace still holds gets the grant that lets+// them, and only them, read it+const insertParticipantOwnerShares = async ({+ manager,+ workspaceId,+ participantObjectMetadataId,+}: {+ manager: EntityManager;+ workspaceId: string;+ participantObjectMetadataId: string;+}): Promise<number> => {+ const tables = getTables(workspaceId);++ const inserted: { id: string }[] = await manager.query(+ `INSERT INTO ${tables.recordShare}+ ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")+ SELECT $1, participant.id, participant."workspaceMemberId", 'WORKSPACE_MEMBER', 'FULL', 'OWNER', participant.id+ FROM ${tables.participant} participant+ JOIN ${tables.workspaceMember} member+ ON member.id = participant."workspaceMemberId" AND member."deletedAt" IS NULL+ ON CONFLICT DO NOTHING+ RETURNING id`,+ [participantObjectMetadataId],+ );++ return inserted.length;+};++const deleteParticipantOwnerShares = async ({+ manager,+ workspaceId,+ participantObjectMetadataId,+}: {+ manager: EntityManager;+ workspaceId: string;+ participantObjectMetadataId: string;+}): Promise<number> => {+ const tables = getTables(workspaceId);++ const [, deletedCount]: [unknown[], number] = await manager.query(+ `DELETE FROM ${tables.recordShare}+ WHERE "objectMetadataId" = $1 AND "rowCause" = 'OWNER'`,+ [participantObjectMetadataId],+ );++ return deletedCount;+};++@RegisteredWorkspaceCommand('2.46.0', 1791056679663)+@Command({+ name: 'upgrade:2-46:make-agent-chat-thread-participants-private',+ description:+ "Grant every chat participant row to its member and make the object PRIVATE, so a member's inbox state reaches their open apps through record events",+})+export class MakeAgentChatThreadParticipantsPrivateCommand extends ProvisionedWorkspaceCommandRunner {+ constructor(+ protected readonly workspaceIteratorService: WorkspaceIteratorService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,+ private readonly storage: AgentHistoryUpgradeStorageService,+ ) {+ super(workspaceIteratorService);+ }++ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {+ await this.up(args);+ }++ // Grants first, so the object is never PRIVATE with rows nobody can read+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ const participantObject = await this.findParticipantObject(workspaceId);++ if (!isDefined(participantObject)) {+ return;+ }++ if (options.dryRun ?? false) {+ this.logger.log(+ `[DRY RUN] Would grant chat participants to their members and make them PRIVATE for workspace ${workspaceId}`,+ );++ return;+ }++ const grantCount = await this.storage.run(workspaceId, ({ manager }) =>+ insertParticipantOwnerShares({+ manager,+ workspaceId,+ participantObjectMetadataId: participantObject.id,+ }),+ );++ await this.setReadability({+ workspaceId,+ participantObject,+ readability: MetadataReadability.PRIVATE,+ });++ this.logger.log(+ `Workspace ${workspaceId}: granted ${grantCount} chat participant row(s) to their members and made the object PRIVATE`,+ );+ }++ async down({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ const participantObject = await this.findParticipantObject(workspaceId);++ if (!isDefined(participantObject)) {+ return;+ }++ if (options.dryRun ?? false) {+ this.logger.log(+ `[DRY RUN] Would make chat participants SYSTEM again and remove their grants for workspace ${workspaceId}`,+ );++ return;+ }++ await this.setReadability({+ workspaceId,+ participantObject,+ readability: MetadataReadability.SYSTEM,+ });++ const deletedCount = await this.storage.run(workspaceId, ({ manager }) =>+ deleteParticipantOwnerShares({+ manager,+ workspaceId,+ participantObjectMetadataId: participantObject.id,+ }),+ );++ this.logger.log(+ `Workspace ${workspaceId}: made chat participants SYSTEM again and removed ${deletedCount} grant(s)`,+ );+ }++ private async findParticipantObject(+ workspaceId: string,+ ): Promise<FlatObjectMetadata | undefined> {+ const { flatObjectMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ ]);++ const participantObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier+ ];++ if (!isDefined(participantObject)) {+ this.logger.log(+ `agentChatThreadParticipant object not found for workspace ${workspaceId}, skipping`,+ );+ }++ return participantObject;+ }++ private async setReadability({+ workspaceId,+ participantObject,+ readability,+ }: {+ workspaceId: string;+ participantObject: FlatObjectMetadata;+ readability: MetadataReadability;+ }): Promise<void> {+ if (participantObject.readability === readability) {+ return;+ }++ const result =+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(+ {+ workspaceId,+ isSystemBuild: true,+ applicationUniversalIdentifier:+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,+ allFlatEntityOperationByMetadataName: {+ objectMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: [+ {+ ...participantObject,+ readability,+ updatedAt: new Date().toISOString(),+ },+ ],+ },+ },+ },+ );++ if (result.status === 'fail') {+ throw new WorkspaceMigrationBuilderException(result);+ }+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command.tsnew file mode 100644index 00000000000..5114080dbb2--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command.ts@@ -0,0 +1,109 @@+import { Command } from 'nest-commander';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { isDefined } from 'twenty-shared/utils';++import { AgentHistoryUpgradeStorageService } from 'src/database/commands/agent-history/agent-history-upgrade-storage.service';+import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';+import { AGENT_CHAT_THREAD_SNOOZE_END_JOB_RETRY_OPTIONS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-job-retry-options.constant';+import { END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant';+import { type EndAgentChatThreadSnoozeJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';++type PendingSnooze = {+ threadId: string;+ workspaceMemberId: string;+ snoozedUntil: Date;+ remainingDelay: number;+};++// Snoozes saved before snoozing queued its own end have nothing to bring the+// chat back to the inbox of an app that stays open+@RegisteredWorkspaceCommand('2.46.0', 1791093059050)+@Command({+ name: 'upgrade:2-46:schedule-agent-chat-thread-snooze-ends',+ description:+ 'Queue the end of every chat snooze still pending, so open apps see the chat come back',+})+export class ScheduleAgentChatThreadSnoozeEndsCommand extends ProvisionedWorkspaceCommandRunner {+ constructor(+ protected readonly workspaceIteratorService: WorkspaceIteratorService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly storage: AgentHistoryUpgradeStorageService,+ @InjectMessageQueue(MessageQueue.delayedJobsQueue)+ private readonly delayedJobsQueueService: MessageQueueService,+ ) {+ super(workspaceIteratorService);+ }++ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {+ await this.up(args);+ }++ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ if (!(await this.hasParticipantObject(workspaceId))) {+ return;+ }++ const pendingSnoozes = await this.storage.run(workspaceId, ({ manager }) =>+ manager.query<PendingSnooze[]>(+ `SELECT "threadId", "workspaceMemberId", "snoozedUntil",+ CEIL(EXTRACT(EPOCH FROM "snoozedUntil" - clock_timestamp()) * 1000)::float8 AS "remainingDelay"+ FROM ${escapeIdentifier(getWorkspaceSchemaName(workspaceId))}."agentChatThreadParticipant"+ WHERE "archivedAt" IS NOT NULL AND "snoozedUntil" > clock_timestamp()`,+ ),+ );++ if (options.dryRun ?? false) {+ this.logger.log(+ `[DRY RUN] Would queue the end of ${pendingSnoozes.length} chat snooze(s) for workspace ${workspaceId}`,+ );++ return;+ }++ // The end of a snooze the member changed since finds nothing to end+ for (const { remainingDelay, snoozedUntil, ...snooze } of pendingSnoozes) {+ await this.delayedJobsQueueService.add<EndAgentChatThreadSnoozeJobData>(+ END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME,+ { ...snooze, workspaceId, snoozedUntil: snoozedUntil.toISOString() },+ {+ delay: remainingDelay,+ ...AGENT_CHAT_THREAD_SNOOZE_END_JOB_RETRY_OPTIONS,+ },+ );+ }++ this.logger.log(+ `Workspace ${workspaceId}: queued the end of ${pendingSnoozes.length} chat snooze(s)`,+ );+ }++ // Queued ends only send what is already true by then, so there is nothing+ // to undo+ async down({ workspaceId }: RunOnWorkspaceArgs): Promise<void> {+ this.logger.log(+ `Workspace ${workspaceId}: queued chat snooze ends are left to run`,+ );+ }++ private async hasParticipantObject(workspaceId: string): Promise<boolean> {+ const { flatObjectMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ ]);++ return isDefined(+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier+ ],+ );+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.tsindex 0307b186745..aaa1648fcd7 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/agent-chat-thread.module.ts@@ -3,7 +3,9 @@ import { Module } from '@nestjs/common';import { RecordShareStorageModule } from 'src/engine/core-modules/record-share/record-share-storage.module';import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';import { AgentChatThreadLifecycleModule } from 'src/engine/metadata-modules/ai/ai-chat/agent-chat-thread-lifecycle.module';+import { EndAgentChatThreadSnoozeJob } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze.job';import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';+import { AgentChatThreadParticipantEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service';import { AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';import { AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';import { AgentInboxService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-inbox.service';@@ -24,9 +26,11 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache],providers: [AgentChatSharingService,+ AgentChatThreadParticipantEventService,AgentChatThreadParticipantService,AgentChatThreadService,AgentInboxService,+ EndAgentChatThreadSnoozeJob,],exports: [AgentChatSharingService,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-job-retry-options.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-job-retry-options.constant.tsnew file mode 100644index 00000000000..41c1ee1c8de--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-job-retry-options.constant.ts@@ -0,0 +1,8 @@+import { type QueueJobOptions } from 'src/engine/core-modules/message-queue/drivers/interfaces/job-options.interface';++// Open apps only learn a snooze ended from this job, so a passing failure+// must not lose it+export const AGENT_CHAT_THREAD_SNOOZE_END_JOB_RETRY_OPTIONS = {+ retryLimit: 5,+ backoff: { strategy: 'exponential', initialDelayMilliseconds: 1_000 },+} as const satisfies Pick<QueueJobOptions, 'retryLimit' | 'backoff'>;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-recheck-minimum-delay-ms.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-recheck-minimum-delay-ms.constant.tsnew file mode 100644index 00000000000..e00f3d353bb--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-recheck-minimum-delay-ms.constant.ts@@ -0,0 +1,3 @@+// Keeps a snooze end that runs before the database clock reaches it from+// checking again in a tight loop+export const AGENT_CHAT_THREAD_SNOOZE_END_RECHECK_MINIMUM_DELAY_MS = 100;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto.tsindex ab7161897ac..ff0b5c5d479 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto.ts@@ -4,6 +4,9 @@ import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/@ObjectType('AgentChatThreadParticipant')export class AgentChatThreadParticipantDTO {+ @Field(() => UUIDScalarType)+ id: string;+@Field(() => UUIDScalarType)threadId: string;@@ -15,4 +18,8 @@ export class AgentChatThreadParticipantDTO {@Field(() => Date, { nullable: true })snoozedUntil: Date | null;++ // Orders the copies a member's apps receive, so an older one never wins+ @Field(() => Date)+ updatedAt: Date;}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant.tsnew file mode 100644index 00000000000..6ccb40e3c95--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant.ts@@ -0,0 +1,2 @@+export const END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME =+ 'EndAgentChatThreadSnoozeJob';diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types.tsnew file mode 100644index 00000000000..228f0aa1a89--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types.ts@@ -0,0 +1,5 @@+import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';++export type EndAgentChatThreadSnoozeJobData = AgentChatThreadAccessArgs & {+ snoozedUntil: string;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze.job.tsnew file mode 100644index 00000000000..e1222a74cff--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze.job.ts@@ -0,0 +1,18 @@+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';+import { END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant';+import { type EndAgentChatThreadSnoozeJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types';+import { AgentChatThreadParticipantService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service';++@Processor(MessageQueue.delayedJobsQueue)+export class EndAgentChatThreadSnoozeJob {+ constructor(+ private readonly participantService: AgentChatThreadParticipantService,+ ) {}++ @Process(END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME)+ async handle(data: EndAgentChatThreadSnoozeJobData): Promise<void> {+ await this.participantService.endSnooze(data);+ }+}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 36149e5a1c8..ab1917a12d4 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,6 @@import { AuthException } from 'src/engine/core-modules/auth/auth.exception';import { randomUUID } from 'node:crypto';+import { buildAgentChatThreadParticipantOwnerShareInsert } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util';import { getAgentChatThreadParticipantTable } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-chat-thread-participant-table.util';import { backfillWorkspaceChatThreadOwnerGrants } from 'src/engine/metadata-modules/ai/ai-chat/utils/backfill-workspace-chat-thread-owner-grants.util';import { Injectable } from '@nestjs/common';@@ -45,17 +46,21 @@ export class AgentChatSharingService {// workspace, it has neither the participant table nor the thread's// lastActivityAt column. Remove once 2.46 leaves the window.async hasInboxState(workspaceId: string): Promise<boolean> {+ return isDefined(await this.findParticipantObjectMetadataId(workspaceId));+ }++ async findParticipantObjectMetadataId(+ workspaceId: string,+ ): Promise<string | undefined> {const { flatObjectMetadataMaps } =await this.workspaceCacheService.getOrRecompute(workspaceId, ['flatObjectMetadataMaps',]);- return isDefined(- findAgentChatFlatObjectMetadata(- flatObjectMetadataMaps,- 'agentChatThreadParticipant',- ),- );+ return findAgentChatFlatObjectMetadata(+ flatObjectMetadataMaps,+ 'agentChatThreadParticipant',+ )?.id;}getReadableThread(args: AgentChatThreadAccessArgs) {@@ -129,7 +134,9 @@ export class AgentChatSharingService {}): Promise<AgentChatThreadWorkspaceEntity> {const authContext = await this.getAuthContext(args);const objectMetadata = await this.getThreadObjectMetadata(args.workspaceId);- const hasInboxState = await this.hasInboxState(args.workspaceId);+ const participantObjectMetadataId =+ await this.findParticipantObjectMetadataId(args.workspaceId);+ const hasInboxState = isDefined(participantObjectMetadataId);// workflowRunId is set by the server for a run conversation, never written by the memberawait this.workspaceOrmManager.executeInWorkspaceContext(@@ -179,9 +186,22 @@ export class AgentChatSharingService {}if (hasInboxState) {await manager.query(- `INSERT INTO ${getAgentChatThreadParticipantTable(args.workspaceId)} ("threadId", "workspaceMemberId", "lastReadAt")- VALUES ($1, $2, $3)`,- [record.id, authContext.workspaceMemberId, record.lastActivityAt],+ `WITH participant AS (+ INSERT INTO ${getAgentChatThreadParticipantTable(args.workspaceId)} ("threadId", "workspaceMemberId", "lastReadAt")+ VALUES ($1, $2, $3)+ RETURNING id, "workspaceMemberId"+ )+ ${buildAgentChatThreadParticipantOwnerShareInsert({+ workspaceId: args.workspaceId,+ participantSource: 'participant',+ objectMetadataIdParameter: '$4',+ })}`,+ [+ record.id,+ authContext.workspaceMemberId,+ record.lastActivityAt,+ participantObjectMetadataId,+ ],);}return record;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service.tsnew file mode 100644index 00000000000..cff0b07f665--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service.ts@@ -0,0 +1,98 @@+import { Injectable, Logger } from '@nestjs/common';++import { isDefined } from 'twenty-shared/utils';++import { DatabaseEventAction } from 'src/engine/api/graphql/graphql-query-runner/enums/database-event-action';+import { type AgentChatThreadParticipantRow } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type';+import { findAgentChatFlatObjectMetadata } from 'src/engine/metadata-modules/ai/ai-chat/utils/find-agent-chat-flat-object-metadata.util';+import { formatTwentyOrmEventToDatabaseBatchEvent } from 'src/engine/twenty-orm/utils/format-twenty-orm-event-to-database-batch-event.util';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';++type ParticipantWrite = {+ before: AgentChatThreadParticipantRow | null;+ after: AgentChatThreadParticipantRow;+};++// Participant rows are written in SQL, outside the ORM that would send these+@Injectable()+export class AgentChatThreadParticipantEventService {+ private readonly logger = new Logger(+ AgentChatThreadParticipantEventService.name,+ );++ constructor(+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workspaceEventEmitter: WorkspaceEventEmitter,+ ) {}++ // Sent once the write has committed, so a failure here must not report the+ // write itself as failed+ async emitParticipantWritten(+ args: ParticipantWrite & { workspaceId: string },+ ): Promise<void> {+ try {+ await this.emit(args);+ } catch (error) {+ this.logger.error(+ `Could not send the chat participant change of workspace ${args.workspaceId}`,+ error,+ );+ }+ }++ private async emit({+ workspaceId,+ before,+ after,+ }: ParticipantWrite & { workspaceId: string }): Promise<void> {+ const { flatObjectMetadataMaps, flatFieldMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ ]);+ const objectMetadata = findAgentChatFlatObjectMetadata(+ flatObjectMetadataMaps,+ 'agentChatThreadParticipant',+ );++ if (!isDefined(objectMetadata)) {+ return;+ }++ const event = formatTwentyOrmEventToDatabaseBatchEvent({+ action: isDefined(before)+ ? DatabaseEventAction.UPDATED+ : DatabaseEventAction.CREATED,+ objectMetadataItem: objectMetadata,+ flatFieldMetadataMaps,+ workspaceId,+ recordsBefore: isDefined(before) ? [before] : undefined,+ recordsAfter: [after],+ });++ if (!isDefined(event)) {+ return;+ }++ // Changes can be delivered out of order, and apps keep only the most+ // recent version of a row, so each change carries its version+ this.workspaceEventEmitter.emitDatabaseBatchEvent({+ ...event,+ events: event.events.map((recordEvent) =>+ 'updatedFields' in recordEvent.properties+ ? {+ ...recordEvent,+ properties: {+ ...recordEvent.properties,+ updatedFields: [+ ...(recordEvent.properties.updatedFields ?? []),+ 'updatedAt',+ ],+ },+ }+ : recordEvent,+ ),+ });+ }+}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.tsindex ae1c47c3766..da8dcc8d2be 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant.service.ts@@ -1,12 +1,23 @@import { Injectable } from '@nestjs/common';import { isDefined } from 'twenty-shared/utils';+import { type EntityManager } from 'typeorm';+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';import { AGENT_CHAT_THREAD_ACTIVITY_COLUMNS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-activity-columns.constant';+import { AGENT_CHAT_THREAD_SNOOZE_END_JOB_RETRY_OPTIONS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-job-retry-options.constant';+import { AGENT_CHAT_THREAD_SNOOZE_END_RECHECK_MINIMUM_DELAY_MS } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-snooze-end-recheck-minimum-delay-ms.constant';import { type AgentChatThreadParticipantDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto';+import { END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant';+import { type EndAgentChatThreadSnoozeJobData } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job.types';import { AgentChatSharingService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service';+import { AgentChatThreadParticipantEventService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread-participant-event.service';import { type AgentChatThreadAccessArgs } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-access-args.type';+import { type AgentChatThreadParticipantRow } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type';import { type AgentChatThreadActivity } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-activity.type';+import { buildAgentChatThreadParticipantOwnerShareInsert } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util';import { buildAgentChatThreadActivitySetClause } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-activity-set-clause.util';import { getAgentChatThreadParticipantTable } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-chat-thread-participant-table.util';import { throwAgentChatThreadNotFound } from 'src/engine/metadata-modules/ai/ai-chat/utils/throw-agent-chat-thread-not-found.util';@@ -19,16 +30,37 @@ import {AiExceptionCode,} from 'src/engine/metadata-modules/ai/ai.exception';-const PARTICIPANT_COLUMNS = `"threadId", "lastReadAt", "archivedAt", "snoozedUntil"`;+type BuildParticipantWriteQuery = (tables: {+ participantTable: string;+ threadTable: string;+}) => string;++// A snooze whose end is already due, which its queued end may have checked+// before this write, is saved as ended+const buildArchiveQuery: BuildParticipantWriteQuery = ({ participantTable }) =>+ `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil")+ VALUES ($1, $2, CASE WHEN $3::timestamptz <= clock_timestamp() THEN NULL ELSE clock_timestamp() END, $3)+ ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET+ "archivedAt" = EXCLUDED."archivedAt",+ "snoozedUntil" = EXCLUDED."snoozedUntil",+ "updatedAt" = now()+ RETURNING *`;++const PARTICIPANT_COLUMNS = `id, "workspaceMemberId", "threadId", "lastReadAt", "archivedAt", "snoozedUntil", "updatedAt"`;// Timestamps compared against thread.lastActivityAt are stamped by Postgres-// (clock_timestamp), so ordering follows the database rather than app servers+// (clock_timestamp), so ordering follows the database rather than app servers.+// Every row is granted to its member, and every change to it is sent as a+// record event, which only that member is let through to receive.@Injectable()export class AgentChatThreadParticipantService {constructor(@InjectAgentHistoryRepository('agentChatThread')private readonly threadRepository: AgentHistoryRepository<AgentChatThreadWorkspaceEntity>,private readonly sharingService: AgentChatSharingService,+ private readonly participantEventService: AgentChatThreadParticipantEventService,+ @InjectMessageQueue(MessageQueue.delayedJobsQueue)+ private readonly delayedJobsQueueService: MessageQueueService,) {}// A member keeps their row after losing access to a thread, so rows are@@ -43,9 +75,11 @@ export class AgentChatThreadParticipantService {return [];}+ // A snooze is ended by a queued job, which may not have run yetconst rows = await this.threadRepository.query(workspaceId, ({ manager }) =>manager.query<AgentChatThreadParticipantDTO[]>(- `SELECT ${PARTICIPANT_COLUMNS}+ `SELECT id, "threadId", "lastReadAt", "snoozedUntil", "updatedAt",+ CASE WHEN "snoozedUntil" <= clock_timestamp() THEN NULL ELSE "archivedAt" END AS "archivedAt"FROM ${getAgentChatThreadParticipantTable(workspaceId)}WHERE "workspaceMemberId" = $1`,[workspaceMemberId],@@ -75,7 +109,7 @@ export class AgentChatThreadParticipantService {ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET"lastReadAt" = GREATEST(participant."lastReadAt", EXCLUDED."lastReadAt"),"updatedAt" = now()- RETURNING ${PARTICIPANT_COLUMNS}`,+ RETURNING *`,);}@@ -90,7 +124,7 @@ export class AgentChatThreadParticipantService {ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET"lastReadAt" = NULL,"updatedAt" = now()- RETURNING ${PARTICIPANT_COLUMNS}`,+ RETURNING *`,);}@@ -113,9 +147,89 @@ export class AgentChatThreadParticipantService {);}+ await this.assertCanWriteInboxState(args);++ // Queued before the write, so no saved snooze lacks its end; the end of+ // a snooze that was never saved finds nothing to end+ await this.scheduleSnoozeEnd({+ ...args,+ snoozedUntil: snoozedUntil.toISOString(),+ delay: Math.max(snoozedUntil.getTime() - Date.now(), 0),+ });+return this.setArchive(args, snoozedUntil);}+ // A snooze ends by moving the chat back to the inbox. The snooze stays+ // recorded, as what brought it back.+ async endSnooze({+ snoozedUntil,+ ...args+ }: EndAgentChatThreadSnoozeJobData): Promise<void> {+ const remainingDelay = await this.findRemainingSnoozeDelay({+ workspaceId: args.workspaceId,+ snoozedUntil,+ });++ // This server's clock ran ahead of the database's+ if (remainingDelay > 0) {+ await this.scheduleSnoozeEnd({+ ...args,+ snoozedUntil,+ delay: Math.max(+ remainingDelay,+ AGENT_CHAT_THREAD_SNOOZE_END_RECHECK_MINIMUM_DELAY_MS,+ ),+ });++ return;+ }++ const [readableThreadId] = await this.sharingService.findReadableThreadIds({+ workspaceId: args.workspaceId,+ workspaceMemberId: args.workspaceMemberId,+ threadIds: [args.threadId],+ });++ if (!isDefined(readableThreadId)) {+ return;+ }++ // A snooze the member replaced or cleared since has nothing to end+ await this.writeOne(+ args,+ ({ participantTable }) =>+ `UPDATE ${participantTable}+ SET "archivedAt" = NULL, "updatedAt" = now()+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2+ AND "snoozedUntil" = $3 AND "archivedAt" IS NOT NULL+ RETURNING *`,+ [snoozedUntil],+ );+ }++ // For the row written along with a new thread+ async emitParticipantCreated(args: AgentChatThreadAccessArgs): Promise<void> {+ if (!(await this.sharingService.hasInboxState(args.workspaceId))) {+ return;+ }++ const participant = await this.threadRepository.query(+ args.workspaceId,+ ({ manager }) => this.findOne({ manager, ...args }),+ );++ if (!isDefined(participant)) {+ return;+ }++ await this.participantEventService.emitParticipantWritten({+ workspaceId: args.workspaceId,+ before: null,+ after: participant,+ });+ }+async moveToInbox(args: AgentChatThreadAccessArgs,): Promise<AgentChatThreadParticipantDTO> {@@ -128,7 +242,7 @@ export class AgentChatThreadParticipantService {"archivedAt" = NULL,"snoozedUntil" = NULL,"updatedAt" = now()- RETURNING ${PARTICIPANT_COLUMNS}`,+ RETURNING *`,);}@@ -153,11 +267,21 @@ export class AgentChatThreadParticipantService {}const participantTable = getAgentChatThreadParticipantTable(workspaceId);+ const participantObjectMetadataId =+ await this.sharingService.findParticipantObjectMetadataId(workspaceId);- const rows = await this.threadRepository.query(+ const { rows, before, after } = await this.threadRepository.query(workspaceId,- ({ manager, table }) =>- manager.query<AgentChatThreadActivity[]>(+ async ({ manager, table }) => {+ const before = await this.findOne({+ manager,+ workspaceId,+ workspaceMemberId,+ threadId,+ lock: true,+ });++ const rows = await manager.query<AgentChatThreadActivity[]>(`WITH thread AS (UPDATE ${table('agentChatThread')}SET "updatedAt" = now(),@@ -176,45 +300,123 @@ export class AgentChatThreadParticipantService {"archivedAt" = NULL,"snoozedUntil" = NULL,"updatedAt" = now()+ RETURNING id, "workspaceMemberId"+ ), owner_share AS (+ ${buildAgentChatThreadParticipantOwnerShareInsert({ workspaceId, participantSource: 'participant', objectMetadataIdParameter: '$4' })})SELECT ${AGENT_CHAT_THREAD_ACTIVITY_COLUMNS} FROM thread`,- [threadId, workspaceMemberId, text],- ),+ [threadId, workspaceMemberId, text, participantObjectMetadataId],+ );++ const after = await this.findOne({+ manager,+ workspaceId,+ workspaceMemberId,+ threadId,+ });++ return { rows, before, after };+ },);if (rows.length !== 1) {return throwAgentChatThreadNotFound();}+ if (isDefined(after)) {+ await this.participantEventService.emitParticipantWritten({+ workspaceId,+ before,+ after,+ });+ }+return rows[0];}+ private async scheduleSnoozeEnd({+ delay,+ ...data+ }: EndAgentChatThreadSnoozeJobData & { delay: number }): Promise<void> {+ await this.delayedJobsQueueService.add<EndAgentChatThreadSnoozeJobData>(+ END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME,+ data,+ { delay, ...AGENT_CHAT_THREAD_SNOOZE_END_JOB_RETRY_OPTIONS },+ );+ }++ private async findOne({+ manager,+ workspaceId,+ workspaceMemberId,+ threadId,+ lock = false,+ }: AgentChatThreadAccessArgs & {+ manager: EntityManager;+ lock?: boolean;+ }): Promise<AgentChatThreadParticipantRow | null> {+ // Also taken when the row does not exist yet, so two first writes cannot+ // both send it as created+ if (lock) {+ await manager.query(+ 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',+ [+ `agent-chat-thread-participant:${workspaceId}:${threadId}:${workspaceMemberId}`,+ ],+ );+ }++ const [participant] = await manager.query<AgentChatThreadParticipantRow[]>(+ `SELECT ${PARTICIPANT_COLUMNS}+ FROM ${getAgentChatThreadParticipantTable(workspaceId)}+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,+ [threadId, workspaceMemberId],+ );++ return participant ?? null;+ }++ private async findRemainingSnoozeDelay({+ workspaceId,+ snoozedUntil,+ }: {+ workspaceId: string;+ snoozedUntil: string;+ }): Promise<number> {+ const [{ remainingDelay }] = await this.threadRepository.query(+ workspaceId,+ ({ manager }) =>+ manager.query<{ remainingDelay: number }[]>(+ `SELECT GREATEST(CEIL(EXTRACT(EPOCH FROM $1::timestamptz - clock_timestamp()) * 1000), 0)::int AS "remainingDelay"`,+ [snoozedUntil],+ ),+ );++ return remainingDelay;+ }+private setArchive(args: AgentChatThreadAccessArgs,snoozedUntil: Date | null,): Promise<AgentChatThreadParticipantDTO> {- return this.upsertOne(- args,- ({ participantTable }) =>- `INSERT INTO ${participantTable} AS participant ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil")- VALUES ($1, $2, clock_timestamp(), $3)- ON CONFLICT ("threadId", "workspaceMemberId") DO UPDATE SET- "archivedAt" = EXCLUDED."archivedAt",- "snoozedUntil" = EXCLUDED."snoozedUntil",- "updatedAt" = now()- RETURNING ${PARTICIPANT_COLUMNS}`,- [snoozedUntil],- );+ return this.upsertOne(args, buildArchiveQuery, [snoozedUntil]);}private async upsertOne(- { workspaceId, workspaceMemberId, threadId }: AgentChatThreadAccessArgs,- buildQuery: (tables: {- participantTable: string;- threadTable: string;- }) => string,+ args: AgentChatThreadAccessArgs,+ buildQuery: BuildParticipantWriteQuery,extraParameters: unknown[] = [],): Promise<AgentChatThreadParticipantDTO> {+ await this.assertCanWriteInboxState(args);++ return this.writeOneOrThrow(args, buildQuery, extraParameters);+ }++ private async assertCanWriteInboxState({+ workspaceId,+ workspaceMemberId,+ threadId,+ }: AgentChatThreadAccessArgs): Promise<void> {const [readableThreadId] = await this.sharingService.findReadableThreadIds({workspaceId,workspaceMemberId,@@ -231,23 +433,76 @@ export class AgentChatThreadParticipantService {AiExceptionCode.CHAT_THREAD_INBOX_STATE_UNAVAILABLE,);}+ }++ private async writeOneOrThrow(+ args: AgentChatThreadAccessArgs,+ buildQuery: BuildParticipantWriteQuery,+ extraParameters: unknown[],+ ): Promise<AgentChatThreadParticipantDTO> {+ return (+ (await this.writeOne(args, buildQuery, extraParameters)) ??+ throwAgentChatThreadNotFound()+ );+ }++ // The row is locked while it is read and written, so the change sent is+ // the one this write made+ private async writeOne(+ { workspaceId, workspaceMemberId, threadId }: AgentChatThreadAccessArgs,+ buildQuery: BuildParticipantWriteQuery,+ extraParameters: unknown[] = [],+ ): Promise<AgentChatThreadParticipantRow | null> {+ const parameters = [+ threadId,+ workspaceMemberId,+ ...extraParameters,+ await this.sharingService.findParticipantObjectMetadataId(workspaceId),+ ];- const rows = await this.threadRepository.query(+ const { before, after } = await this.threadRepository.query(workspaceId,- ({ manager, table }) =>- manager.query<AgentChatThreadParticipantDTO[]>(- buildQuery({- participantTable: getAgentChatThreadParticipantTable(workspaceId),- threadTable: table('agentChatThread'),- }),- [threadId, workspaceMemberId, ...extraParameters],- ),+ async ({ manager, table }) => {+ const before = await this.findOne({+ manager,+ workspaceId,+ workspaceMemberId,+ threadId,+ lock: true,+ });++ const [after] = await manager.query<AgentChatThreadParticipantRow[]>(+ `WITH written_participant AS (+ ${buildQuery({+ participantTable:+ getAgentChatThreadParticipantTable(workspaceId),+ threadTable: table('agentChatThread'),+ })}+ ), owner_share AS (+ ${buildAgentChatThreadParticipantOwnerShareInsert({+ workspaceId,+ participantSource: 'written_participant',+ objectMetadataIdParameter: `$${parameters.length}`,+ })}+ )+ SELECT ${PARTICIPANT_COLUMNS} FROM written_participant`,+ parameters,+ );++ return { before, after };+ },);- if (rows.length !== 1) {- return throwAgentChatThreadNotFound();+ if (!isDefined(after)) {+ return null;}- return rows[0];+ await this.participantEventService.emitParticipantWritten({+ workspaceId,+ before,+ after,+ });++ return after;}}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.tsindex eaad1b6c975..a5103d68805 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service.ts@@ -33,6 +33,13 @@ export class AgentChatThreadService {) {const savedThread = await this.sharingService.createThread(args);+ // Sent first, so the new thread never shows as unread to its owner+ await this.participantService.emitParticipantCreated({+ workspaceId: args.workspaceId,+ workspaceMemberId: args.workspaceMemberId,+ threadId: savedThread.id,+ });+await this.threadRecordEventService.emitThreadCreated({workspaceId: args.workspaceId,threadId: savedThread.id,diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type.tsnew file mode 100644index 00000000000..4e0f892a412--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-participant-row.type.ts@@ -0,0 +1,5 @@+import { type AgentChatThreadParticipantDTO } from 'src/engine/metadata-modules/ai/ai-chat/dtos/agent-chat-thread-participant.dto';++export type AgentChatThreadParticipantRow = AgentChatThreadParticipantDTO & {+ workspaceMemberId: string;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util.tsnew file mode 100644index 00000000000..f6c438b8f97--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util.ts@@ -0,0 +1,25 @@+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';++// A participant row is one member's private inbox state, so its member is the+// only one granted it, while still a member. Reads its rows (id,+// workspaceMemberId) from a CTE or table.+export const buildAgentChatThreadParticipantOwnerShareInsert = ({+ workspaceId,+ participantSource,+ objectMetadataIdParameter,+}: {+ workspaceId: string;+ participantSource: string;+ objectMetadataIdParameter: string;+}) => {+ const schema = escapeIdentifier(getWorkspaceSchemaName(workspaceId));++ return `INSERT INTO ${schema}."recordShare"+ ("objectMetadataId", "recordId", "principalId", "principalType", "accessLevel", "rowCause", "sourceId")+ SELECT ${objectMetadataIdParameter}::uuid, participant.id, participant."workspaceMemberId", 'WORKSPACE_MEMBER', 'FULL', 'OWNER', participant.id+ FROM ${participantSource} participant+ JOIN ${schema}."workspaceMember" member+ ON member.id = participant."workspaceMemberId" AND member."deletedAt" IS NULL+ ON CONFLICT DO NOTHING`;+};diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agent-chat-thread-inbox-state.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agent-chat-thread-inbox-state.util.tsindex 67497e48a23..d7f2e7f8f39 100644--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agent-chat-thread-inbox-state.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-agent-chat-thread-inbox-state.util.ts@@ -1,4 +1,7 @@+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { AGENT_CHAT_THREAD_LAST_MESSAGE_TEXT_MAX_LENGTH } from 'src/engine/metadata-modules/ai/ai-chat/constants/agent-chat-thread-last-message-text-max-length.constant';+import { buildAgentChatThreadParticipantOwnerShareInsert } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-agent-chat-thread-participant-owner-share-insert.util';import { getAgentChatThreadParticipantTable } from 'src/engine/metadata-modules/ai/ai-chat/utils/get-agent-chat-thread-participant-table.util';import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';@@ -69,4 +72,17 @@ export const seedAgentChatThreadInboxState = async ({WHERE thread."workspaceMemberId" IS NOT NULLON CONFLICT ("threadId", "workspaceMemberId") DO NOTHING`,);++ // Every row, so ones seeded by an earlier run are granted too+ await manager.query(+ buildAgentChatThreadParticipantOwnerShareInsert({+ workspaceId,+ participantSource: getAgentChatThreadParticipantTable(workspaceId),+ objectMetadataIdParameter: `(SELECT id FROM core."objectMetadata" WHERE "workspaceId" = $1 AND "universalIdentifier" = $2)`,+ }),+ [+ workspaceId,+ STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier,+ ],+ );};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.tsindex 47df10abb89..b68433361a1 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts@@ -104,6 +104,10 @@ describe('agent history workspace metadata', () => {readability: MetadataReadability.INHERITED,writability: MetadataWritability.OPEN,},+ agentChatThreadParticipant: {+ readability: MetadataReadability.PRIVATE,+ writability: MetadataWritability.SYSTEM,+ },};it.each(OBJECT_NAMES)('keeps %s protected by metadata policy', (name) => {diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.tsindex ed27a9409ac..d6d621f79dc 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts@@ -101,7 +101,7 @@ describe('Standard object readability', () => {});});- it.each(['recordShare', 'shortLink', 'agentChatThreadParticipant'] as const)(+ it.each(['recordShare', 'shortLink'] as const)('declares %s SYSTEM for readability and writability',(objectName) => {expect(findStandardFlatObjectMetadata(objectName)).toMatchObject({@@ -111,6 +111,15 @@ describe('Standard object readability', () => {},);+ it('declares agentChatThreadParticipant PRIVATE, written only by the chat resolvers', () => {+ expect(+ findStandardFlatObjectMetadata('agentChatThreadParticipant'),+ ).toMatchObject({+ readability: MetadataReadability.PRIVATE,+ writability: MetadataWritability.SYSTEM,+ });+ });+// Inheriting from the record would reveal which private conversations are filed under itit('resolves its thread as the only parent of an agentChatThreadTarget', () => {expect(diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.tsindex c78ec1e6b1b..bee0bb531f7 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts@@ -264,9 +264,9 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {isAuditLogged: false,isUIEditable: false,isUICreatable: false,- // Each row is one member's private inbox state, so it is only reached- // through the chat resolvers, never through the record API- readability: MetadataReadability.SYSTEM,+ // Each row is one member's private inbox state, readable through its+ // owner grant and written only through the chat resolvers+ readability: MetadataReadability.PRIVATE,writability: MetadataWritability.SYSTEM,labelIdentifierFieldMetadataName: 'id',},diff --git a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.tsindex 36670e21be2..b844184e9f7 100644--- a/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/chat-thread-participant.integration-spec.ts@@ -1,12 +1,18 @@import { randomUUID } from 'node:crypto';import { parse } from 'graphql';+import {+ type ObjectRecordCreateEvent,+ type ObjectRecordUpdateEvent,+} from 'twenty-shared/database-events';import { STANDARD_OBJECTS } from 'twenty-shared/metadata';import {RecordShareAccessLevel,RecordSharePrincipalType,} from 'twenty-shared/types';+import { findManyOperationFactory } from 'test/integration/graphql/utils/find-many-operation-factory.util';+import { makeGraphqlApiRequest } from 'test/integration/graphql/utils/make-graphql-api-request.util';import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';import { destroyAgentChatThread } from 'test/integration/utils/destroy-agent-chat-thread.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';@@ -16,12 +22,14 @@ import { type AgentChatThreadParticipantService } from 'src/engine/metadata-moduimport { type AgentChatThreadService } from 'src/engine/metadata-modules/ai/ai-chat/services/agent-chat-thread.service';import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { type WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);-const PARTICIPANT_FIELDS = 'threadId lastReadAt archivedAt snoozedUntil';+const PARTICIPANT_FIELDS =+ 'id threadId lastReadAt archivedAt snoozedUntil updatedAt';const MY_PARTICIPANTS = parse(`query MyParticipants { myAgentChatThreadParticipants { ${PARTICIPANT_FIELDS} } }`,@@ -36,7 +44,12 @@ const SNOOZE = parse(`mutation Snooze($threadId: UUID!, $snoozedUntil: DateTime!) { snoozeAgentChatThread(threadId: $threadId, snoozedUntil: $snoozedUntil) { ${PARTICIPANT_FIELDS} } }`,);+// Outlasts any test, yet within the delay the test queue fast-forwards+const buildFutureSnoozedUntil = () =>+ new Date(Date.now() + 30_000).toISOString();+type Participant = {+ id: string;threadId: string;lastReadAt: string | null;archivedAt: string | null;@@ -102,6 +115,55 @@ const createThread = async (): Promise<string> => {return threadId;};+const spyOnParticipantEvents = () =>+ jest.spyOn(+ getAppProviderByClassName<WorkspaceEventEmitter>('WorkspaceEventEmitter'),+ 'emitDatabaseBatchEvent',+ );++const findParticipantEvents = (+ eventSpy: ReturnType<typeof spyOnParticipantEvents>,+ threadId: string,+) =>+ eventSpy.mock.calls+ .map(([batchEvent]) => batchEvent)+ .filter(+ (batchEvent) =>+ batchEvent?.objectMetadataNameSingular === 'agentChatThreadParticipant',+ )+ .flatMap((batchEvent) =>+ (+ batchEvent!.events as (+ | ObjectRecordCreateEvent<Participant>+ | ObjectRecordUpdateEvent<Participant>+ )[]+ )+ .filter(({ properties }) => properties.after.threadId === threadId)+ .map(({ properties }) => ({+ action: batchEvent!.action,+ updatedFields:+ 'updatedFields' in properties ? properties.updatedFields : [],+ })),+ );++const listParticipantRecordIds = async (token: string): Promise<string[]> => {+ const response = await makeGraphqlApiRequest(+ findManyOperationFactory({+ objectMetadataSingularName: 'agentChatThreadParticipant',+ objectMetadataPluralName: 'agentChatThreadParticipants',+ gqlFields: 'id',+ first: 200,+ }),+ token,+ );++ expect(response.body.errors).toBeUndefined();++ return response.body.data.agentChatThreadParticipants.edges.map(+ ({ node }: { node: { id: string } }) => node.id,+ );+};+const setShareWithJony = async (threadId: string, enabled: boolean) => {const { flatObjectMetadataMaps } =await getAppProviderByClassName<WorkspaceCacheService>(@@ -137,6 +199,8 @@ describe('Chat thread participant state through the authenticated API', () => {};afterEach(async () => {+ jest.restoreAllMocks();+for (const threadId of createdThreadIds.splice(0)) {await setShareWithJony(threadId, false);await destroyAgentChatThread({ threadId });@@ -241,7 +305,7 @@ describe('Chat thread participant state through the authenticated API', () => {expect(pastSnooze.body.errors[0].extensions.code).toBe('BAD_USER_INPUT');- const snoozedUntil = new Date(Date.now() + 86_400_000).toISOString();+ const snoozedUntil = buildFutureSnoozedUntil();const snoozed = await makeMetadataApiRequest({query: SNOOZE,variables: { threadId, snoozedUntil },@@ -264,6 +328,214 @@ describe('Chat thread participant state through the authenticated API', () => {});});+ it('sends each change as a record event carrying what changed', async () => {+ const eventSpy = spyOnParticipantEvents();+ const threadId = await createTestThread();++ await runThreadMutation('markAgentChatThreadAsUnread', threadId);+ await runThreadMutation('markAgentChatThreadAsUnread', threadId);+ await runThreadMutation('archiveAgentChatThread', threadId);++ expect(findParticipantEvents(eventSpy, threadId)).toEqual([+ { action: 'created', updatedFields: [] },+ { action: 'updated', updatedFields: ['lastReadAt', 'updatedAt'] },+ { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },+ ]);+ });++ it('lets only its member read a row, through the grant it is given', async () => {+ const threadId = await createTestThread();++ await setShareWithJony(threadId, true);+ await runThreadMutation(+ 'archiveAgentChatThread',+ threadId,+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ const janeParticipant = await findMyParticipant(threadId);+ const jonyParticipant = await findMyParticipant(+ threadId,+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );+ const ownerShares: { recordId: string; principalId: string }[] =+ await global.testDataSource.query(+ `SELECT "recordId", "principalId" FROM ${SCHEMA}."recordShare"+ WHERE "recordId" = ANY($1) AND "rowCause" = 'OWNER'+ ORDER BY "principalId"`,+ [[janeParticipant!.id, jonyParticipant!.id]],+ );+ const jonyRecordIds = await listParticipantRecordIds(+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(ownerShares).toEqual(+ expect.arrayContaining([+ {+ recordId: janeParticipant!.id,+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ },+ {+ recordId: jonyParticipant!.id,+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ ]),+ );+ expect(ownerShares).toHaveLength(2);+ expect(jonyRecordIds).toContain(jonyParticipant!.id);+ expect(jonyRecordIds).not.toContain(janeParticipant!.id);+ });++ it('ends a snooze once its time passes by moving the chat back to the inbox', async () => {+ const threadId = await createTestThread();++ await makeMetadataApiRequest({+ query: SNOOZE,+ variables: {+ threadId,+ snoozedUntil: buildFutureSnoozedUntil(),+ },+ });++ const snoozedUntil = new Date(Date.now() - 1000);++ await global.testDataSource.query(+ `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "snoozedUntil" = $3+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE, snoozedUntil],+ );++ const eventSpy = spyOnParticipantEvents();++ await getAppProviderByClassName<AgentChatThreadParticipantService>(+ 'AgentChatThreadParticipantService',+ ).endSnooze({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadId,+ snoozedUntil: snoozedUntil.toISOString(),+ });++ const [row]: { archivedAt: Date | null; snoozedUntil: Date | null }[] =+ await global.testDataSource.query(+ `SELECT "archivedAt", "snoozedUntil" FROM ${SCHEMA}."agentChatThreadParticipant"+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],+ );++ // The snooze stays recorded, so the chat shows what brought it back+ expect(row.archivedAt).toBeNull();+ expect(row.snoozedUntil?.getTime()).toBe(snoozedUntil.getTime());+ expect(findParticipantEvents(eventSpy, threadId)).toEqual([+ { action: 'updated', updatedFields: ['archivedAt', 'updatedAt'] },+ ]);+ });++ it('saves as ended a snooze whose time passed before it was saved', async () => {+ const threadId = await createTestThread();+ const snoozedUntil = new Date(Date.now() - 1000);++ // The snooze was accepted while its time was still ahead, and its+ // queued end already ran and found nothing to end+ const participant =+ await getAppProviderByClassName<AgentChatThreadParticipantService>(+ 'AgentChatThreadParticipantService',+ )['setArchive'](+ {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadId,+ },+ snoozedUntil,+ );++ expect(participant.archivedAt).toBeNull();+ expect(new Date(participant.snoozedUntil!).getTime()).toBe(+ snoozedUntil.getTime(),+ );+ });++ it('reads a snooze whose time passed as ended before its end has run', async () => {+ const threadId = await createTestThread();++ await makeMetadataApiRequest({+ query: SNOOZE,+ variables: {+ threadId,+ snoozedUntil: buildFutureSnoozedUntil(),+ },+ });++ await global.testDataSource.query(+ `UPDATE ${SCHEMA}."agentChatThreadParticipant" SET "snoozedUntil" = $3+ WHERE "threadId" = $1 AND "workspaceMemberId" = $2`,+ [+ threadId,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ new Date(Date.now() - 1000),+ ],+ );++ expect(await findMyParticipant(threadId)).toMatchObject({+ archivedAt: null,+ snoozedUntil: expect.any(String),+ });+ });++ it('waits for the database clock before ending a snooze', async () => {+ const threadId = await createTestThread();+ const snoozedUntil = buildFutureSnoozedUntil();++ await makeMetadataApiRequest({+ query: SNOOZE,+ variables: { threadId, snoozedUntil },+ });++ const eventSpy = spyOnParticipantEvents();++ await getAppProviderByClassName<AgentChatThreadParticipantService>(+ 'AgentChatThreadParticipantService',+ ).endSnooze({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadId,+ snoozedUntil,+ });++ expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);+ expect(await findMyParticipant(threadId)).toMatchObject({+ archivedAt: expect.any(String),+ });+ });++ it('leaves alone a snooze the member replaced since', async () => {+ const threadId = await createTestThread();++ await makeMetadataApiRequest({+ query: SNOOZE,+ variables: {+ threadId,+ snoozedUntil: buildFutureSnoozedUntil(),+ },+ });++ const eventSpy = spyOnParticipantEvents();++ await getAppProviderByClassName<AgentChatThreadParticipantService>(+ 'AgentChatThreadParticipantService',+ ).endSnooze({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadId,+ snoozedUntil: new Date(Date.now() - 1000).toISOString(),+ });++ expect(findParticipantEvents(eventSpy, threadId)).toEqual([]);+ expect(await findMyParticipant(threadId)).toMatchObject({+ archivedAt: expect.any(String),+ });+ });+it('brings the thread back and marks it read for the member who writes in it', async () => {const threadId = await createTestThread();diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.integration-spec.tsnew file mode 100644index 00000000000..f00f7aa1e6c--- /dev/null+++ b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.integration-spec.ts@@ -0,0 +1,144 @@+import { randomUUID } from 'node:crypto';++import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { MetadataReadability } from 'twenty-shared/types';++import { type MakeAgentChatThreadParticipantsPrivateCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791056679663-make-agent-chat-thread-participants-private.command';+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';++const RUN_ON_WORKSPACE_ARGS = {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ options: {},+ index: 0,+ total: 1,+};++const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);++describe('2-46 workspace command - make agent chat thread participants private (integration)', () => {+ let command: MakeAgentChatThreadParticipantsPrivateCommand;+ let workspaceOrmManager: WorkspaceOrmManager;++ const threadId = randomUUID();+ const janeParticipantId = randomUUID();+ const jonyParticipantId = randomUUID();++ const runCommand = (direction: 'up' | 'down') =>+ workspaceOrmManager.executeInWorkspaceContext(+ () => command[direction](RUN_ON_WORKSPACE_ARGS),+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),+ );++ const findParticipantObject = async () => {+ const { flatObjectMetadataMaps } =+ await getAppProviderByClassName<WorkspaceCacheService>(+ 'WorkspaceCacheService',+ ).getOrRecompute(SEED_APPLE_WORKSPACE_ID, ['flatObjectMetadataMaps']);++ return flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThreadParticipant.universalIdentifier+ ]!;+ };++ const readOwnerShares = async () => {+ const rows: { recordId: string; principalId: string }[] =+ await global.testDataSource.query(+ `SELECT "recordId", "principalId" FROM ${SCHEMA}."recordShare"+ WHERE "recordId" = ANY($1) AND "rowCause" = 'OWNER'+ ORDER BY "principalId"`,+ [[janeParticipantId, jonyParticipantId]],+ );++ return rows;+ };++ beforeAll(async () => {+ command =+ getAppProviderByClassName<MakeAgentChatThreadParticipantsPrivateCommand>(+ 'MakeAgentChatThreadParticipantsPrivateCommand',+ );+ workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(+ 'WorkspaceOrmManager',+ );++ await runCommand('down');++ await global.testDataSource.query(+ `INSERT INTO ${SCHEMA}."agentChatThread" (id, title, "workspaceMemberId")+ VALUES ($1, 'Private participants', $2)`,+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],+ );+ await global.testDataSource.query(+ `INSERT INTO ${SCHEMA}."agentChatThreadParticipant" (id, "threadId", "workspaceMemberId")+ VALUES ($1, $3, $4), ($2, $3, $5)`,+ [+ janeParticipantId,+ jonyParticipantId,+ threadId,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ ],+ );+ });++ afterAll(async () => {+ await runCommand('up');+ await global.testDataSource.query(+ `DELETE FROM ${SCHEMA}."recordShare" WHERE "recordId" = ANY($1)`,+ [[janeParticipantId, jonyParticipantId]],+ );+ await global.testDataSource.query(+ `DELETE FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = $1`,+ [threadId],+ );+ await global.testDataSource.query(+ `DELETE FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,+ [threadId],+ );+ });++ it('starts from rows nobody is granted on a SYSTEM object', async () => {+ expect((await findParticipantObject()).readability).toBe(+ MetadataReadability.SYSTEM,+ );+ expect(await readOwnerShares()).toEqual([]);+ });++ it('grants each row to its member and makes the object PRIVATE', async () => {+ await runCommand('up');+ await runCommand('up');++ expect((await findParticipantObject()).readability).toBe(+ MetadataReadability.PRIVATE,+ );+ expect(await readOwnerShares()).toEqual(+ [+ {+ recordId: janeParticipantId,+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ },+ {+ recordId: jonyParticipantId,+ principalId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ },+ ].sort((first, second) =>+ first.principalId.localeCompare(second.principalId),+ ),+ );+ });++ it('makes the object SYSTEM again and removes the grants on down', async () => {+ await runCommand('down');++ expect((await findParticipantObject()).readability).toBe(+ MetadataReadability.SYSTEM,+ );+ expect(await readOwnerShares()).toEqual([]);+ });+});diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.integration-spec.tsnew file mode 100644index 00000000000..2c211c9c888--- /dev/null+++ b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.integration-spec.ts@@ -0,0 +1,98 @@+import { randomUUID } from 'node:crypto';++import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';++import { type ScheduleAgentChatThreadSnoozeEndsCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-workspace-command-1791093059050-schedule-agent-chat-thread-snooze-ends.command';+import { END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME } from 'src/engine/metadata-modules/ai/ai-chat/jobs/end-agent-chat-thread-snooze-job-name.constant';+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';++const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);++describe('2-46 workspace command - schedule agent chat thread snooze ends (integration)', () => {+ const pendingThreadId = randomUUID();+ const endedThreadId = randomUUID();+ let pendingSnoozedUntil: Date;++ beforeAll(async () => {+ for (const threadId of [pendingThreadId, endedThreadId]) {+ await global.testDataSource.query(+ `INSERT INTO ${SCHEMA}."agentChatThread" (id, title, "workspaceMemberId")+ VALUES ($1, 'Snooze ends', $2)`,+ [threadId, WORKSPACE_MEMBER_DATA_SEED_IDS.JANE],+ );+ }++ pendingSnoozedUntil = new Date(Date.now() + 30_000);++ await global.testDataSource.query(+ `INSERT INTO ${SCHEMA}."agentChatThreadParticipant" ("threadId", "workspaceMemberId", "archivedAt", "snoozedUntil")+ VALUES ($1, $3, now(), $4), ($2, $3, now(), now() - interval '1 minute')`,+ [+ pendingThreadId,+ endedThreadId,+ WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ pendingSnoozedUntil,+ ],+ );+ });++ afterAll(async () => {+ for (const threadId of [pendingThreadId, endedThreadId]) {+ await global.testDataSource.query(+ `DELETE FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = $1`,+ [threadId],+ );+ await global.testDataSource.query(+ `DELETE FROM ${SCHEMA}."agentChatThread" WHERE id = $1`,+ [threadId],+ );+ }+ });++ it('queues the end of each snooze still pending', async () => {+ const command =+ getAppProviderByClassName<ScheduleAgentChatThreadSnoozeEndsCommand>(+ 'ScheduleAgentChatThreadSnoozeEndsCommand',+ );+ const addSpy = jest+ .spyOn(command['delayedJobsQueueService'], 'add')+ .mockResolvedValue(undefined);++ await getAppProviderByClassName<WorkspaceOrmManager>(+ 'WorkspaceOrmManager',+ ).executeInWorkspaceContext(+ () =>+ command.up({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ options: {},+ index: 0,+ total: 1,+ }),+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),+ );++ const queuedThreadIds = addSpy.mock.calls.map(+ ([, data]) => (data as { threadId: string }).threadId,+ );+ const pendingCall = addSpy.mock.calls.find(+ ([, data]) => (data as { threadId: string }).threadId === pendingThreadId,+ );++ expect(queuedThreadIds).not.toContain(endedThreadId);+ expect(pendingCall?.[0]).toBe(END_AGENT_CHAT_THREAD_SNOOZE_JOB_NAME);+ expect(pendingCall?.[1]).toEqual({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,+ threadId: pendingThreadId,+ snoozedUntil: pendingSnoozedUntil.toISOString(),+ });+ expect(pendingCall?.[2]?.delay).toBeGreaterThan(0);+ expect(pendingCall?.[2]?.delay).toBeLessThanOrEqual(30_000);++ addSpy.mockRestore();+ });+});diff --git a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts b/packages/twenty-shared/src/types/CoreObjectNameSingular.tsindex 65e656c1ed1..28121d247bd 100644--- a/packages/twenty-shared/src/types/CoreObjectNameSingular.ts+++ b/packages/twenty-shared/src/types/CoreObjectNameSingular.ts@@ -2,6 +2,7 @@ export enum CoreObjectNameSingular {Activity = 'activity',ActivityTarget = 'activityTarget',AgentChatThread = 'agentChatThread',+ AgentChatThreadParticipant = 'agentChatThreadParticipant',AgentChatThreadTarget = 'agentChatThreadTarget',ApiKey = 'apiKey',Attachment = 'attachment',