The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Load a member's chat inbox state with its threads (#27219)
Félix Malfait7cc3246800bc
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex ba7bbc2c4cc..26f118f17e2 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -3993,7 +3993,6 @@ type Query {chatMessages(threadId: UUID!): [AgentMessage!]!chatStreamCatchupChunks(threadId: UUID!): ChatStreamCatchupChunks!getAiSystemPromptPreview: AiSystemPromptPreview!- myAgentChatThreadParticipants: [AgentChatThreadParticipant!]!skills: [Skill!]!skill(id: UUID!): SkillagentTurns(agentId: UUID!): [AgentTurn!]!diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 043f1968721..ff045b59778 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -3489,7 +3489,6 @@ export interface Query {chatMessages: AgentMessage[]chatStreamCatchupChunks: ChatStreamCatchupChunksgetAiSystemPromptPreview: AiSystemPromptPreview- myAgentChatThreadParticipants: AgentChatThreadParticipant[]skills: Skill[]skill?: SkillagentTurns: AgentTurn[]@@ -7457,7 +7456,6 @@ export interface QueryGenqlSelection{chatMessages?: (AgentMessageGenqlSelection & { __args: {threadId: Scalars['UUID']} })chatStreamCatchupChunks?: (ChatStreamCatchupChunksGenqlSelection & { __args: {threadId: Scalars['UUID']} })getAiSystemPromptPreview?: AiSystemPromptPreviewGenqlSelection- myAgentChatThreadParticipants?: AgentChatThreadParticipantGenqlSelectionskills?: SkillGenqlSelectionskill?: (SkillGenqlSelection & { __args: {id: Scalars['UUID']} })agentTurns?: (AgentTurnGenqlSelection & { __args: {agentId: Scalars['UUID']} })diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.tsindex e953b73c23f..80ca63d168c 100644--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts@@ -8328,9 +8328,6 @@ export default {"getAiSystemPromptPreview": [384],- "myAgentChatThreadParticipants": [- 388- ],"skills": [381],diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 4f78223d6ff..f80ab8761b4 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -5354,7 +5354,6 @@ export type Query = {metadataTranslations: Array<MetadataTranslation>;minimalMetadata: MinimalMetadata;mostlyEmptyFieldMetadataIds: Array<Scalars['UUID']['output']>;- myAgentChatThreadParticipants: Array<AgentChatThreadParticipant>;myCalendarChannels: Array<CalendarChannel>;myConnectedAccounts: Array<ConnectedAccountPublicDto>;myMessageChannels: Array<MessageChannel>;@@ -8239,11 +8238,6 @@ export type GetChatMessagesQueryVariables = Exact<{export type GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{ __typename?: 'AgentMessage', id: string, threadId: string, turnId?: string | null, senderUserWorkspaceId?: string | null, role: string, status: string, createdAt: string, parts: Array<{ __typename?: 'AgentMessagePart', id: string, messageId: string, orderIndex: number, type: string, textContent?: string | null, reasoningContent?: string | null, toolName?: string | null, toolCallId?: string | null, toolInput?: any | null, toolOutput?: any | null, state?: string | null, providerExecuted?: boolean | null, errorMessage?: string | null, sourceUrlSourceId?: string | null, sourceUrlUrl?: string | null, sourceUrlTitle?: string | null, sourceDocumentSourceId?: string | null, sourceDocumentMediaType?: string | null, sourceDocumentTitle?: string | null, sourceDocumentFilename?: string | null, fileMediaType?: string | null, fileFilename?: string | null, fileUrl?: string | null, fileId?: string | null, providerMetadata?: any | null, createdAt: string }> }>, chatStreamCatchupChunks: { __typename?: 'ChatStreamCatchupChunks', chunks: Array<any>, maxSeq: number, error?: { __typename?: 'ChatStreamError', code: string, message: string } | null } };-export type GetMyAgentChatThreadParticipantsQueryVariables = Exact<{ [key: string]: never; }>;---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; }>;@@ -10743,7 +10737,6 @@ export const FindWorkspaceAiStatsDocument = {"kind":"Document","definitions":[{"export const GetAgentTurnsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAgentTurns"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"agentTurns"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"agentId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"agentId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"threadId"}},{"kind":"Field","name":{"kind":"Name","value":"agentId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"evaluations"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"score"}},{"kind":"Field","name":{"kind":"Name","value":"comment"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"messages"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"role"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"parts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"textContent"}},{"kind":"Field","name":{"kind":"Name","value":"reasoningContent"}},{"kind":"Field","name":{"kind":"Name","value":"toolName"}},{"kind":"Field","name":{"kind":"Name","value":"toolCallId"}},{"kind":"Field","name":{"kind":"Name","value":"toolInput"}},{"kind":"Field","name":{"kind":"Name","value":"toolOutput"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"providerExecuted"}},{"kind":"Field","name":{"kind":"Name","value":"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":"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/AgentChatThreadParticipantOperationsEffect.tsx b/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsxindex 15c5089c9b8..6489de0861b 100644--- a/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsx+++ b/packages/twenty-front/src/modules/ai/components/AgentChatThreadParticipantOperationsEffect.tsx@@ -3,8 +3,8 @@ 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 { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import { getAgentChatThreadParticipantFromRecord } from '@/ai/utils/getAgentChatThreadParticipantFromRecord';import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';@@ -31,8 +31,6 @@ export const AgentChatThreadParticipantOperationsEffect = () => {const currentWorkspaceMemberId = useAtomStateValue(currentWorkspaceMemberState,)?.id;- const { refreshAgentChatThreadParticipants } =- useAgentChatThreadParticipants();const isEnabled =isDefined(participantObjectMetadataItem) &&isDefined(currentWorkspaceMemberId);@@ -57,7 +55,7 @@ export const AgentChatThreadParticipantOperationsEffect = () => {const handleRecordOperation = useCallback(({ operation }: ObjectRecordOperationBrowserEventDetail) => {- // Also kept aside, so a load already on its way cannot undo them+ // Also kept aside, for when the member's rows have not loaded yetconst applyParticipants = (participants: AgentChatThreadParticipantFieldsFragment[],) => {@@ -89,12 +87,15 @@ export const AgentChatThreadParticipantOperationsEffect = () => {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,- ]),+ [+ ...Object.values(+ store.get(agentChatThreadStreamedParticipantsState.atom),+ ),+ ...Object.values(+ store.get(agentChatThreadParticipantsState.atom) ?? {},+ ),+ ].map((participant) => [participant.id, participant]),);const updatedParticipants = updateInputs.map(({ recordId, updatedFields }) => {@@ -106,24 +107,22 @@ export const AgentChatThreadParticipantOperationsEffect = () => {},);- // Updates only carry what changed, so a row not loaded yet is- // read again whole- if (- !isDefined(participants) ||- !updatedParticipants.every(isDefined)- ) {- void refreshAgentChatThreadParticipants();- return;+ // Updates only carry what changed, so a row not loaded yet comes+ // whole with its thread, and a page on its way is read again in+ // case it holds an older copy+ if (!updatedParticipants.every(isDefined)) {+ store.set(+ agentChatThreadRecordUpdateCountState.atom,+ (updateCount) => updateCount + 1,+ );}- applyParticipants(updatedParticipants);+ applyParticipants(updatedParticipants.filter(isDefined));return;}- default:- void refreshAgentChatThreadParticipants();}},- [refreshAgentChatThreadParticipants, store],+ [store],);useListenToObjectRecordOperationBrowserEvent({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.tsxindex 470bb358a82..e03ba8233e1 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadParticipantOperationsEffect.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AgentChatThreadParticipantOperationsEffect.test.tsx@@ -4,6 +4,7 @@ import { CoreObjectNameSingular } from 'twenty-shared/types';import { AgentChatThreadParticipantOperationsEffect } from '@/ai/components/AgentChatThreadParticipantOperationsEffect';import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';@@ -20,14 +21,6 @@ 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',() => ({@@ -108,10 +101,6 @@ const receiveParticipantUpdate = ();describe('AgentChatThreadParticipantOperationsEffect', () => {- beforeEach(() => {- mockRefreshAgentChatThreadParticipants.mockClear();- });-it('adds a row the member created elsewhere', () => {const { store } = renderEffect({});@@ -157,7 +146,7 @@ describe('AgentChatThreadParticipantOperationsEffect', () => {).toEqual({ ...snoozedParticipant, ...change });});- it('keeps a change for a load already on its way, with its new version', () => {+ it('keeps a change for a page already on its way, with its new version', () => {// Archived through an earlier change, so its version is still T0const { store } = renderEffect({[THREAD_ID]: {@@ -176,7 +165,7 @@ describe('AgentChatThreadParticipantOperationsEffect', () => {updatedAt: '2026-10-01T10:02:00.000Z',});- // A load that read the archived row (T1) merges this change (T2) over it+ // A page that read the archived row (T1) merges this change (T2) over itexpect(mergeAgentChatThreadParticipants({ [THREAD_ID]: loadedArchivedParticipant },@@ -202,15 +191,34 @@ describe('AgentChatThreadParticipantOperationsEffect', () => {});});- it('reloads the rows when a change is for a row it does not have', () => {+ it('leaves a change for a row it does not have to the page of its thread', () => {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,});+ expect(store.get(agentChatThreadRecordUpdateCountState.atom)).toBe(1);+ });++ it('applies a change to a row that arrived before the first page', () => {+ const { store } = renderEffect(null);++ receiveCreatedParticipant(READ_PARTICIPANT);+ receiveParticipantUpdate(PARTICIPANT_ID, {+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ });++ expect(store.get(agentChatThreadStreamedParticipantsState.atom)).toEqual({+ [THREAD_ID]: {+ ...READ_PARTICIPANT,+ lastReadAt: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ },+ });+ expect(store.get(agentChatThreadRecordUpdateCountState.atom)).toBe(0);});it('ignores a copy older than the one it has', () => {@@ -227,7 +235,7 @@ describe('AgentChatThreadParticipantOperationsEffect', () => {});});- it('keeps a row that arrives before the first load for that load', () => {+ it('keeps a row that arrives before the first page for that page', () => {const { store } = renderEffect(null);receiveCreatedParticipant(READ_PARTICIPANT);diff --git a/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.ts b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.tsindex 5292bcf2c02..9303bee25f1 100644--- a/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.ts+++ b/packages/twenty-front/src/modules/ai/constants/AgentChatThreadListRecordGqlFields.ts@@ -17,4 +17,13 @@ export const AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS = {conversationSize: true,totalInputCredits: true,totalOutputCredits: true,+ participants: {+ id: true,+ threadId: true,+ workspaceMemberId: true,+ lastReadAt: true,+ archivedAt: true,+ snoozedUntil: true,+ updatedAt: true,+ },};diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getMyAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getMyAgentChatThreadParticipants.tsdeleted file mode 100644index f106e7e1825..00000000000--- a/packages/twenty-front/src/modules/ai/graphql/queries/getMyAgentChatThreadParticipants.ts+++ /dev/null@@ -1,12 +0,0 @@-import { gql } from '@apollo/client';--import { AGENT_CHAT_THREAD_PARTICIPANT_FRAGMENT } from '@/ai/graphql/fragments/agentChatThreadParticipantFragment';--export const GET_MY_AGENT_CHAT_THREAD_PARTICIPANTS = gql`- ${AGENT_CHAT_THREAD_PARTICIPANT_FRAGMENT}- query GetMyAgentChatThreadParticipants {- myAgentChatThreadParticipants {- ...AgentChatThreadParticipantFields- }- }-`;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 b30a8650bf0..bcbcf6e74ab 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,7 +4,6 @@ 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';@@ -19,13 +18,12 @@ const READ_PARTICIPANT = {updatedAt: '2026-10-01T10:00:00.000Z',};-const query = jest.fn();const mutate = jest.fn();const enqueueToast = jest.fn();jest.mock('@apollo/client/react', () => ({...jest.requireActual('@apollo/client/react'),- useApolloClient: () => ({ query, mutate }),+ useApolloClient: () => ({ mutate }),}));jest.mock('twenty-ui/components', () => ({@@ -57,82 +55,6 @@ describe('useAgentChatThreadParticipants', () => {jest.clearAllMocks();});- it('loads the member state of every thread', async () => {- query.mockResolvedValue({- data: {- myAgentChatThreadParticipants: [READ_PARTICIPANT],- },- });- const { result, store } = renderParticipants();-- await act(async () => {- await result.current.refreshAgentChatThreadParticipants();- });-- expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({- [THREAD_ID]: READ_PARTICIPANT,- });- });-- 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();@@ -159,15 +81,14 @@ describe('useAgentChatThreadParticipants', () => {).toEqual(expect.any(String));});- it('reloads the server state and reports a refused snooze', async () => {+ it('puts the member state back and reports a refused snooze', async () => {mutate.mockRejectedValue(new Error('Snooze time must be in the future'));- query.mockResolvedValue({- data: {- myAgentChatThreadParticipants: [READ_PARTICIPANT],- },- });const { result, store } = renderParticipants();+ store.set(agentChatThreadParticipantsState.atom, {+ [THREAD_ID]: READ_PARTICIPANT,+ });+await act(async () => {await result.current.snoozeAgentChatThreads({threadIds: [THREAD_ID],@@ -181,6 +102,45 @@ describe('useAgentChatThreadParticipants', () => {expect(enqueueToast).toHaveBeenCalled();});+ it('keeps a row the server sent while a refused change was on its way', async () => {+ const { result, store } = renderParticipants();+ const archivedParticipant = {+ ...READ_PARTICIPANT,+ archivedAt: '2026-10-01T10:05:00.000Z',+ updatedAt: '2026-10-01T10:05:00.000Z',+ };++ store.set(agentChatThreadParticipantsState.atom, {+ [THREAD_ID]: READ_PARTICIPANT,+ });+ mutate.mockImplementation(async () => {+ store.set(agentChatThreadParticipantsState.atom, {+ [THREAD_ID]: archivedParticipant,+ });++ throw new Error('Network error');+ });++ await act(async () => {+ await result.current.markAgentChatThreadAsUnread(THREAD_ID);+ });++ expect(+ store.get(agentChatThreadParticipantsState.atom)?.[THREAD_ID],+ ).toEqual(archivedParticipant);+ });++ it('removes the change of a refused update on a thread without a row', async () => {+ mutate.mockRejectedValue(new Error('Network error'));+ const { result, store } = renderParticipants();++ await act(async () => {+ await result.current.archiveAgentChatThread(THREAD_ID);+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({});+ });+it('keeps the thread on screen unread when the member marks it unread', async () => {mutate.mockReturnValue(new Promise(() => undefined));const { result, store } = renderParticipants();@@ -206,9 +166,6 @@ describe('useAgentChatThreadParticipants', () => {it('puts the visit back when the server refuses to mark it unread', async () => {mutate.mockRejectedValue(new Error('Network error'));- query.mockResolvedValue({- data: { myAgentChatThreadParticipants: [READ_PARTICIPANT] },- });const { result, store } = renderParticipants();const visit = {threadId: THREAD_ID,diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsxindex c69b7badf79..fd1313dc535 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useRefreshAgentChatThreads.test.tsx@@ -4,11 +4,14 @@ import { type ReactNode } from 'react';import { useRefreshAgentChatThreads } from '@/ai/hooks/useRefreshAgentChatThreads';import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { agentChatThreadsSelector } from '@/ai/states/selectors/agentChatThreadsSelector';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';+import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';const queryMock = jest.fn();const mockApolloCoreClient = { query: queryMock };@@ -43,14 +46,6 @@ jest.mock('@/ai/hooks/useRefreshAgentChatThreadPermissions', () => ({}),}));-const refreshAgentChatThreadParticipants = jest.fn();--jest.mock('@/ai/hooks/useAgentChatThreadParticipants', () => ({- useAgentChatThreadParticipants: () => ({- refreshAgentChatThreadParticipants,- }),-}));-const buildThread = (id: string, title: string): AgentChatThreadRecord => ({__typename: 'AgentChatThread',id,@@ -126,7 +121,6 @@ describe('useRefreshAgentChatThreads', () => {fetchPolicy: 'network-only',}),);- expect(refreshAgentChatThreadParticipants).toHaveBeenCalled();expect(store.get(agentChatThreadListState.atom)).toEqual({threadIds: ['thread-1'],hasNextPage: true,@@ -137,6 +131,97 @@ describe('useRefreshAgentChatThreads', () => {]);});+ it("keeps the member's own inbox state from the page, and newer streamed rows", async () => {+ const store = buildStore();+ store.set(currentWorkspaceMemberState.atom, {+ id: 'member-id',+ } as never);+ const buildParticipant = (+ threadId: string,+ workspaceMemberId: string,+ updatedAt: string,+ ) => ({+ __typename: 'AgentChatThreadParticipant',+ id: `${threadId}-${workspaceMemberId}`,+ threadId,+ workspaceMemberId,+ lastReadAt: '2026-10-01T10:00:00.000Z',+ archivedAt: null,+ snoozedUntil: null,+ updatedAt,+ });+ const streamedParticipant = {+ id: 'thread-2-member-id',+ threadId: 'thread-2',+ lastReadAt: null,+ archivedAt: null,+ snoozedUntil: null,+ updatedAt: '2026-10-01T10:05:00.000Z',+ };+ store.set(agentChatThreadStreamedParticipantsState.atom, {+ 'thread-2': streamedParticipant,+ });+ queryMock.mockResolvedValue(+ buildPage([+ {+ ...buildThread('thread-1', 'First'),+ participants: {+ edges: [+ {+ node: buildParticipant(+ 'thread-1',+ 'member-id',+ '2026-10-01T10:00:00.000Z',+ ),+ },+ {+ node: buildParticipant(+ 'thread-1',+ 'other-member-id',+ '2026-10-01T10:00:00.000Z',+ ),+ },+ ],+ },+ } as AgentChatThreadRecord,+ {+ ...buildThread('thread-2', 'Second'),+ participants: {+ edges: [+ {+ node: buildParticipant(+ 'thread-2',+ 'member-id',+ '2026-10-01T10:00:00.000Z',+ ),+ },+ ],+ },+ } as AgentChatThreadRecord,+ ]),+ );+ const result = renderRefresh(store);++ await act(async () => {+ await result.current.refreshAgentChatThreads();+ });++ expect(store.get(agentChatThreadParticipantsState.atom)).toEqual({+ 'thread-1': {+ id: 'thread-1-member-id',+ threadId: 'thread-1',+ lastReadAt: '2026-10-01T10:00:00.000Z',+ archivedAt: null,+ snoozedUntil: null,+ updatedAt: '2026-10-01T10:00:00.000Z',+ },+ 'thread-2': streamedParticipant,+ });+ expect(store.get(agentChatThreadsSelector.atom)[0]).not.toHaveProperty(+ 'participants',+ );+ });+it('orders by last change on a workspace the 2.46 upgrade has not reached', async () => {const store = buildStore();store.set(chatObjectMetadataItemAtom, {diff --git a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.tsindex a8bd9ed5545..07d94ee8323 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAgentChatThreadParticipants.ts@@ -5,20 +5,16 @@ 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,ArchiveAgentChatThreadDocument,- GetMyAgentChatThreadParticipantsDocument,MarkAgentChatThreadAsReadDocument,MarkAgentChatThreadAsUnreadDocument,MoveAgentChatThreadToInboxDocument,@@ -30,43 +26,7 @@ export const useAgentChatThreadParticipants = () => {const store = useStore();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,- fetchPolicy: 'network-only',- })- .catch(() => undefined);-- if (- !isDefined(result?.data) ||- store.get(agentChatThreadParticipantsLoadCountState.atom) !== loadCount- ) {- return;- }-- store.set(- agentChatThreadParticipantsState.atom,- mergeAgentChatThreadParticipants(- Object.fromEntries(- result.data.myAgentChatThreadParticipants.map((participant) => [- participant.threadId,- participant,- ]),- ),- Object.values(store.get(agentChatThreadStreamedParticipantsState.atom)),- ),- );- }, [client, store]);-- // The change shows right away; if the server refuses it, the visit is put- // back and the member's state is reloaded from the server+ // The change shows right away, and is put back if the server refuses itconst updateParticipant = useCallback(async <TVariables extends { threadId: string }>({mutation,@@ -81,6 +41,9 @@ export const useAgentChatThreadParticipants = () => {}) => {const { threadId } = variables;const previousVisit = store.get(agentChatThreadVisitState.atom);+ const previousParticipant = store.get(+ agentChatThreadParticipantsState.atom,+ )?.[threadId];if (isDefined(optimisticVisit)) {store.set(agentChatThreadVisitState.atom, (visit) =>@@ -102,6 +65,9 @@ export const useAgentChatThreadParticipants = () => {}: participants,);+ const optimisticEntry = store.get(+ agentChatThreadParticipantsState.atom,+ )?.[threadId];try {await client.mutate({ mutation, variables });@@ -114,10 +80,25 @@ export const useAgentChatThreadParticipants = () => {);}- await refreshAgentChatThreadParticipants();+ // A newer row may have arrived since, and is kept+ store.set(agentChatThreadParticipantsState.atom, (participants) => {+ if (+ !isDefined(participants) ||+ participants[threadId] !== optimisticEntry+ ) {+ return participants;+ }++ const { [threadId]: _optimisticEntry, ...otherParticipants } =+ participants;++ return isDefined(previousParticipant)+ ? { ...otherParticipants, [threadId]: previousParticipant }+ : otherParticipants;+ });}},- [client, enqueueToast, refreshAgentChatThreadParticipants, store],+ [client, enqueueToast, store],);const markAgentChatThreadAsRead = useCallback(@@ -166,8 +147,6 @@ export const useAgentChatThreadParticipants = () => {[updateParticipant],);- // One chat at a time: a failed update reloads every chat's state, which- // would undo the optimistic change of an update still on its wayconst snoozeAgentChatThreads = useCallback(async ({threadIds,@@ -176,16 +155,18 @@ export const useAgentChatThreadParticipants = () => {threadIds: string[];snoozedUntil: Date;}) => {- for (const threadId of threadIds) {- await updateParticipant({- mutation: SnoozeAgentChatThreadDocument,- variables: { threadId, snoozedUntil: snoozedUntil.toISOString() },- optimisticParticipant: {- archivedAt: new Date().toISOString(),- snoozedUntil: snoozedUntil.toISOString(),- },- });- }+ await Promise.all(+ threadIds.map((threadId) =>+ updateParticipant({+ mutation: SnoozeAgentChatThreadDocument,+ variables: { threadId, snoozedUntil: snoozedUntil.toISOString() },+ optimisticParticipant: {+ archivedAt: new Date().toISOString(),+ snoozedUntil: snoozedUntil.toISOString(),+ },+ }),+ ),+ );},[updateParticipant],);@@ -201,7 +182,6 @@ export const useAgentChatThreadParticipants = () => {);return {- refreshAgentChatThreadParticipants,markAgentChatThreadAsRead,markAgentChatThreadAsUnread,archiveAgentChatThread,diff --git a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.tsindex c7bc6f56da1..0dfe4452b3f 100644--- a/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useRefreshAgentChatThreads.ts@@ -3,22 +3,26 @@ import { AGENT_CHAT_INSTANCE_ID } from '@/ai/constants/AgentChatInstanceId';import { AGENT_CHAT_THREAD_LIST_RECORD_GQL_FIELDS } from '@/ai/constants/AgentChatThreadListRecordGqlFields';import { useRefreshAgentChatThreadPermissions } from '@/ai/hooks/useRefreshAgentChatThreadPermissions';import { agentChatThreadListState } from '@/ai/states/agentChatThreadListState';+import { agentChatThreadParticipantsState } from '@/ai/states/agentChatThreadParticipantsState';import { agentChatThreadRecordUpdateCountState } from '@/ai/states/agentChatThreadRecordUpdateCountState';+import { agentChatThreadStreamedParticipantsState } from '@/ai/states/agentChatThreadStreamedParticipantsState';import { agentChatUsageComponentFamilyState } from '@/ai/states/agentChatUsageComponentFamilyState';import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { type AgentChatThreadRecord } from '@/ai/types/AgentChatThreadRecord';import { buildAgentChatThreadListFilter } from '@/ai/utils/buildAgentChatThreadListFilter';import { getAgentChatThreadLastActivityFieldName } from '@/ai/utils/getAgentChatThreadLastActivityFieldName';+import { getAgentChatThreadParticipantFromRecord } from '@/ai/utils/getAgentChatThreadParticipantFromRecord';import { getAgentChatUsageFromThread } from '@/ai/utils/getAgentChatUsageFromThread';+import { mergeAgentChatThreadParticipants } from '@/ai/utils/mergeAgentChatThreadParticipants';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';-import { useAgentChatThreadParticipants } from '@/ai/hooks/useAgentChatThreadParticipants';import { useApplyAgentChatThreadUpdate } from '@/ai/hooks/useApplyAgentChatThreadUpdate';import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';import { objectMetadataItemFamilySelector } from '@/object-metadata/states/objectMetadataItemFamilySelector';import { objectMetadataItemsSelector } from '@/object-metadata/states/objectMetadataItemsSelector';import { getRecordsFromRecordConnection } from '@/object-record/cache/utils/getRecordsFromRecordConnection';import { type RecordGqlOperationFindManyResult } from '@/object-record/graphql/types/RecordGqlOperationFindManyResult';+import { type ObjectRecord } from '@/object-record/types/ObjectRecord';import { useObjectPermissions } from '@/object-record/hooks/useObjectPermissions';import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';import { generateFindManyRecordsQuery } from '@/object-record/utils/generateFindManyRecordsQuery';@@ -31,6 +35,8 @@ import {} from 'twenty-shared/types';import { isDefined, isValidUuid } from 'twenty-shared/utils';+import { type AgentChatThreadParticipantFieldsFragment } from '~/generated-metadata/graphql';+export const useRefreshAgentChatThreads = () => {const apolloCoreClient = useApolloCoreClient();const store = useStore();@@ -39,8 +45,6 @@ export const useRefreshAgentChatThreads = () => {const { refreshAgentChatThreadPermissions } =useRefreshAgentChatThreadPermissions();const { addAgentChatThread } = useApplyAgentChatThreadUpdate();- const { refreshAgentChatThreadParticipants } =- useAgentChatThreadParticipants();const fetchAgentChatThreadsPage = useCallback(async ({@@ -64,10 +68,12 @@ export const useRefreshAgentChatThreads = () => {return undefined;}+ const currentWorkspaceMemberId = store.get(+ currentWorkspaceMemberState.atom,+ )?.id;const listFilter = buildAgentChatThreadListFilter({chatObjectMetadataItem,- currentWorkspaceMemberId: store.get(currentWorkspaceMemberState.atom)- ?.id,+ currentWorkspaceMemberId,});const result = await apolloCoreClient@@ -102,10 +108,22 @@ export const useRefreshAgentChatThreads = () => {return undefined;}+ const records = getRecordsFromRecordConnection<+ AgentChatThreadRecord & { participants?: ObjectRecord[] }+ >({ recordConnection: connection });+return {- threads: getRecordsFromRecordConnection<AgentChatThreadRecord>({- recordConnection: connection,- }),+ threads: records.map(+ ({ participants: _participants, ...thread }) => thread,+ ),+ // Roles that read every record get every member's row+ participants: records+ .flatMap(({ participants }) => participants ?? [])+ .filter(+ (participant) =>+ participant.workspaceMemberId === currentWorkspaceMemberId,+ )+ .map(getAgentChatThreadParticipantFromRecord),hasNextPage: connection.pageInfo.hasNextPage ?? false,endCursor: connection.pageInfo.endCursor ?? null,};@@ -113,6 +131,24 @@ export const useRefreshAgentChatThreads = () => {[apolloCoreClient, objectPermissionsByObjectMetadataId, store],);+ // The member's inbox state comes with the threads it belongs to+ const addAgentChatThreadParticipants = useCallback(+ (participants: AgentChatThreadParticipantFieldsFragment[]) => {+ store.set(agentChatThreadParticipantsState.atom, (loadedParticipants) =>+ mergeAgentChatThreadParticipants(+ mergeAgentChatThreadParticipants(+ loadedParticipants ?? {},+ participants,+ ),+ Object.values(+ store.get(agentChatThreadStreamedParticipantsState.atom),+ ),+ ),+ );+ },+ [store],+ );+const loadAgentChatThreads = useCallback(async (mode: 'refresh' | 'fetch-more') => {const workspaceId = store.get(currentWorkspaceState.atom)?.id;@@ -166,6 +202,7 @@ export const useRefreshAgentChatThreads = () => {}upsertRecordsInStore({ partialRecords: page.threads });+ addAgentChatThreadParticipants(page.participants);const pageThreadIds = page.threads.map(({ id }) => id);const previousThreadIds =@@ -188,6 +225,7 @@ export const useRefreshAgentChatThreads = () => {return undefined;},[+ addAgentChatThreadParticipants,fetchAgentChatThreadsPage,refreshAgentChatThreadPermissions,store,@@ -195,14 +233,10 @@ export const useRefreshAgentChatThreads = () => {],);- const refreshAgentChatThreads = useCallback(async () => {- const [threads] = await Promise.all([- loadAgentChatThreads('refresh'),- refreshAgentChatThreadParticipants(),- ]);-- return threads;- }, [loadAgentChatThreads, refreshAgentChatThreadParticipants]);+ const refreshAgentChatThreads = useCallback(+ () => loadAgentChatThreads('refresh'),+ [loadAgentChatThreads],+ );const fetchMoreAgentChatThreads = useCallback(() => loadAgentChatThreads('fetch-more'),@@ -241,6 +275,7 @@ export const useRefreshAgentChatThreads = () => {}addAgentChatThread(thread);+ addAgentChatThreadParticipants(page.participants);// The chat may have been selected before its record loaded, when usage couldn't be restored.const usageAtom = agentChatUsageComponentFamilyState.atomFamily({@@ -259,6 +294,7 @@ export const useRefreshAgentChatThreads = () => {},[addAgentChatThread,+ addAgentChatThreadParticipants,fetchAgentChatThreadsPage,refreshAgentChatThreadPermissions,store,diff --git a/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.ts b/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.tsdeleted file mode 100644index 8d706c985ab..00000000000--- a/packages/twenty-front/src/modules/ai/states/agentChatThreadParticipantsLoadCountState.ts+++ /dev/null@@ -1,8 +0,0 @@-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.tsindex 1bb85f597a4..038093f9a61 100644--- a/packages/twenty-front/src/modules/ai/states/agentChatThreadStreamedParticipantsState.ts+++ b/packages/twenty-front/src/modules/ai/states/agentChatThreadStreamedParticipantsState.ts@@ -1,8 +1,8 @@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+// Rows the server sent, kept so they are not lost before the first page of+// threads brings the member's rowsexport const agentChatThreadStreamedParticipantsState = createAtomState<Record<string, AgentChatThreadParticipantFieldsFragment>>({diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.tsindex d7f8f8d99d4..7dc612aa4ea 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/resolvers/agent-chat-thread-participant.resolver.ts@@ -1,5 +1,5 @@import { UseFilters, UseGuards, UseInterceptors } from '@nestjs/common';-import { Args, Mutation, Query } from '@nestjs/graphql';+import { Args, Mutation } from '@nestjs/graphql';import { PermissionFlagType } from 'twenty-shared/constants';@@ -39,17 +39,6 @@ export class AgentChatThreadParticipantResolver {private readonly threadService: AgentChatThreadService,) {}- @Query(() => [AgentChatThreadParticipantDTO])- async myAgentChatThreadParticipants(- @AuthWorkspaceMemberId() workspaceMemberId: string,- @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,- ): Promise<AgentChatThreadParticipantDTO[]> {- return this.participantService.findForWorkspaceMember({- workspaceId,- workspaceMemberId,- });- }-@Mutation(() => AgentChatThreadParticipantDTO)async markAgentChatThreadAsRead(@Args('threadId', { type: () => UUIDScalarType }) threadId: string,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 964402de77f..cbf6f717e77 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@@ -63,40 +63,6 @@ export class AgentChatThreadParticipantService {private readonly delayedJobsQueueService: MessageQueueService,) {}- // A member keeps their row after losing access to a thread, so rows are- // only returned for threads they can still read- async findForWorkspaceMember({- workspaceId,- workspaceMemberId,- }: Omit<AgentChatThreadAccessArgs, 'threadId'>): Promise<- AgentChatThreadParticipantDTO[]- > {- if (!(await this.sharingService.hasInboxState(workspaceId))) {- return [];- }-- // A snooze is ended by a queued job, which may not have run yet- const rows = await this.threadRepository.query(workspaceId, ({ manager }) =>- manager.query<AgentChatThreadParticipantDTO[]>(- `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],- ),- );-- const readableThreadIds = new Set(- await this.sharingService.findReadableThreadIds({- workspaceId,- workspaceMemberId,- threadIds: rows.map(({ threadId }) => threadId),- }),- );-- return rows.filter(({ threadId }) => readableThreadIds.has(threadId));- }-async markAsRead(args: AgentChatThreadAccessArgs,): Promise<AgentChatThreadParticipantDTO> {diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snapindex 317f566075a..1c164a96f30 100644--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap@@ -76,7 +76,6 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an"AgentChatThreadParticipantResolver.markAgentChatThreadAsRead {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.markAgentChatThreadAsUnread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.moveAgentChatThreadToInbox {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",- "AgentChatThreadParticipantResolver.myAgentChatThreadParticipants {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentChatThreadParticipantResolver.snoozeAgentChatThread {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}","AgentInboxResolver.sendInboxMessage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":true,"oauthClient":false,"userSession":false}]}","AgentResolver.createOneAgent {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",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 d1c60499fb0..fc5338bc043 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@@ -31,10 +31,6 @@ const SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);const PARTICIPANT_FIELDS ='id threadId lastReadAt archivedAt snoozedUntil updatedAt';-const MY_PARTICIPANTS = parse(- `query MyParticipants { myAgentChatThreadParticipants { ${PARTICIPANT_FIELDS} } }`,-);-const buildThreadMutation = (name: string) =>parse(`mutation Run($threadId: UUID!) { ${name}(threadId: $threadId) { ${PARTICIPANT_FIELDS} } }`,@@ -80,20 +76,42 @@ const runThreadMutation = (token,);-const findMyParticipant = async (+// Read the way the inbox does: rows come with the threads the caller can read+const findThreadParticipants = async (threadId: string,- token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,-): Promise<Participant | undefined> => {- const response = await makeMetadataApiRequest(- { query: MY_PARTICIPANTS },+ token: string,+): Promise<(Participant & { workspaceMemberId: string })[] | undefined> => {+ const response = await makeGraphqlApiRequest(+ findManyOperationFactory({+ objectMetadataSingularName: 'agentChatThread',+ objectMetadataPluralName: 'agentChatThreads',+ gqlFields: `id participants { edges { node { ${PARTICIPANT_FIELDS} workspaceMemberId } } }`,+ filter: { id: { eq: threadId } },+ }),token,);expect(response.body.errors).toBeUndefined();- return (- response.body.data.myAgentChatThreadParticipants as Participant[]- ).find((participant) => participant.threadId === threadId);+ const [thread] = response.body.data.agentChatThreads.edges;++ return thread?.node.participants.edges.map(+ ({ node }: { node: Participant & { workspaceMemberId: string } }) => node,+ );+};++const findMyParticipant = async (+ threadId: string,+ token: string = APPLE_JANE_ADMIN_ACCESS_TOKEN,+): Promise<Participant | undefined> => {+ const workspaceMemberId =+ token === APPLE_JONY_MEMBER_ACCESS_TOKEN+ ? WORKSPACE_MEMBER_DATA_SEED_IDS.JONY+ : WORKSPACE_MEMBER_DATA_SEED_IDS.JANE;++ return (await findThreadParticipants(threadId, token))?.find(+ (participant) => participant.workspaceMemberId === workspaceMemberId,+ );};const readThreadActivity = async (threadId: string) => {@@ -505,33 +523,6 @@ describe('Chat thread participant state through the authenticated API', () => {);});- 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();@@ -679,10 +670,6 @@ describe('Chat thread participant state through the authenticated API', () => {APPLE_JONY_MEMBER_ACCESS_TOKEN,);- const response = await makeMetadataApiRequest(- { query: MY_PARTICIPANTS },- APPLE_JONY_MEMBER_ACCESS_TOKEN,- );const rows: { workspaceMemberId: string }[] =await global.testDataSource.query(`SELECT "workspaceMemberId" FROM ${SCHEMA}."agentChatThreadParticipant" WHERE "threadId" = $1`,@@ -691,10 +678,12 @@ describe('Chat thread participant state through the authenticated API', () => {expect(rows).toHaveLength(2);expect(- (- response.body.data.myAgentChatThreadParticipants as Participant[]- ).filter((participant) => participant.threadId === threadId),- ).toHaveLength(1);+ await findThreadParticipants(threadId, APPLE_JONY_MEMBER_ACCESS_TOKEN),+ ).toEqual([+ expect.objectContaining({+ workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JONY,+ }),+ ]);});it('stops listing a thread once the member loses access to it', async () => {diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.integration-spec.tsindex 2cf95fbeab6..3af2eb8495a 100644--- a/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.integration-spec.ts+++ b/packages/twenty-server/test/integration/upgrade/suites/2-46-workspace-command-1790942019632-backfill-agent-chat-thread-inbox-state.integration-spec.ts@@ -60,7 +60,6 @@ describe('2-46 workspace commands - agent chat thread inbox state (integration)'let beforeUpgrade: {createdThreadLastActivityAt: string | null;recordedLastActivityAt: Date | null;- participants: unknown[];};const threadIds = [createdBeforeUpgradeThreadId,@@ -192,10 +191,6 @@ describe('2-46 workspace commands - agent chat thread inbox state (integration)'beforeUpgrade = {createdThreadLastActivityAt: createdThread.lastActivityAt ?? null,recordedLastActivityAt: lastActivityAt,- participants: await participantService.findForWorkspaceMember({- workspaceId: SEED_APPLE_WORKSPACE_ID,- workspaceMemberId: WORKSPACE_MEMBER_DATA_SEED_IDS.JANE,- }),};await insertThread(sharedThreadId);@@ -425,6 +420,5 @@ describe('2-46 workspace commands - agent chat thread inbox state (integration)'it('keeps chats working on a workspace the upgrade has not reached yet', () => {expect(beforeUpgrade.createdThreadLastActivityAt).toBeNull();expect(beforeUpgrade.recordedLastActivityAt).toBeNull();- expect(beforeUpgrade.participants).toEqual([]);});});