The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Show "Worked for X" instead of step count in AI chat thinking summary (#27611)
Félix Malfaitedc6292e71df
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.tsindex 0dafd60ee29..f96574297b1 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -8304,7 +8304,7 @@ 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 GetChatMessagesQuery = { __typename?: 'Query', chatMessages: Array<{ __typename?: 'AgentMessage', id: string, threadId: string, turnId?: string | null, senderUserWorkspaceId?: string | null, role: string, status: string, createdAt: string, processedAt?: string | null, 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 GetToolIndexQueryVariables = Exact<{ [key: string]: never; }>;@@ -10827,7 +10827,7 @@ export const FindWorkspaceAiStatsDocument = {"kind":"Document","definitions":[{"export const GetAgentChatOpenThreadsSummaryDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAgentChatOpenThreadsSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"agentChatOpenThreadsSummary"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"openThreadCount"}},{"kind":"Field","name":{"kind":"Name","value":"needsInputThreadCount"}},{"kind":"Field","name":{"kind":"Name","value":"hasUnreadOpenThread"}},{"kind":"Field","name":{"kind":"Name","value":"hasUnreadMentionThread"}},{"kind":"Field","name":{"kind":"Name","value":"hasUnreadAssignedThread"}}]}}]}}]} as unknown as DocumentNode<GetAgentChatOpenThreadsSummaryQuery, GetAgentChatOpenThreadsSummaryQueryVariables>;export const GetAgentRunsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetAgentRuns"},"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":"agentRuns"},"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":"threadTitle"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"errorMessage"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"startedAt"}},{"kind":"Field","name":{"kind":"Name","value":"endedAt"}},{"kind":"Field","name":{"kind":"Name","value":"modelId"}},{"kind":"Field","name":{"kind":"Name","value":"inputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"outputTokens"}},{"kind":"Field","name":{"kind":"Name","value":"credits"}},{"kind":"Field","name":{"kind":"Name","value":"creatorSource"}},{"kind":"Field","name":{"kind":"Name","value":"creatorName"}},{"kind":"Field","name":{"kind":"Name","value":"input"}},{"kind":"Field","name":{"kind":"Name","value":"reply"}},{"kind":"Field","name":{"kind":"Name","value":"toolNames"}}]}}]}}]} as unknown as DocumentNode<GetAgentRunsQuery, GetAgentRunsQueryVariables>;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 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":"processedAt"}},{"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 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/AiChatAssistantMessageRenderer.tsx b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsxindex c48546bc2eb..166498d6256 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatAssistantMessageRenderer.tsx@@ -113,11 +113,13 @@ export const AiChatAssistantMessageRenderer = ({isLastMessageStreaming,hasError,shouldHideThinkingSteps = false,+ workDurationMs,}: {messageParts: ExtendedUIMessagePart[];isLastMessageStreaming: boolean;hasError?: boolean;shouldHideThinkingSteps?: boolean;+ workDurationMs?: number | null;}) => {const frontComponentIdByToolName = useFrontComponentIdByToolName();@@ -158,6 +160,10 @@ export const AiChatAssistantMessageRenderer = ({: groupedRenderItems;const lastRenderItemIndex = renderItems.length - 1;+ // the duration covers the whole message, so only the steps right before the final answer carry it+ const lastThinkingStepsRenderItemIndex = renderItems.findLastIndex(+ (renderItem) => renderItem.type === 'thinking-steps',+ );if (!renderItems.length && !hasError) {const hasOnlyHiddenReasoning =@@ -191,6 +197,11 @@ export const AiChatAssistantMessageRenderer = ({!hasError &&index === lastRenderItemIndex}+ workDurationMs={+ index === lastThinkingStepsRenderItemIndex+ ? workDurationMs+ : null+ }/>) : (<MessagePartRendererdiff --git a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsxindex 68419f3ecae..7a6382a7763 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatMessage.tsx@@ -14,6 +14,7 @@ import { agentChatFirstUnreadMessageIdSelector } from '@/ai/states/selectors/ageimport { agentChatIsMessageBeforeFirstUserMessageFamilySelector } from '@/ai/states/selectors/agentChatIsMessageBeforeFirstUserMessageFamilySelector';import { agentChatMessageFamilySelector } from '@/ai/states/selectors/agentChatMessageFamilySelector';import { getAgentChatSenderLabel } from '@/ai/utils/getAgentChatSenderLabel';+import { getAgentChatMessageWorkDurationMs } from '@/ai/utils/getAgentChatMessageWorkDurationMs';import { type AiChatError } from '@/ai/types/AiChatError';import { LightCopyIconButton } from '@/ui/input/components/LightCopyIconButton';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';@@ -229,6 +230,10 @@ export const AiChatMessage = ({messageParts={agentChatMessage.parts}hasError={shouldShowError}shouldHideThinkingSteps={isMessageBeforeFirstUserMessage}+ workDurationMs={getAgentChatMessageWorkDurationMs({+ metadata: agentChatMessage.metadata,+ isStreaming: isLastMessageStreaming,+ })}/>);diff --git a/packages/twenty-front/src/modules/ai/components/ThinkingStepsDisplay.tsx b/packages/twenty-front/src/modules/ai/components/ThinkingStepsDisplay.tsxindex 382bf71e27c..8c3e5d2ed80 100644--- a/packages/twenty-front/src/modules/ai/components/ThinkingStepsDisplay.tsx+++ b/packages/twenty-front/src/modules/ai/components/ThinkingStepsDisplay.tsx@@ -2,6 +2,7 @@ import { styled } from '@linaria/react';import { plural, t } from '@lingui/core/macro';import { useState } from 'react';import { IconChevronRight, IconCpu } from 'twenty-ui/icon';+import { isDefined } from 'twenty-shared/utils';import { themeCssVariables } from 'twenty-ui/theme';import { AiChatThinkingRow } from '@/ai/components/AiChatThinkingRow';@@ -12,6 +13,7 @@ import { getActiveReasoningContent } from '@/ai/utils/getActiveReasoningContent'import { getLastReasoningContent } from '@/ai/utils/getLastReasoningContent';import { isThinkingStepPartActive } from '@/ai/utils/isThinkingStepPartActive';import { type ThinkingStepPart } from '@/ai/types/ThinkingStepPart';+import { formatRoundedDuration } from '~/utils/format/formatRoundedDuration';const StyledContainer = styled.div`display: flex;@@ -160,11 +162,13 @@ export const ThinkingStepsDisplay = ({isLastMessageStreaming,hasAssistantTextResponseStarted,isTrailingWhileStreaming = false,+ workDurationMs,}: {parts: ThinkingStepPart[];isLastMessageStreaming: boolean;hasAssistantTextResponseStarted: boolean;isTrailingWhileStreaming?: boolean;+ workDurationMs?: number | null;}) => {const [isExpanded, setIsExpanded] = useState(false);@@ -198,10 +202,12 @@ export const ThinkingStepsDisplay = ({<IconChevronRight size={14} /></StyledSummaryChevronContainer><StyledSummaryText>- {plural(stepCount, {- one: '# step',- other: '# steps',- })}+ {isDefined(workDurationMs)+ ? t`Worked for ${formatRoundedDuration(workDurationMs)}`+ : plural(stepCount, {+ one: '# step',+ other: '# steps',+ })}</StyledSummaryText></StyledSummaryButton>)}diff --git a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsxindex 69c77165821..f0508206f51 100644--- a/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx+++ b/packages/twenty-front/src/modules/ai/components/__stories__/AiChatMessage.stories.tsx@@ -232,6 +232,8 @@ const mockThinkingStepsDone: ExtendedUIMessage = {],metadata: {createdAt: new Date().toISOString(),+ startedAt: '2026-01-01T10:00:00.000Z',+ finishedAt: '2026-01-01T10:01:23.000Z',},};@@ -367,7 +369,7 @@ export const ThinkingStepsDoneExpanded: Story = {play: async ({ canvasElement }) => {const canvas = within(canvasElement);const summaryButton = await canvas.findByRole('button', {- name: /2 steps/i,+ name: /worked for 1m 23s/i,});await userEvent.click(summaryButton);diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsxindex 4757e69f69e..82b40950da1 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/AiChatAssistantMessageRenderer.test.tsx@@ -9,13 +9,15 @@ jest.mock('@/ai/components/ThinkingStepsDisplay', () => ({hasAssistantTextResponseStarted,parts,isTrailingWhileStreaming,+ workDurationMs,}: {parts: unknown[];hasAssistantTextResponseStarted: boolean;isTrailingWhileStreaming?: boolean;+ workDurationMs?: number | null;}) => (<div data-testid="thinking-steps-display">- {`thinking-${parts.length}-${hasAssistantTextResponseStarted ? 'answer-started' : 'answer-pending'}${isTrailingWhileStreaming ? '-trailing-while-streaming' : ''}`}+ {`thinking-${parts.length}-${hasAssistantTextResponseStarted ? 'answer-started' : 'answer-pending'}${isTrailingWhileStreaming ? '-trailing-while-streaming' : ''}${workDurationMs ? `-worked-${workDurationMs}` : ''}`}</div>),}));@@ -51,9 +53,11 @@ const renderAssistantRenderer = ({isLastMessageStreaming = false,shouldHideThinkingSteps = false,+ workDurationMs,}: {isLastMessageStreaming?: boolean;shouldHideThinkingSteps?: boolean;+ workDurationMs?: number | null;} = {},) => {return render(@@ -62,6 +66,7 @@ const renderAssistantRenderer = (messageParts={messageParts}isLastMessageStreaming={isLastMessageStreaming}shouldHideThinkingSteps={shouldHideThinkingSteps}+ workDurationMs={workDurationMs}/></ThemeProvider>,);@@ -102,6 +107,44 @@ describe('AiChatAssistantMessageRenderer', () => {);});+ it('should give the work duration to the last group of thinking steps only', () => {+ const messageParts = [+ {+ type: 'reasoning',+ text: 'First reasoning',+ state: 'done',+ },+ {+ type: 'text',+ text: 'Intermediate answer',+ },+ {+ type: 'tool-web_search',+ toolCallId: 'tool-1',+ input: { query: 'crm software' },+ output: { result: { ok: true } },+ state: 'output-available',+ },+ {+ type: 'text',+ text: 'Final answer',+ },+ ] as ExtendedUIMessagePart[];++ renderAssistantRenderer(messageParts, { workDurationMs: 83_000 });++ const thinkingStepsDisplays = screen.getAllByTestId(+ 'thinking-steps-display',+ );++ expect(thinkingStepsDisplays[0]).toHaveTextContent(+ /^thinking-1-answer-started$/,+ );+ expect(thinkingStepsDisplays[1]).toHaveTextContent(+ 'thinking-1-answer-started-worked-83000',+ );+ });+it('should keep answer-started false for thinking blocks with no following text', () => {const messageParts = [{diff --git a/packages/twenty-front/src/modules/ai/components/__tests__/ThinkingStepsDisplay.test.tsx b/packages/twenty-front/src/modules/ai/components/__tests__/ThinkingStepsDisplay.test.tsxindex 3a3019c02cb..bd3a88d3f2c 100644--- a/packages/twenty-front/src/modules/ai/components/__tests__/ThinkingStepsDisplay.test.tsx+++ b/packages/twenty-front/src/modules/ai/components/__tests__/ThinkingStepsDisplay.test.tsx@@ -107,11 +107,13 @@ const renderThinkingStepsDisplay = ({isLastMessageStreaming,parts,isTrailingWhileStreaming = false,+ workDurationMs,}: {parts: ThinkingStepPart[];isLastMessageStreaming: boolean;hasAssistantTextResponseStarted?: boolean;isTrailingWhileStreaming?: boolean;+ workDurationMs?: number | null;}) => {return render(<ThemeProvider colorScheme="light">@@ -120,6 +122,7 @@ const renderThinkingStepsDisplay = ({isLastMessageStreaming={isLastMessageStreaming}hasAssistantTextResponseStarted={hasAssistantTextResponseStarted}isTrailingWhileStreaming={isTrailingWhileStreaming}+ workDurationMs={workDurationMs}/></ThemeProvider>,);@@ -212,6 +215,20 @@ describe('ThinkingStepsDisplay', () => {expect(screen.queryByText('Completed reasoning content')).toBeNull();});+ it('should summarize done state with the work duration when known', () => {+ renderThinkingStepsDisplay({+ isLastMessageStreaming: false,+ hasAssistantTextResponseStarted: true,+ workDurationMs: 83_000,+ parts: [createToolPart(), createReasoningPart()],+ });++ expect(+ screen.getByRole('button', { name: 'Worked for 1m 23s' }),+ ).toHaveAttribute('aria-expanded', 'false');+ expect(screen.queryByText(/steps/i)).toBeNull();+ });+it('should keep done state expanded while streaming before answer text starts', () => {renderThinkingStepsDisplay({isLastMessageStreaming: true,diff --git a/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts b/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.tsindex 9fadd8f74e3..24fe353361b 100644--- a/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts+++ b/packages/twenty-front/src/modules/ai/graphql/queries/getChatMessages.ts@@ -10,6 +10,7 @@ export const GET_CHAT_MESSAGES = gql`rolestatuscreatedAt+ processedAtparts {idmessageIddiff --git a/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatMessageWorkDurationMs.test.ts b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatMessageWorkDurationMs.test.tsnew file mode 100644index 00000000000..2bd334344bd--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/__tests__/getAgentChatMessageWorkDurationMs.test.ts@@ -0,0 +1,66 @@+import { getAgentChatMessageWorkDurationMs } from '@/ai/utils/getAgentChatMessageWorkDurationMs';++const STARTED_AT = '2026-01-01T10:00:00.000Z';++describe('getAgentChatMessageWorkDurationMs', () => {+ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(new Date('2026-01-01T10:00:30.000Z'));+ });++ afterEach(() => {+ jest.useRealTimers();+ });++ it('returns the time between start and finish', () => {+ expect(+ getAgentChatMessageWorkDurationMs({+ metadata: {+ createdAt: STARTED_AT,+ startedAt: STARTED_AT,+ finishedAt: '2026-01-01T10:01:23.000Z',+ },+ isStreaming: false,+ }),+ ).toBe(83_000);+ });++ it('measures up to now while the message is still streaming', () => {+ expect(+ getAgentChatMessageWorkDurationMs({+ metadata: { createdAt: STARTED_AT, startedAt: STARTED_AT },+ isStreaming: true,+ }),+ ).toBe(30_000);+ });++ it('returns null when a message stopped streaming without a finish time', () => {+ expect(+ getAgentChatMessageWorkDurationMs({+ metadata: { createdAt: STARTED_AT, startedAt: STARTED_AT },+ isStreaming: false,+ }),+ ).toBeNull();+ });++ it('returns null without a start time', () => {+ expect(+ getAgentChatMessageWorkDurationMs({+ metadata: { createdAt: STARTED_AT },+ isStreaming: true,+ }),+ ).toBeNull();+ });++ it('returns null for a message saved in one go', () => {+ expect(+ getAgentChatMessageWorkDurationMs({+ metadata: {+ createdAt: STARTED_AT,+ startedAt: STARTED_AT,+ finishedAt: '2026-01-01T10:00:00.040Z',+ },+ isStreaming: false,+ }),+ ).toBeNull();+ });+});diff --git a/packages/twenty-front/src/modules/ai/utils/getAgentChatMessageWorkDurationMs.ts b/packages/twenty-front/src/modules/ai/utils/getAgentChatMessageWorkDurationMs.tsnew file mode 100644index 00000000000..eb56a71e65d--- /dev/null+++ b/packages/twenty-front/src/modules/ai/utils/getAgentChatMessageWorkDurationMs.ts@@ -0,0 +1,31 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type ExtendedUIMessage } from 'twenty-shared/ai';++const MINIMUM_WORK_DURATION_MS = 1000;++export const getAgentChatMessageWorkDurationMs = ({+ metadata,+ isStreaming,+}: {+ metadata: ExtendedUIMessage['metadata'];+ isStreaming: boolean;+}): number | null => {+ const startedAt = metadata?.startedAt;+ const finishedAt = metadata?.finishedAt;++ if (!isNonEmptyString(startedAt)) {+ return null;+ }++ if (!isNonEmptyString(finishedAt) && !isStreaming) {+ return null;+ }++ const endedAtMs = isNonEmptyString(finishedAt)+ ? new Date(finishedAt).getTime()+ : Date.now();+ const durationMs = endedAtMs - new Date(startedAt).getTime();++ // messages written in a single save, like agent run replies, carry no real duration+ return durationMs >= MINIMUM_WORK_DURATION_MS ? durationMs : null;+};diff --git a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts b/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.tsindex dbb30a9b46c..ea15ca64788 100644--- a/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts+++ b/packages/twenty-front/src/modules/ai/utils/mapDBMessagesToUIMessages.ts@@ -1,4 +1,5 @@import { mapDBPartToUIMessagePart } from '@/ai/utils/mapDBPartToUIMessagePart';+import { AGENT_MESSAGE_ROLE } from '@/ai/constants/AgentMessageRole';import { type ExtendedUIMessage } from 'twenty-shared/ai';import { isDefined } from 'twenty-shared/utils';import { type AgentMessage } from '~/generated-metadata/graphql';@@ -17,6 +18,13 @@ export const mapDBMessagesToUIMessages = (metadata: {createdAt: dbMessage.createdAt,senderUserWorkspaceId: dbMessage.senderUserWorkspaceId,+ ...(dbMessage.role === AGENT_MESSAGE_ROLE.ASSISTANT+ ? {+ startedAt: dbMessage.createdAt,+ // the assistant message is rewritten until its stream finishes+ finishedAt: dbMessage.processedAt ?? undefined,+ }+ : {}),},threadId: dbMessage.threadId,}));diff --git a/packages/twenty-front/src/utils/format/__tests__/formatRoundedDuration.test.ts b/packages/twenty-front/src/utils/format/__tests__/formatRoundedDuration.test.tsnew file mode 100644index 00000000000..0d36c41d77e--- /dev/null+++ b/packages/twenty-front/src/utils/format/__tests__/formatRoundedDuration.test.ts@@ -0,0 +1,16 @@+import { formatRoundedDuration } from '~/utils/format/formatRoundedDuration';++describe('formatRoundedDuration', () => {+ it.each<[number, string]>([+ [0, '0s'],+ [1_400, '1s'],+ [12_400, '12s'],+ [59_600, '1m'],+ [83_000, '1m 23s'],+ [120_000, '2m'],+ [3_600_000, '1h'],+ [3_960_000, '1h 6m'],+ ])('formats %sms as %s', (durationMs, expected) => {+ expect(formatRoundedDuration(durationMs)).toBe(expected);+ });+});diff --git a/packages/twenty-front/src/utils/format/formatRoundedDuration.ts b/packages/twenty-front/src/utils/format/formatRoundedDuration.tsnew file mode 100644index 00000000000..20d02750790--- /dev/null+++ b/packages/twenty-front/src/utils/format/formatRoundedDuration.ts@@ -0,0 +1,26 @@+import { t } from '@lingui/core/macro';++const SECONDS_PER_MINUTE = 60;+const SECONDS_PER_HOUR = 3600;++export const formatRoundedDuration = (durationMs: number): string => {+ const totalSeconds = Math.max(0, Math.round(durationMs / 1000));++ if (totalSeconds < SECONDS_PER_MINUTE) {+ return t`${totalSeconds}s`;+ }++ if (totalSeconds < SECONDS_PER_HOUR) {+ const minutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE);+ const seconds = totalSeconds % SECONDS_PER_MINUTE;++ return seconds === 0 ? t`${minutes}m` : t`${minutes}m ${seconds}s`;+ }++ const hours = Math.floor(totalSeconds / SECONDS_PER_HOUR);+ const minutes = Math.floor(+ (totalSeconds % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE,+ );++ return minutes === 0 ? t`${hours}h` : t`${hours}h ${minutes}m`;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.tsindex a6c0b67195a..4b8c50e3827 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/jobs/stream-agent-chat.job.ts@@ -656,9 +656,16 @@ export class StreamAgentChatJob {usageTotals.conversationSize = part.usage?.inputTokens ?? 0;}+ if (part.type === 'start') {+ return { startedAt: new Date().toISOString() };+ }+if (part.type === 'finish') {+ const finishedAt = new Date().toISOString();+return {- createdAt: new Date().toISOString(),+ createdAt: finishedAt,+ finishedAt,usage: {inputTokens: usageTotals.inputTokens,outputTokens: usageTotals.outputTokens,diff --git a/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.tsindex bfb0f1a6c35..b8eb0c4a4a2 100644--- a/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts+++ b/packages/twenty-shared/src/ai/types/ExtendedUIMessage.ts@@ -16,7 +16,9 @@ export type AiChatModelMetadata = {};type Metadata = {- createdAt: string;+ createdAt?: string;+ startedAt?: string;+ finishedAt?: string;senderUserWorkspaceId?: string | null;usage?: AiChatUsageMetadata;model?: AiChatModelMetadata;