The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(workflow): record each agent step execution as a conversation (#26765)
Félix Malfait0ef5816d5fe2
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 9bc9c0e6c1c..701a15e8d9b 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -96,7 +96,7 @@ export type AdminChatThreadListItem = {userFirstName?: Maybe<Scalars['String']['output']>;userLastName?: Maybe<Scalars['String']['output']>;userReplyCount: Scalars['Int']['output'];- userWorkspaceId: Scalars['UUID']['output'];+ userWorkspaceId?: Maybe<Scalars['UUID']['output']>;workspaceDisplayName?: Maybe<Scalars['String']['output']>;workspaceId: Scalars['UUID']['output'];};@@ -1501,7 +1501,7 @@ export type GetAdminChatThreadsQueryVariables = Exact<{}>;-export type GetAdminChatThreadsQuery = { __typename?: 'Query', getAdminChatThreads: { __typename?: 'PaginatedAdminChatThreads', totalCount: number, hasMore: boolean, threads: Array<{ __typename?: 'AdminChatThreadListItem', id: string, title?: string | null, workspaceId: string, workspaceDisplayName?: string | null, userWorkspaceId: string, userEmail?: string | null, userFirstName?: string | null, userLastName?: string | null, messageCount: number, userReplyCount: number, hasError: boolean, isOnboardingThread: boolean, deletedAt?: string | null, createdAt: string, updatedAt: string }> } };+export type GetAdminChatThreadsQuery = { __typename?: 'Query', getAdminChatThreads: { __typename?: 'PaginatedAdminChatThreads', totalCount: number, hasMore: boolean, threads: Array<{ __typename?: 'AdminChatThreadListItem', id: string, title?: string | null, workspaceId: string, workspaceDisplayName?: string | null, userWorkspaceId?: string | null, userEmail?: string | null, userFirstName?: string | null, userLastName?: string | null, messageCount: number, userReplyCount: number, hasError: boolean, isOnboardingThread: boolean, deletedAt?: string | null, createdAt: string, updatedAt: string }> } };export type GetAdminWorkspaceChatThreadsQueryVariables = Exact<{workspaceId: Scalars['UUID']['input'];diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepAiAgentConversationButton.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepAiAgentConversationButton.tsxnew file mode 100644index 00000000000..d7754745ae1--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepAiAgentConversationButton.tsx@@ -0,0 +1,32 @@+import { useLingui } from '@lingui/react/macro';+import { isDefined } from 'twenty-shared/utils';+import { IconMessage } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/primitives/input';++import { useOpenAskAiThread } from '@/ai/hooks/useOpenAskAiThread';+import { useWorkflowRunStepInfo } from '@/workflow/workflow-steps/hooks/useWorkflowRunStepInfo';++export const WorkflowRunStepAiAgentConversationButton = ({+ stepId,+}: {+ stepId: string;+}) => {+ const { t } = useLingui();+ const { openAskAiThread } = useOpenAskAiThread();+ const stepInfo = useWorkflowRunStepInfo({ stepId });+ const threadId = stepInfo?.threadId;++ if (!isDefined(threadId)) {+ return null;+ }++ return (+ <Button+ startIcon={<IconMessage />}+ size="sm"+ onClick={() => openAskAiThread(threadId)}+ >+ {t`Open conversation`}+ </Button>+ );+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsDetail.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsDetail.tsxindex 30091fd8818..cc443584368 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsDetail.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsDetail.tsx@@ -11,6 +11,7 @@ import { useFlowOrThrow } from '@/workflow/hooks/useFlowOrThrow';import { useWorkflowRunIdOrThrow } from '@/workflow/hooks/useWorkflowRunIdOrThrow';import { useWorkflowRunStepLog } from '@/workflow/hooks/useWorkflowRunStepLog';import { getIsDescendantOfIterator } from '@/workflow/workflow-steps/utils/getIsDescendantOfIterator';+import { WorkflowRunStepAiAgentConversationButton } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepAiAgentConversationButton';import { WorkflowRunStepLogsAiAgentDetail } from '@/workflow/workflow-steps/workflow-actions/ai-agent-action/components/WorkflowRunStepLogsAiAgentDetail';import { WorkflowRunStepLogsCodeDetail } from '@/workflow/workflow-steps/workflow-actions/code-action/components/WorkflowRunStepLogsCodeDetail';import { WorkflowRunStepLogsEmailDetail } from '@/workflow/workflow-steps/workflow-actions/components/WorkflowRunStepLogsEmailDetail';@@ -62,6 +63,7 @@ export const WorkflowRunStepLogsDetail = ({ stepId }: { stepId: string }) => {<IconInfoCircle size={20} /><div>{t`No logs were recorded for this step.`}</div></StyledEmptyState>+ <WorkflowRunStepAiAgentConversationButton stepId={stepId} /></StyledRoot>);}@@ -93,7 +95,12 @@ export const WorkflowRunStepLogsDetail = ({ stepId }: { stepId: string }) => {const renderDetails = () => {switch (stepLog.details.type) {case 'AI_AGENT':- return <WorkflowRunStepLogsAiAgentDetail details={stepLog.details} />;+ return (+ <>+ <WorkflowRunStepAiAgentConversationButton stepId={stepId} />+ <WorkflowRunStepLogsAiAgentDetail details={stepLog.details} />+ </>+ );case 'CODE':return <WorkflowRunStepLogsCodeDetail details={stepLog.details} />;case 'HTTP_REQUEST':diff --git a/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts b/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.tsindex 471701592e3..d1b4241042b 100644--- a/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts+++ b/packages/twenty-server/src/database/commands/agent-history/utils/get-agent-history-schema-additions.util.ts@@ -44,7 +44,10 @@ export const getAgentHistorySchemaAdditions = ({((current.readability === MetadataReadability.SYSTEM &¤t.writability === MetadataWritability.SYSTEM) ||(identifier === STANDARD_OBJECTS.agentChatThread.universalIdentifier &&- current.readability === MetadataReadability.PRIVATE &&+ // INHERITED once threads can belong to a workflow run; a thread+ // without one still reads only through its own grants.+ (current.readability === MetadataReadability.PRIVATE ||+ current.readability === MetadataReadability.INHERITED) &¤t.writability === MetadataWritability.OPEN));if (isDefined(current) &&diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.tsindex 271401daba6..273d67e9c79 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-upgrade-version-command.module.ts@@ -9,6 +9,7 @@ import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cacheimport { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';import { AgentHistoryMigrationModule } from 'src/database/commands/agent-history/agent-history-migration.module';import { LinkChatMessageSendersToWorkspaceMembersCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790605326331-link-chat-message-senders-to-workspace-members.command';+import { AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-runner/workspace-migration-runner.module';@@ -27,6 +28,7 @@ import { WorkspaceMigrationRunnerModule } from 'src/engine/workspace-manager/worDeleteFieldLessIndexMetadataCommand,FollowWorkflowVisibilityOnRunsCommand,LinkChatMessageSendersToWorkspaceMembersCommand,+ AddWorkflowRunToChatThreadsCommand,],})export class V2_44_UpgradeVersionCommandModule {}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.tsnew file mode 100644index 00000000000..4028a6878c5--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command.ts@@ -0,0 +1,241 @@+import { Command } from 'nest-commander';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { MetadataReadability } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';+import { LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER } from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant';+import { getStandardFlatEntitiesToCreateOrThrow } from 'src/database/commands/upgrade-version-command/2-10/utils/get-standard-flat-entities-to-create-or-throw.util';+import { ApplicationService } from 'src/engine/core-modules/application/application.service';+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';++const WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS = [+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,+ STANDARD_OBJECTS.agentChatThread.fields.workflowStepId.universalIdentifier,+ STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,+];++const WORKFLOW_RUN_THREAD_INDEX_UNIVERSAL_IDENTIFIERS = [+ STANDARD_OBJECTS.agentChatThread.indexes.workflowRunIndex.universalIdentifier,+];++// A workflow agent step now records each execution as a chat thread owned by+// its run rather than by a member. Threads therefore stop requiring an owner+// and inherit readability from the run; a thread without a run has no parent,+// so member chats keep reading exactly as they did under PRIVATE.+@RegisteredWorkspaceCommand('2.44.0', 1790607161319)+@Command({+ name: 'upgrade:2-44:add-workflow-run-to-chat-threads',+ description:+ 'Link chat threads to workflow runs and make threads inherit readability from their run',+})+export class AddWorkflowRunToChatThreadsCommand extends ProvisionedWorkspaceCommandRunner {+ constructor(+ protected readonly workspaceIteratorService: WorkspaceIteratorService,+ private readonly applicationService: ApplicationService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,+ ) {+ super(workspaceIteratorService);+ }++ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {+ await this.up(args);+ }++ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ 'flatIndexMaps',+ ]);++ const threadObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.universalIdentifier+ ];+ const workflowRunObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.workflowRun.universalIdentifier+ ];++ if (!isDefined(threadObject) || !isDefined(workflowRunObject)) {+ this.logger.log(+ `agentChatThread or workflowRun object not found for workspace ${workspaceId}, skipping`,+ );++ return;+ }++ const { twentyStandardFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );+ const { allFlatEntityMaps: standardAllFlatEntityMaps } =+ computeTwentyStandardApplicationAllFlatEntityMaps({+ now: new Date().toISOString(),+ workspaceId,+ twentyStandardApplicationId: twentyStandardFlatApplication.id,+ });++ const fieldsToCreate =+ getStandardFlatEntitiesToCreateOrThrow<FlatFieldMetadata>({+ standardFlatEntityMaps: standardAllFlatEntityMaps.flatFieldMetadataMaps,+ existingFlatEntityMaps: flatFieldMetadataMaps,+ universalIdentifiers: WORKFLOW_RUN_THREAD_FIELD_UNIVERSAL_IDENTIFIERS,+ });+ const indexesToCreate =+ getStandardFlatEntitiesToCreateOrThrow<FlatIndexMetadata>({+ standardFlatEntityMaps: standardAllFlatEntityMaps.flatIndexMaps,+ existingFlatEntityMaps: flatIndexMaps,+ universalIdentifiers: WORKFLOW_RUN_THREAD_INDEX_UNIVERSAL_IDENTIFIERS,+ });++ const ownerField =+ flatFieldMetadataMaps.byUniversalIdentifier[+ LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER+ ];+ const fieldsToUpdate: FlatFieldMetadata[] =+ isDefined(ownerField) && !ownerField.isNullable+ ? [{ ...ownerField, isNullable: true }]+ : [];++ if (options.dryRun ?? false) {+ this.logger.log(+ `[DRY RUN] Would create ${fieldsToCreate.length} field(s) and ${indexesToCreate.length} index(es), update ${fieldsToUpdate.length} field(s), then make chat threads inherit readability from their run for workspace ${workspaceId}`,+ );++ return;+ }++ if (+ fieldsToCreate.length + indexesToCreate.length + fieldsToUpdate.length >+ 0+ ) {+ await this.runMigration({+ workspaceId,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ allFlatEntityOperationByMetadataName: {+ fieldMetadata: {+ flatEntityToCreate: fieldsToCreate,+ flatEntityToDelete: [],+ flatEntityToUpdate: fieldsToUpdate,+ },+ index: {+ flatEntityToCreate: indexesToCreate,+ flatEntityToDelete: [],+ flatEntityToUpdate: [],+ },+ },+ });+ }++ // Only threads already under common sharing (2.43) inherit: SYSTEM+ // threads are still owner-only and have no owner grants yet, so making+ // them inherit would lock owners out of their own chats.+ if (threadObject.readability !== MetadataReadability.PRIVATE) {+ this.logger.log(+ `agentChatThread readability is ${threadObject.readability} for workspace ${workspaceId}, leaving it`,+ );++ return;+ }++ // Readability names the parent field, so it can only change once the+ // field exists.+ const flatObjectMetadatasToUpdate: FlatObjectMetadata[] = [+ {+ ...threadObject,+ readability: MetadataReadability.INHERITED,+ readabilityParentFieldUniversalIdentifiers: [+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun+ .universalIdentifier,+ ],+ },+ ];++ await this.runMigration({+ workspaceId,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ allFlatEntityOperationByMetadataName: {+ objectMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: flatObjectMetadatasToUpdate,+ },+ },+ });+ }++ async down({ workspaceId }: RunOnWorkspaceArgs): Promise<void> {+ const { flatObjectMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ ]);+ const threadObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.universalIdentifier+ ];++ if (!isDefined(threadObject)) {+ return;+ }++ const { twentyStandardFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );++ // The run link and its conversations stay: under PRIVATE nobody but a+ // thread's own grantees reads it, and ownerless run threads have none.+ await this.runMigration({+ workspaceId,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ allFlatEntityOperationByMetadataName: {+ objectMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: [+ {+ ...threadObject,+ readability: MetadataReadability.PRIVATE,+ readabilityParentFieldUniversalIdentifiers: null,+ },+ ],+ },+ },+ });+ }++ private async runMigration(+ args: Omit<+ Parameters<+ WorkspaceMigrationValidateBuildAndRunService['validateBuildAndRunLegacyWorkspaceMigration']+ >[0],+ 'isSystemBuild'+ >,+ ): Promise<void> {+ const result =+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(+ { ...args, isSystemBuild: true },+ );++ if (result.status === 'fail') {+ throw new Error(+ `Failed to link chat threads to workflow runs for workspace ${args.workspaceId}: ${JSON.stringify(result, null, 2)}`,+ );+ }+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant.tsnew file mode 100644index 00000000000..c409b5b1365--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant.ts@@ -0,0 +1,4 @@+// Pinned here rather than read from the standard objects, which drop the+// legacy owner column: commands using it must still build and run without it.+export const LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER =+ 'bf830886-b6dc-46e9-a229-eecbb0e66032';diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.tsindex 5d6f959b54f..9f872a1e6ca 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/admin-chat-thread-list-item.dto.ts@@ -16,8 +16,9 @@ export class AdminChatThreadListItemDTO {@Field(() => String, { nullable: true })workspaceDisplayName: string | null;- @Field(() => UUIDScalarType)- userWorkspaceId: string;+ // A workflow run's conversation belongs to the run, not to a member.+ @Field(() => UUIDScalarType, { nullable: true })+ userWorkspaceId: string | null;@Field(() => String, { nullable: true })userEmail: string | null;diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.tsindex 6b31c2e50b2..ef340dee64b 100644--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-global-chat-threads.service.ts@@ -29,7 +29,7 @@ type GlobalChatThreadRawRow = {title: string | null;workspaceId: string;workspaceDisplayName: string | null;- userWorkspaceId: string;+ userWorkspaceId: string | null;userEmail: string | null;userFirstName: string | null;userLastName: string | null;@@ -113,7 +113,7 @@ export class AdminPanelGlobalChatThreadsService {membership.id AS "userWorkspaceId", owner.email AS "userEmail", owner."firstName" AS "userFirstName", owner."lastName" AS "userLastName",thread."archivedAt" AS "deletedAt", thread."createdAt", thread."updatedAt", thread."lastStreamError" IS NOT NULL AS "hasError",(EXISTS (SELECT 1 FROM ${table('agentMessage')} hidden WHERE hidden."threadId" = thread.id AND hidden."isHidden" = true)- OR thread.id = public.uuid_generate_v5($2::uuid, workspace.id::text || ':' || membership.id::text)) AS "isOnboardingThread",+ OR (membership.id IS NOT NULL AND thread.id = public.uuid_generate_v5($2::uuid, workspace.id::text || ':' || membership.id::text))) AS "isOnboardingThread",(SELECT COUNT(*)::int FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message."isHidden" = false) AS "messageCount",((SELECT COUNT(*) FROM ${table('agentMessage')} message WHERE message."threadId" = thread.id AND message."isHidden" = false AND message.role = 'user')+ (SELECT COUNT(*) FROM ${table('agentMessagePart')} part JOIN ${table('agentMessage')} message ON message.id = part."messageId"diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ai-steps-to-ui-message-parts.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ai-steps-to-ui-message-parts.util.spec.tsnew file mode 100644index 00000000000..cdda6f879d6--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/__tests__/map-ai-steps-to-ui-message-parts.util.spec.ts@@ -0,0 +1,103 @@+import { type StepResult, type ToolSet } from 'ai';++import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';++const buildStep = (+ content: StepResult<ToolSet>['content'],+): Pick<StepResult<ToolSet>, 'content'> => ({ content });++describe('mapAiStepsToUiMessageParts', () => {+ it('turns each step into the parts a chat stream would have stored', () => {+ const parts = mapAiStepsToUiMessageParts([+ buildStep([+ { type: 'reasoning', text: 'Looking the company up first' },+ {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'find_companies',+ input: { name: 'Acme' },+ },+ {+ type: 'tool-result',+ toolCallId: 'call-1',+ toolName: 'find_companies',+ input: { name: 'Acme' },+ output: { records: [{ id: 'company-1' }] },+ },+ ]),+ buildStep([{ type: 'text', text: 'Acme exists.' }]),+ ]);++ expect(parts).toEqual([+ { type: 'step-start' },+ {+ type: 'reasoning',+ text: 'Looking the company up first',+ providerMetadata: undefined,+ },+ {+ type: 'tool-find_companies',+ toolCallId: 'call-1',+ state: 'output-available',+ input: { name: 'Acme' },+ output: { records: [{ id: 'company-1' }] },+ providerExecuted: undefined,+ },+ { type: 'step-start' },+ { type: 'text', text: 'Acme exists.' },+ ]);+ });++ it('records a failed tool call as an error on its call', () => {+ const parts = mapAiStepsToUiMessageParts([+ buildStep([+ {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'send_email',+ input: {},+ },+ {+ type: 'tool-error',+ toolCallId: 'call-1',+ toolName: 'send_email',+ input: {},+ error: new Error('No connected account'),+ },+ ]),+ ]);++ expect(parts[1]).toMatchObject({+ type: 'tool-send_email',+ state: 'output-error',+ errorText: 'Error: No connected account',+ });+ });++ // A dangling call is finalized by the storage path, not dropped here.+ it('keeps a call that never got a result as waiting on its input', () => {+ const parts = mapAiStepsToUiMessageParts([+ buildStep([+ {+ type: 'tool-call',+ toolCallId: 'call-1',+ toolName: 'find_people',+ input: {},+ },+ ]),+ ]);++ expect(parts[1]).toMatchObject({ state: 'input-available' });+ });++ it('skips empty text and reasoning', () => {+ expect(+ mapAiStepsToUiMessageParts([+ buildStep([+ { type: 'text', text: '' },+ { type: 'reasoning', text: '' },+ ]),+ ]),+ ).toEqual([{ type: 'step-start' }]);+ });+});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.tsnew file mode 100644index 00000000000..ef4913eb864--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util.ts@@ -0,0 +1,74 @@+import { type StepResult, type ToolSet } from 'ai';+import { type ExtendedUIMessagePart } from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';++// An agent run outside chat keeps no stream to persist, only the SDK's step+// results. Rebuilding the parts a chat stream would have produced lets that+// run be stored and read back as an ordinary conversation.+export const mapAiStepsToUiMessageParts = (+ steps: Pick<StepResult<ToolSet>, 'content'>[],+): ExtendedUIMessagePart[] => {+ const parts: ExtendedUIMessagePart[] = [];+ const toolPartIndexByCallId = new Map<string, number>();++ for (const step of steps) {+ parts.push({ type: 'step-start' });++ for (const part of step.content) {+ switch (part.type) {+ case 'text':+ if (part.text.length > 0) {+ parts.push({ type: 'text', text: part.text });+ }+ break;+ case 'reasoning':+ if (part.text.length > 0) {+ parts.push({+ type: 'reasoning',+ text: part.text,+ providerMetadata: part.providerMetadata,+ });+ }+ break;+ case 'tool-call':+ toolPartIndexByCallId.set(part.toolCallId, parts.length);+ parts.push({+ type: `tool-${part.toolName}`,+ toolCallId: part.toolCallId,+ state: 'input-available',+ input: part.input,+ providerExecuted: part.providerExecuted,+ } as ExtendedUIMessagePart);+ break;+ case 'tool-result': {+ const index = toolPartIndexByCallId.get(part.toolCallId);++ if (isDefined(index)) {+ parts[index] = {+ ...parts[index],+ state: 'output-available',+ output: part.output,+ } as ExtendedUIMessagePart;+ }+ break;+ }+ case 'tool-error': {+ const index = toolPartIndexByCallId.get(part.toolCallId);++ if (isDefined(index)) {+ parts[index] = {+ ...parts[index],+ state: 'output-error',+ errorText: String(part.error),+ } as ExtendedUIMessagePart;+ }+ break;+ }+ default:+ break;+ }+ }+ }++ return parts;+};diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.tsindex 2a8a68901a3..6967f602ded 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/__tests__/agent-chat-sharing.service.spec.ts@@ -18,7 +18,10 @@ const args = {const buildService = (legacyOwnerFieldPresent = true) => {const query = jest.fn().mockResolvedValue([{ id: THREAD_ID }]);- const thread = { id: THREAD_ID, workspaceMemberId: 'owner' };+ const thread: Record<string, unknown> = {+ id: THREAD_ID,+ workspaceMemberId: 'owner',+ };const threadRepository = {query: jest.fn()@@ -58,19 +61,20 @@ const buildService = (legacyOwnerFieldPresent = true) => {id: 'object',readability: MetadataReadability.PRIVATE,};+ const flatFieldMetadataMaps = {+ byUniversalIdentifier: (legacyOwnerFieldPresent+ ? { 'bf830886-b6dc-46e9-a229-eecbb0e66032': { id: 'legacy' } }+ : {}) as Record<string, unknown>,+ };const cache = {getOrRecompute: jest.fn().mockResolvedValue({- flatFieldMetadataMaps: {- byUniversalIdentifier: legacyOwnerFieldPresent- ? { 'bf830886-b6dc-46e9-a229-eecbb0e66032': { id: 'legacy' } }- : {},- },flatObjectMetadataMaps: {byUniversalIdentifier: {[STANDARD_OBJECTS.agentChatThread.universalIdentifier]:objectMetadata,},},+ flatFieldMetadataMaps,}),};const aiPermissions = {@@ -100,6 +104,8 @@ const buildService = (legacyOwnerFieldPresent = true) => {return {query,service,+ thread,+ flatFieldMetadataMaps,threadRepository,userAuthContextService,repository,@@ -276,4 +282,33 @@ describe('Conversation common record access', () => {await service.getPermissionsForThreads({ ...args, threadIds: [THREAD_ID] });expect(sharing.getPermissionsForRecords).toHaveBeenCalledTimes(1);});++ it.each(['update', 'delete', 'soft-delete', 'restore'] as const)(+ 'refuses %s on a workflow run conversation while still letting its readers read it',+ async (operation) => {+ const { service, thread } = buildService();+ thread.workflowRunId = 'workflow-run';+ await expect(service.getReadableThread(args)).resolves.toBeDefined();+ await expect(+ service.getThreadWithAccess({ ...args, operationType: operation }),+ ).rejects.toMatchObject({ code: 'WORKFLOW_RUN_THREAD_READ_ONLY' });+ },+ );++ it('leaves workflow run conversations out of the chat list once threads can name a run', async () => {+ const { service, repository, flatFieldMetadataMaps } = buildService();+ await service.getReadableThreadIds(args);+ expect(repository.find).toHaveBeenLastCalledWith(+ expect.objectContaining({ where: undefined }),+ );+ flatFieldMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier+ ] = {};+ await service.getReadableThreadIds(args);+ expect(repository.find).toHaveBeenLastCalledWith(+ expect.objectContaining({+ where: { workflowRunId: expect.objectContaining({ _type: 'isNull' }) },+ }),+ );+ });});diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.tsindex 09afc10eb50..7ba2830fafe 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/services/agent-chat-sharing.service.ts@@ -1,5 +1,6 @@import { hasLegacyChatThreadOwnerField } from 'src/engine/metadata-modules/ai/ai-chat/utils/has-legacy-chat-thread-owner-field.util';import { lockAgentChatThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/lock-agent-chat-thread.util';+import { IsNull } from 'typeorm';import { type AgentHistoryStorageContext } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-workspace-storage.service';import { escapeIdentifier } from 'src/engine/workspace-manager/workspace-migration/utils/remove-sql-injection.util';import { AuthException } from 'src/engine/core-modules/auth/auth.exception';@@ -17,6 +18,8 @@ import { type RecordPermissionsDTO } from 'src/engine/core-modules/record-share/import { UserWorkspaceAuthContextService } from 'src/engine/core-modules/user-workspace/services/user-workspace-auth-context.service';import { AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';+import { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';+import { isWorkflowRunThread } from 'src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util';import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';import {AiException,@@ -67,6 +70,11 @@ export class AgentChatSharingService {if (!isDefined(thread)) {return this.throwNotFound();}+ // A run's conversation is the record of what its agent step did, and it is+ // readable by whoever reads the run, so nobody may add to or edit it.+ if (operationType !== 'select') {+ this.assertNotWorkflowRunThread(thread);+ }const allowedIds = await this.workspaceOrmManager.executeInWorkspaceContext(() =>this.workspaceOrmManager@@ -110,10 +118,20 @@ export class AgentChatSharingService {args: Omit<ThreadAccessArgs, 'threadId'>,): Promise<string[]> {const authContext = await this.getAuthContext(args);+ const { flatFieldMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(args.workspaceId, [+ 'flatFieldMetadataMaps',+ ]);+return this.workspaceOrmManager.executeInWorkspaceContext(async () => {const records = await this.workspaceOrmManager.getRepositoryWithContextPermissions('agentChatThread').find({+ // Anyone who reads a run reads its agent's conversations, so without+ // this every run would crowd into every member's own chats.+ where: hasWorkflowRunThreadFields(flatFieldMetadataMaps)+ ? { workflowRunId: IsNull() }+ : undefined,select: { id: true },withDeleted: false,order: { updatedAt: 'DESC', id: 'DESC' },@@ -267,6 +285,7 @@ export class AgentChatSharingService {objectMetadataId: objectMetadata.id,threadId: args.threadId,});+ this.assertNotWorkflowRunThread(thread);const allowedIds = await this.workspaceOrmManager.getRepositoryWithContextPermissions('agentChatThread')@@ -286,6 +305,17 @@ export class AgentChatSharingService {);}+ private assertNotWorkflowRunThread(+ thread: AgentChatThreadWorkspaceEntity,+ ): void {+ if (isWorkflowRunThread(thread)) {+ throw new AiException(+ 'A workflow run conversation is read-only',+ AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY,+ );+ }+ }+async getAuthContext(args: Omit<ThreadAccessArgs, 'threadId'>) {const authContext = await this.userAuthContextService.resolveWorkspaceMember(args)diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.tsnew file mode 100644index 00000000000..5497e6dfe0d--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-chat/utils/is-workflow-run-thread.util.ts@@ -0,0 +1,6 @@+import { isDefined } from 'twenty-shared/utils';++// Agent history records carry every workspace column, including the run link+// the legacy thread entity type does not declare.+export const isWorkflowRunThread = (thread: object): boolean =>+ 'workflowRunId' in thread && isDefined(thread.workflowRunId);diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.tsindex 5ce5fa9fe73..87c6b5dcfd3 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity.ts@@ -6,6 +6,7 @@ import { type AgentChatThreadTargetWorkspaceEntity } from 'src/engine/metadata-mimport { BaseWorkspaceEntity } from 'src/engine/twenty-orm/base.workspace-entity';import { type AgentChatThreadLastStreamError } from 'src/engine/metadata-modules/ai/ai-chat/types/agent-chat-thread-last-stream-error.type';import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';+import { type WorkflowRunWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {messages: EntityRelation<AgentMessageWorkspaceEntity[]>;@@ -13,11 +14,14 @@ export class AgentChatThreadWorkspaceEntity extends BaseWorkspaceEntity {attachments: EntityRelation<AttachmentWorkspaceEntity[]>;workspaceMember: EntityRelation<WorkspaceMemberWorkspaceEntity> | null;recordTargets: EntityRelation<AgentChatThreadTargetWorkspaceEntity[]>;+ workflowRun: EntityRelation<WorkflowRunWorkspaceEntity> | null;archivedAt: string | null;- userWorkspaceId: string;+ userWorkspaceId: string | null;workspaceMemberId: string | null;+ workflowRunId: string | null;+ workflowStepId: string | null;title: string | null;totalInputTokens: number;totalOutputTokens: number;diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util.tsnew file mode 100644index 00000000000..8b759aa160c--- /dev/null+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util.ts@@ -0,0 +1,18 @@+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { isDefined } from 'twenty-shared/utils';++import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';++// Fence for the 2.44 cross-upgrade window: until+// upgrade:2-44:add-workflow-run-to-chat-threads has reached a workspace, its+// threads have no column to name a workflow run, so no run conversation can be+// written and none has to be filtered out. Remove once 2.44 leaves the window.+export const hasWorkflowRunThreadFields = (+ flatFieldMetadataMaps: FlatEntityMaps<FlatFieldMetadata>,+): boolean =>+ isDefined(+ flatFieldMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier+ ],+ );diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.tsindex a07ab5b4a12..a371cc51420 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai.exception.ts@@ -30,6 +30,7 @@ export enum AiExceptionCode {EVALUATION_MODEL_NOT_FOUND = 'EVALUATION_MODEL_NOT_FOUND',EVALUATION_QUESTION_UNSUPPORTED = 'EVALUATION_QUESTION_UNSUPPORTED',INVALID_EVALUATION_REQUEST = 'INVALID_EVALUATION_REQUEST',+ WORKFLOW_RUN_THREAD_READ_ONLY = 'WORKFLOW_RUN_THREAD_READ_ONLY',}const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {@@ -84,6 +85,8 @@ const getAiExceptionUserFriendlyMessage = (code: AiExceptionCode) => {return msg`This model cannot answer one of the questions asked.`;case AiExceptionCode.INVALID_EVALUATION_REQUEST:return msg`Invalid classification request.`;+ case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:+ return msg`This conversation belongs to a workflow run and can only be read.`;default:assertUnreachable(code);}diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.tsindex 16521f86be1..6d35fc01f01 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/filters/ai-api-exception.filter.ts@@ -40,6 +40,12 @@ export class AiRestApiExceptionFilter implements ExceptionFilter {response,503, // Service Unavailable - the AI service is not configured);+ case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:+ return this.httpExceptionHandlerService.handleError(+ exception,+ response,+ 403,+ );case AiExceptionCode.AGENT_EXECUTION_FAILED:case AiExceptionCode.ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS:case AiExceptionCode.INVALID_AGENT_INPUT:diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.tsindex fa6bfdba74f..3243634d1d5 100644--- a/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts+++ b/packages/twenty-server/src/engine/metadata-modules/ai/utils/ai-graphql-api-exception-handler.util.ts@@ -39,6 +39,7 @@ export const aiGraphqlApiExceptionHandler = (error: Error) => {case AiExceptionCode.ROLE_CANNOT_BE_ASSIGNED_TO_AGENTS:case AiExceptionCode.RUN_AS_WORKSPACE_MEMBER_NOT_ALLOWED:case AiExceptionCode.RUN_AGENT_NOT_ALLOWED:+ case AiExceptionCode.WORKFLOW_RUN_THREAD_READ_ONLY:throw new ForbiddenError(error);case AiExceptionCode.AGENT_EXECUTION_FAILED:case AiExceptionCode.API_KEY_NOT_CONFIGURED:diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snapindex 823d0867ec1..d6d26252238 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/__snapshots__/get-standard-object-metadata-related-entity-ids.util.spec.ts.snap@@ -5,301 +5,307 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"agentChatThread": {"fields": {"activeStreamId": {- "id": "00000000-0000-0000-0000-000000001017",+ "id": "00000000-0000-0000-0000-000000001018",},"archivedAt": {- "id": "00000000-0000-0000-0000-000000001005",+ "id": "00000000-0000-0000-0000-000000001006",},"attachments": {- "id": "00000000-0000-0000-0000-000000001022",+ "id": "00000000-0000-0000-0000-000000001025",},"contextWindowTokens": {- "id": "00000000-0000-0000-0000-000000001011",+ "id": "00000000-0000-0000-0000-000000001012",},"conversationSize": {- "id": "00000000-0000-0000-0000-000000001012",+ "id": "00000000-0000-0000-0000-000000001013",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001002",+ "id": "00000000-0000-0000-0000-000000001003",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001004",+ "id": "00000000-0000-0000-0000-000000001005",},"id": {- "id": "00000000-0000-0000-0000-000000001001",+ "id": "00000000-0000-0000-0000-000000001002",},"lastStreamError": {- "id": "00000000-0000-0000-0000-000000001019",+ "id": "00000000-0000-0000-0000-000000001022",},"messages": {- "id": "00000000-0000-0000-0000-000000001021",+ "id": "00000000-0000-0000-0000-000000001024",},"pendingQuestionMessageId": {- "id": "00000000-0000-0000-0000-000000001018",+ "id": "00000000-0000-0000-0000-000000001021",},"recordTargets": {- "id": "00000000-0000-0000-0000-000000001023",+ "id": "00000000-0000-0000-0000-000000001026",},"title": {- "id": "00000000-0000-0000-0000-000000001008",+ "id": "00000000-0000-0000-0000-000000001009",},"totalCacheCreationTokens": {- "id": "00000000-0000-0000-0000-000000001016",+ "id": "00000000-0000-0000-0000-000000001017",},"totalCacheReadTokens": {- "id": "00000000-0000-0000-0000-000000001015",+ "id": "00000000-0000-0000-0000-000000001016",},"totalInputCredits": {- "id": "00000000-0000-0000-0000-000000001013",+ "id": "00000000-0000-0000-0000-000000001014",},"totalInputTokens": {- "id": "00000000-0000-0000-0000-000000001009",+ "id": "00000000-0000-0000-0000-000000001010",},"totalOutputCredits": {- "id": "00000000-0000-0000-0000-000000001014",+ "id": "00000000-0000-0000-0000-000000001015",},"totalOutputTokens": {- "id": "00000000-0000-0000-0000-000000001010",+ "id": "00000000-0000-0000-0000-000000001011",},"turns": {- "id": "00000000-0000-0000-0000-000000001020",+ "id": "00000000-0000-0000-0000-000000001023",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001003",+ "id": "00000000-0000-0000-0000-000000001004",},"userWorkspaceId": {- "id": "00000000-0000-0000-0000-000000001006",+ "id": "00000000-0000-0000-0000-000000001007",+ },+ "workflowRun": {+ "id": "00000000-0000-0000-0000-000000001019",+ },+ "workflowStepId": {+ "id": "00000000-0000-0000-0000-000000001020",},"workspaceMember": {- "id": "00000000-0000-0000-0000-000000001007",+ "id": "00000000-0000-0000-0000-000000001008",},},- "id": "00000000-0000-0000-0000-000000001024",+ "id": "00000000-0000-0000-0000-000000001027","views": undefined,},"agentChatThreadTarget": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001026",+ "id": "00000000-0000-0000-0000-000000001029",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001028",+ "id": "00000000-0000-0000-0000-000000001031",},"id": {- "id": "00000000-0000-0000-0000-000000001025",+ "id": "00000000-0000-0000-0000-000000001028",},"targetCompany": {- "id": "00000000-0000-0000-0000-000000001031",+ "id": "00000000-0000-0000-0000-000000001034",},"targetOpportunity": {- "id": "00000000-0000-0000-0000-000000001032",+ "id": "00000000-0000-0000-0000-000000001035",},"targetPerson": {- "id": "00000000-0000-0000-0000-000000001030",+ "id": "00000000-0000-0000-0000-000000001033",},"thread": {- "id": "00000000-0000-0000-0000-000000001029",+ "id": "00000000-0000-0000-0000-000000001032",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001027",+ "id": "00000000-0000-0000-0000-000000001030",},},- "id": "00000000-0000-0000-0000-000000001033",+ "id": "00000000-0000-0000-0000-000000001036","views": {},},"agentMessage": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001047",+ "id": "00000000-0000-0000-0000-000000001050",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001044",+ "id": "00000000-0000-0000-0000-000000001047",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001046",+ "id": "00000000-0000-0000-0000-000000001049",},"id": {- "id": "00000000-0000-0000-0000-000000001043",+ "id": "00000000-0000-0000-0000-000000001046",},"isHidden": {- "id": "00000000-0000-0000-0000-000000001053",+ "id": "00000000-0000-0000-0000-000000001056",},"parts": {- "id": "00000000-0000-0000-0000-000000001057",+ "id": "00000000-0000-0000-0000-000000001060",},"processedAt": {- "id": "00000000-0000-0000-0000-000000001054",+ "id": "00000000-0000-0000-0000-000000001057",},"role": {- "id": "00000000-0000-0000-0000-000000001051",+ "id": "00000000-0000-0000-0000-000000001054",},"senderApplicationId": {- "id": "00000000-0000-0000-0000-000000001050",+ "id": "00000000-0000-0000-0000-000000001053",},"senderUserWorkspaceId": {- "id": "00000000-0000-0000-0000-000000001049",+ "id": "00000000-0000-0000-0000-000000001052",},"senderWorkspaceMember": {- "id": "00000000-0000-0000-0000-000000001048",+ "id": "00000000-0000-0000-0000-000000001051",},"status": {- "id": "00000000-0000-0000-0000-000000001052",+ "id": "00000000-0000-0000-0000-000000001055",},"thread": {- "id": "00000000-0000-0000-0000-000000001055",+ "id": "00000000-0000-0000-0000-000000001058",},"turn": {- "id": "00000000-0000-0000-0000-000000001056",+ "id": "00000000-0000-0000-0000-000000001059",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001045",+ "id": "00000000-0000-0000-0000-000000001048",},},- "id": "00000000-0000-0000-0000-000000001058",+ "id": "00000000-0000-0000-0000-000000001061","views": undefined,},"agentMessagePart": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001060",+ "id": "00000000-0000-0000-0000-000000001063",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001062",+ "id": "00000000-0000-0000-0000-000000001065",},"errorDetails": {- "id": "00000000-0000-0000-0000-000000001074",+ "id": "00000000-0000-0000-0000-000000001077",},"errorMessage": {- "id": "00000000-0000-0000-0000-000000001073",+ "id": "00000000-0000-0000-0000-000000001076",},"fileFilename": {- "id": "00000000-0000-0000-0000-000000001082",+ "id": "00000000-0000-0000-0000-000000001085",},"fileId": {- "id": "00000000-0000-0000-0000-000000001083",+ "id": "00000000-0000-0000-0000-000000001086",},"id": {- "id": "00000000-0000-0000-0000-000000001059",+ "id": "00000000-0000-0000-0000-000000001062",},"message": {- "id": "00000000-0000-0000-0000-000000001085",+ "id": "00000000-0000-0000-0000-000000001088",},"orderIndex": {- "id": "00000000-0000-0000-0000-000000001063",+ "id": "00000000-0000-0000-0000-000000001066",},"providerExecuted": {- "id": "00000000-0000-0000-0000-000000001072",+ "id": "00000000-0000-0000-0000-000000001075",},"providerMetadata": {- "id": "00000000-0000-0000-0000-000000001084",+ "id": "00000000-0000-0000-0000-000000001087",},"reasoningContent": {- "id": "00000000-0000-0000-0000-000000001066",+ "id": "00000000-0000-0000-0000-000000001069",},"sourceDocumentFilename": {- "id": "00000000-0000-0000-0000-000000001081",+ "id": "00000000-0000-0000-0000-000000001084",},"sourceDocumentMediaType": {- "id": "00000000-0000-0000-0000-000000001079",+ "id": "00000000-0000-0000-0000-000000001082",},"sourceDocumentSourceId": {- "id": "00000000-0000-0000-0000-000000001078",+ "id": "00000000-0000-0000-0000-000000001081",},"sourceDocumentTitle": {- "id": "00000000-0000-0000-0000-000000001080",+ "id": "00000000-0000-0000-0000-000000001083",},"sourceUrlSourceId": {- "id": "00000000-0000-0000-0000-000000001075",+ "id": "00000000-0000-0000-0000-000000001078",},"sourceUrlTitle": {- "id": "00000000-0000-0000-0000-000000001077",+ "id": "00000000-0000-0000-0000-000000001080",},"sourceUrlUrl": {- "id": "00000000-0000-0000-0000-000000001076",+ "id": "00000000-0000-0000-0000-000000001079",},"state": {- "id": "00000000-0000-0000-0000-000000001071",+ "id": "00000000-0000-0000-0000-000000001074",},"textContent": {- "id": "00000000-0000-0000-0000-000000001065",+ "id": "00000000-0000-0000-0000-000000001068",},"toolCallId": {- "id": "00000000-0000-0000-0000-000000001068",+ "id": "00000000-0000-0000-0000-000000001071",},"toolInput": {- "id": "00000000-0000-0000-0000-000000001069",+ "id": "00000000-0000-0000-0000-000000001072",},"toolName": {- "id": "00000000-0000-0000-0000-000000001067",+ "id": "00000000-0000-0000-0000-000000001070",},"toolOutput": {- "id": "00000000-0000-0000-0000-000000001070",+ "id": "00000000-0000-0000-0000-000000001073",},"type": {- "id": "00000000-0000-0000-0000-000000001064",+ "id": "00000000-0000-0000-0000-000000001067",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001061",+ "id": "00000000-0000-0000-0000-000000001064",},},- "id": "00000000-0000-0000-0000-000000001086",+ "id": "00000000-0000-0000-0000-000000001089","views": undefined,},"agentTurn": {"fields": {"agentId": {- "id": "00000000-0000-0000-0000-000000001038",+ "id": "00000000-0000-0000-0000-000000001041",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001035",+ "id": "00000000-0000-0000-0000-000000001038",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001037",+ "id": "00000000-0000-0000-0000-000000001040",},"evaluations": {- "id": "00000000-0000-0000-0000-000000001041",+ "id": "00000000-0000-0000-0000-000000001044",},"id": {- "id": "00000000-0000-0000-0000-000000001034",+ "id": "00000000-0000-0000-0000-000000001037",},"messages": {- "id": "00000000-0000-0000-0000-000000001040",+ "id": "00000000-0000-0000-0000-000000001043",},"thread": {- "id": "00000000-0000-0000-0000-000000001039",+ "id": "00000000-0000-0000-0000-000000001042",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001036",+ "id": "00000000-0000-0000-0000-000000001039",},},- "id": "00000000-0000-0000-0000-000000001042",+ "id": "00000000-0000-0000-0000-000000001045","views": undefined,},"agentTurnEvaluation": {"fields": {"comment": {- "id": "00000000-0000-0000-0000-000000001092",+ "id": "00000000-0000-0000-0000-000000001095",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001088",+ "id": "00000000-0000-0000-0000-000000001091",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001090",+ "id": "00000000-0000-0000-0000-000000001093",},"id": {- "id": "00000000-0000-0000-0000-000000001087",+ "id": "00000000-0000-0000-0000-000000001090",},"score": {- "id": "00000000-0000-0000-0000-000000001091",+ "id": "00000000-0000-0000-0000-000000001094",},"turn": {- "id": "00000000-0000-0000-0000-000000001093",+ "id": "00000000-0000-0000-0000-000000001096",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001089",+ "id": "00000000-0000-0000-0000-000000001092",},},- "id": "00000000-0000-0000-0000-000000001094",+ "id": "00000000-0000-0000-0000-000000001097","views": undefined,},"attachment": {@@ -1057,64 +1063,64 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"campaignDelivery": {"fields": {"bouncedAt": {- "id": "00000000-0000-0000-0000-000000001110",+ "id": "00000000-0000-0000-0000-000000001113",},"campaignId": {- "id": "00000000-0000-0000-0000-000000001099",+ "id": "00000000-0000-0000-0000-000000001102",},"claimExpiresAt": {- "id": "00000000-0000-0000-0000-000000001106",+ "id": "00000000-0000-0000-0000-000000001109",},"claimToken": {- "id": "00000000-0000-0000-0000-000000001105",+ "id": "00000000-0000-0000-0000-000000001108",},"complainedAt": {- "id": "00000000-0000-0000-0000-000000001111",+ "id": "00000000-0000-0000-0000-000000001114",},"createdAt": {- "id": "00000000-0000-0000-0000-000000001096",+ "id": "00000000-0000-0000-0000-000000001099",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001098",+ "id": "00000000-0000-0000-0000-000000001101",},"deliveredAt": {- "id": "00000000-0000-0000-0000-000000001109",+ "id": "00000000-0000-0000-0000-000000001112",},"failureReason": {- "id": "00000000-0000-0000-0000-000000001104",+ "id": "00000000-0000-0000-0000-000000001107",},"id": {- "id": "00000000-0000-0000-0000-000000001095",+ "id": "00000000-0000-0000-0000-000000001098",},"personId": {- "id": "00000000-0000-0000-0000-000000001100",+ "id": "00000000-0000-0000-0000-000000001103",},"providerMessageId": {- "id": "00000000-0000-0000-0000-000000001107",+ "id": "00000000-0000-0000-0000-000000001110",},"recipientEmail": {- "id": "00000000-0000-0000-0000-000000001101",+ "id": "00000000-0000-0000-0000-000000001104",},"rejectedAt": {- "id": "00000000-0000-0000-0000-000000001112",+ "id": "00000000-0000-0000-0000-000000001115",},"renderingFailedAt": {- "id": "00000000-0000-0000-0000-000000001113",+ "id": "00000000-0000-0000-0000-000000001116",},"sentAt": {- "id": "00000000-0000-0000-0000-000000001108",+ "id": "00000000-0000-0000-0000-000000001111",},"skipReason": {- "id": "00000000-0000-0000-0000-000000001103",+ "id": "00000000-0000-0000-0000-000000001106",},"state": {- "id": "00000000-0000-0000-0000-000000001102",+ "id": "00000000-0000-0000-0000-000000001105",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001097",+ "id": "00000000-0000-0000-0000-000000001100",},},- "id": "00000000-0000-0000-0000-000000001114",+ "id": "00000000-0000-0000-0000-000000001117","views": undefined,},"company": {@@ -2071,34 +2077,34 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"messageSuppression": {"fields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000001116",+ "id": "00000000-0000-0000-0000-000000001119",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000001118",+ "id": "00000000-0000-0000-0000-000000001121",},"emailAddress": {- "id": "00000000-0000-0000-0000-000000001119",+ "id": "00000000-0000-0000-0000-000000001122",},"id": {- "id": "00000000-0000-0000-0000-000000001115",+ "id": "00000000-0000-0000-0000-000000001118",},"providerEventId": {- "id": "00000000-0000-0000-0000-000000001122",+ "id": "00000000-0000-0000-0000-000000001125",},"reason": {- "id": "00000000-0000-0000-0000-000000001120",+ "id": "00000000-0000-0000-0000-000000001123",},"source": {- "id": "00000000-0000-0000-0000-000000001121",+ "id": "00000000-0000-0000-0000-000000001124",},"unsubscribeTopicId": {- "id": "00000000-0000-0000-0000-000000001123",+ "id": "00000000-0000-0000-0000-000000001126",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000001117",+ "id": "00000000-0000-0000-0000-000000001120",},},- "id": "00000000-0000-0000-0000-000000001124",+ "id": "00000000-0000-0000-0000-000000001127","views": undefined,},"messageThread": {@@ -3373,6 +3379,9 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object},"workflowRun": {"fields": {+ "agentChatThreads": {+ "id": "00000000-0000-0000-0000-000000000907",+ },"coreWorkflowId": {"id": "00000000-0000-0000-0000-000000000905",},@@ -3419,7 +3428,7 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000000904",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000907",+ "id": "00000000-0000-0000-0000-000000000908",},"updatedAt": {"id": "00000000-0000-0000-0000-000000000890",@@ -3434,70 +3443,70 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"id": "00000000-0000-0000-0000-000000000897",},},- "id": "00000000-0000-0000-0000-000000000927",+ "id": "00000000-0000-0000-0000-000000000928","views": {"allWorkflowRuns": {- "id": "00000000-0000-0000-0000-000000000911",+ "id": "00000000-0000-0000-0000-000000000912","viewFieldGroups": {},"viewFields": {"name": {- "id": "00000000-0000-0000-0000-000000000908",+ "id": "00000000-0000-0000-0000-000000000909",},"status": {- "id": "00000000-0000-0000-0000-000000000910",+ "id": "00000000-0000-0000-0000-000000000911",},"workflow": {- "id": "00000000-0000-0000-0000-000000000909",+ "id": "00000000-0000-0000-0000-000000000910",},},"viewGroups": {},},"workflowRunRecordPageFields": {- "id": "00000000-0000-0000-0000-000000000926",+ "id": "00000000-0000-0000-0000-000000000927","viewFieldGroups": {"general": {- "id": "00000000-0000-0000-0000-000000000924",+ "id": "00000000-0000-0000-0000-000000000925",},"system": {- "id": "00000000-0000-0000-0000-000000000925",+ "id": "00000000-0000-0000-0000-000000000926",},},"viewFields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000000917",+ "id": "00000000-0000-0000-0000-000000000918",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000918",+ "id": "00000000-0000-0000-0000-000000000919",},"endedAt": {- "id": "00000000-0000-0000-0000-000000000916",+ "id": "00000000-0000-0000-0000-000000000917",},"enqueuedAt": {- "id": "00000000-0000-0000-0000-000000000919",+ "id": "00000000-0000-0000-0000-000000000920",},"startedAt": {- "id": "00000000-0000-0000-0000-000000000915",+ "id": "00000000-0000-0000-0000-000000000916",},"state": {- "id": "00000000-0000-0000-0000-000000000920",+ "id": "00000000-0000-0000-0000-000000000921",},"status": {- "id": "00000000-0000-0000-0000-000000000912",+ "id": "00000000-0000-0000-0000-000000000913",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000923",+ "id": "00000000-0000-0000-0000-000000000924",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000921",+ "id": "00000000-0000-0000-0000-000000000922",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000922",+ "id": "00000000-0000-0000-0000-000000000923",},"workflow": {- "id": "00000000-0000-0000-0000-000000000913",+ "id": "00000000-0000-0000-0000-000000000914",},"workflowVersion": {- "id": "00000000-0000-0000-0000-000000000914",+ "id": "00000000-0000-0000-0000-000000000915",},},"viewGroups": {},@@ -3507,118 +3516,118 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"workflowVersion": {"fields": {"coreWorkflowVersionId": {- "id": "00000000-0000-0000-0000-000000000942",+ "id": "00000000-0000-0000-0000-000000000943",},"createdAt": {- "id": "00000000-0000-0000-0000-000000000929",+ "id": "00000000-0000-0000-0000-000000000930",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000932",+ "id": "00000000-0000-0000-0000-000000000933",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000000931",+ "id": "00000000-0000-0000-0000-000000000932",},"id": {- "id": "00000000-0000-0000-0000-000000000928",+ "id": "00000000-0000-0000-0000-000000000929",},"name": {- "id": "00000000-0000-0000-0000-000000000936",+ "id": "00000000-0000-0000-0000-000000000937",},"position": {- "id": "00000000-0000-0000-0000-000000000934",+ "id": "00000000-0000-0000-0000-000000000935",},"runs": {- "id": "00000000-0000-0000-0000-000000000940",+ "id": "00000000-0000-0000-0000-000000000941",},"searchVector": {- "id": "00000000-0000-0000-0000-000000000935",+ "id": "00000000-0000-0000-0000-000000000936",},"status": {- "id": "00000000-0000-0000-0000-000000000939",+ "id": "00000000-0000-0000-0000-000000000940",},"steps": {- "id": "00000000-0000-0000-0000-000000000941",+ "id": "00000000-0000-0000-0000-000000000942",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000943",+ "id": "00000000-0000-0000-0000-000000000944",},"trigger": {- "id": "00000000-0000-0000-0000-000000000938",+ "id": "00000000-0000-0000-0000-000000000939",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000930",+ "id": "00000000-0000-0000-0000-000000000931",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000933",+ "id": "00000000-0000-0000-0000-000000000934",},"workflow": {- "id": "00000000-0000-0000-0000-000000000937",+ "id": "00000000-0000-0000-0000-000000000938",},},- "id": "00000000-0000-0000-0000-000000000963",+ "id": "00000000-0000-0000-0000-000000000964","views": {"allWorkflowVersions": {- "id": "00000000-0000-0000-0000-000000000949",+ "id": "00000000-0000-0000-0000-000000000950","viewFieldGroups": {},"viewFields": {"name": {- "id": "00000000-0000-0000-0000-000000000944",+ "id": "00000000-0000-0000-0000-000000000945",},"runs": {- "id": "00000000-0000-0000-0000-000000000948",+ "id": "00000000-0000-0000-0000-000000000949",},"status": {- "id": "00000000-0000-0000-0000-000000000946",+ "id": "00000000-0000-0000-0000-000000000947",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000947",+ "id": "00000000-0000-0000-0000-000000000948",},"workflow": {- "id": "00000000-0000-0000-0000-000000000945",+ "id": "00000000-0000-0000-0000-000000000946",},},"viewGroups": {},},"workflowVersionRecordPageFields": {- "id": "00000000-0000-0000-0000-000000000962",+ "id": "00000000-0000-0000-0000-000000000963","viewFieldGroups": {"general": {- "id": "00000000-0000-0000-0000-000000000960",+ "id": "00000000-0000-0000-0000-000000000961",},"system": {- "id": "00000000-0000-0000-0000-000000000961",+ "id": "00000000-0000-0000-0000-000000000962",},},"viewFields": {"createdAt": {- "id": "00000000-0000-0000-0000-000000000953",+ "id": "00000000-0000-0000-0000-000000000954",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000955",+ "id": "00000000-0000-0000-0000-000000000956",},"runs": {- "id": "00000000-0000-0000-0000-000000000958",+ "id": "00000000-0000-0000-0000-000000000959",},"status": {- "id": "00000000-0000-0000-0000-000000000950",+ "id": "00000000-0000-0000-0000-000000000951",},"steps": {- "id": "00000000-0000-0000-0000-000000000954",+ "id": "00000000-0000-0000-0000-000000000955",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000959",+ "id": "00000000-0000-0000-0000-000000000960",},"trigger": {- "id": "00000000-0000-0000-0000-000000000952",+ "id": "00000000-0000-0000-0000-000000000953",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000956",+ "id": "00000000-0000-0000-0000-000000000957",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000957",+ "id": "00000000-0000-0000-0000-000000000958",},"workflow": {- "id": "00000000-0000-0000-0000-000000000951",+ "id": "00000000-0000-0000-0000-000000000952",},},"viewGroups": {},@@ -3628,116 +3637,116 @@ exports[`getStandardObjectMetadataRelatedEntityIds should return standard object"workspaceMember": {"fields": {"accountOwnerForCompanies": {- "id": "00000000-0000-0000-0000-000000000983",+ "id": "00000000-0000-0000-0000-000000000984",},"agentChatThreads": {- "id": "00000000-0000-0000-0000-000000000989",+ "id": "00000000-0000-0000-0000-000000000990",},"agentMessages": {- "id": "00000000-0000-0000-0000-000000000988",+ "id": "00000000-0000-0000-0000-000000000989",},"assignedTasks": {- "id": "00000000-0000-0000-0000-000000000981",+ "id": "00000000-0000-0000-0000-000000000982",},"avatarUrl": {- "id": "00000000-0000-0000-0000-000000000977",+ "id": "00000000-0000-0000-0000-000000000978",},"blocklist": {- "id": "00000000-0000-0000-0000-000000000985",+ "id": "00000000-0000-0000-0000-000000000986",},"calendarEventParticipants": {- "id": "00000000-0000-0000-0000-000000000986",+ "id": "00000000-0000-0000-0000-000000000987",},"calendarStartDay": {- "id": "00000000-0000-0000-0000-000000000993",+ "id": "00000000-0000-0000-0000-000000000994",},"colorScheme": {- "id": "00000000-0000-0000-0000-000000000973",+ "id": "00000000-0000-0000-0000-000000000974",},"createdAt": {- "id": "00000000-0000-0000-0000-000000000965",+ "id": "00000000-0000-0000-0000-000000000966",},"createdBy": {- "id": "00000000-0000-0000-0000-000000000968",+ "id": "00000000-0000-0000-0000-000000000969",},"dateFormat": {- "id": "00000000-0000-0000-0000-000000000991",+ "id": "00000000-0000-0000-0000-000000000992",},"deletedAt": {- "id": "00000000-0000-0000-0000-000000000967",+ "id": "00000000-0000-0000-0000-000000000968",},"id": {- "id": "00000000-0000-0000-0000-000000000964",+ "id": "00000000-0000-0000-0000-000000000965",},"jobTitle": {- "id": "00000000-0000-0000-0000-000000000979",+ "id": "00000000-0000-0000-0000-000000000980",},"locale": {- "id": "00000000-0000-0000-0000-000000000976",+ "id": "00000000-0000-0000-0000-000000000977",},"messageParticipants": {- "id": "00000000-0000-0000-0000-000000000984",+ "id": "00000000-0000-0000-0000-000000000985",},"name": {- "id": "00000000-0000-0000-0000-000000000972",+ "id": "00000000-0000-0000-0000-000000000973",},"numberFormat": {- "id": "00000000-0000-0000-0000-000000000994",+ "id": "00000000-0000-0000-0000-000000000995",},"openRecordIn": {- "id": "00000000-0000-0000-0000-000000000975",+ "id": "00000000-0000-0000-0000-000000000976",},"ownedOpportunities": {- "id": "00000000-0000-0000-0000-000000000982",+ "id": "00000000-0000-0000-0000-000000000983",},"position": {- "id": "00000000-0000-0000-0000-000000000970",+ "id": "00000000-0000-0000-0000-000000000971",},"searchVector": {- "id": "00000000-0000-0000-0000-000000000971",+ "id": "00000000-0000-0000-0000-000000000972",},"timeFormat": {- "id": "00000000-0000-0000-0000-000000000992",+ "id": "00000000-0000-0000-0000-000000000993",},"timeZone": {- "id": "00000000-0000-0000-0000-000000000990",+ "id": "00000000-0000-0000-0000-000000000991",},"timelineActivities": {- "id": "00000000-0000-0000-0000-000000000987",+ "id": "00000000-0000-0000-0000-000000000988",},"uiScale": {- "id": "00000000-0000-0000-0000-000000000974",+ "id": "00000000-0000-0000-0000-000000000975",},"updatedAt": {- "id": "00000000-0000-0000-0000-000000000966",+ "id": "00000000-0000-0000-0000-000000000967",},"updatedBy": {- "id": "00000000-0000-0000-0000-000000000969",+ "id": "00000000-0000-0000-0000-000000000970",},"userEmail": {- "id": "00000000-0000-0000-0000-000000000978",+ "id": "00000000-0000-0000-0000-000000000979",},"userId": {- "id": "00000000-0000-0000-0000-000000000980",+ "id": "00000000-0000-0000-0000-000000000981",},},- "id": "00000000-0000-0000-0000-000000001000",+ "id": "00000000-0000-0000-0000-000000001001","views": {"allWorkspaceMembers": {- "id": "00000000-0000-0000-0000-000000000999",+ "id": "00000000-0000-0000-0000-000000001000","viewFieldGroups": {},"viewFields": {"assignedTasks": {- "id": "00000000-0000-0000-0000-000000000998",+ "id": "00000000-0000-0000-0000-000000000999",},"createdAt": {- "id": "00000000-0000-0000-0000-000000000996",+ "id": "00000000-0000-0000-0000-000000000997",},"name": {- "id": "00000000-0000-0000-0000-000000000995",+ "id": "00000000-0000-0000-0000-000000000996",},"ownedOpportunities": {- "id": "00000000-0000-0000-0000-000000000997",+ "id": "00000000-0000-0000-0000-000000000998",},},"viewGroups": {},diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.tsindex 97f3907f423..b3332c6f733 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/compute-agent-history-standard-metadata.spec.ts@@ -98,7 +98,7 @@ describe('agent history workspace metadata', () => {>> = {agentChatThread: {- readability: MetadataReadability.PRIVATE,+ readability: MetadataReadability.INHERITED,writability: MetadataWritability.OPEN,},agentChatThreadTarget: {diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.tsindex 54bcc0b9dba..4d0739290fc 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/__tests__/standard-object-readability.spec.ts@@ -23,6 +23,7 @@ const INHERITED_STANDARD_OBJECT_PARENT_FIELDS = {messageThreadTarget: STANDARD_OBJECT_FIELDS.messageThreadTarget.messageThread,calendarEventTarget: STANDARD_OBJECT_FIELDS.calendarEventTarget.calendarEvent,agentChatThreadTarget: STANDARD_OBJECT_FIELDS.agentChatThreadTarget.thread,+ agentChatThread: STANDARD_OBJECT_FIELDS.agentChatThread.workflowRun,} as const;describe('Standard object readability', () => {@@ -63,7 +64,6 @@ describe('Standard object readability', () => {) as (keyof typeof INHERITED_STANDARD_OBJECT_PARENT_FIELDS)[];const nonOpenObjectUniversalIdentifiers: string[] = [- STANDARD_OBJECTS.agentChatThread.universalIdentifier,STANDARD_OBJECTS.agentMessage.universalIdentifier,STANDARD_OBJECTS.agentMessagePart.universalIdentifier,STANDARD_OBJECTS.agentTurn.universalIdentifier,@@ -170,10 +170,27 @@ describe('Standard object readability', () => {).toContainEqual({joinColumnName: 'targetAgentChatThreadId',parentNameSingular: 'agentChatThread',- parentReadability: MetadataReadability.PRIVATE,+ parentReadability: MetadataReadability.INHERITED,});});+ // A member's chat has no run, so it reads only through its own grants, as a+ // PRIVATE thread did; a run's conversation reads as its run does.+ it('resolves its workflow run as the only parent of an agentChatThread', () => {+ expect(+ resolveParents('agentChatThread').map((parent) =>+ parent.kind === 'column'+ ? {+ joinColumnName: parent.joinColumnName,+ parentNameSingular: parent.parentFlatObjectMetadata.nameSingular,+ }+ : parent.kind,+ ),+ ).toEqual([+ { joinColumnName: 'workflowRunId', parentNameSingular: 'workflowRun' },+ ]);+ });+it('resolves every target of a noteTarget as its parent, not the note', () => {const parents = resolveParents('noteTarget').map((parent) =>parent.kind === 'column'diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.tsindex e224504b330..15e548a4bb4 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-agent-chat-thread-standard-flat-field-metadata.util.ts@@ -64,7 +64,10 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (icon: 'IconId',isSystem: true,isUIEditable: false,- isNullable: false,+ // A workflow run's conversation has no owner: it is read through the+ // run. The column goes away with the owner contract step+ // (twentyhq/core-team-issues#2925).+ isNullable: true,},}),writability: MetadataWritability.SYSTEM,@@ -516,8 +519,9 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (),icon: 'IconUsers',isUIEditable: false,- // Becomes required with the owner contract step- // (twentyhq/core-team-issues#2925).+ // Stays optional for a workflow run's conversation, which is read+ // through its run rather than owned. Every other thread gets an owner+ // with the owner contract step (twentyhq/core-team-issues#2925).isNullable: true,targetObjectName: 'workspaceMember',targetFieldName: 'agentChatThreads',@@ -532,6 +536,62 @@ export const buildAgentChatThreadStandardFlatFieldMetadatas = (writability: MetadataWritability.SYSTEM,isAuditLogged: false,},+ workflowRun: {+ ...createStandardRelationFieldFlatMetadata({+ ...args,+ context: {+ fieldName: 'workflowRun',+ type: FieldMetadataType.RELATION,+ label: i18nLabel(+ msg({ message: 'Workflow Run', context: 'fieldMetadata.label' }),+ ),+ description: i18nLabel(+ msg({+ message: 'Workflow run whose agent step held this conversation',+ context: 'fieldMetadata.description',+ }),+ ),+ icon: 'IconHistoryToggle',+ isUIEditable: false,+ isNullable: true,+ targetObjectName: 'workflowRun',+ targetFieldName: 'agentChatThreads',+ morphId: null,+ settings: {+ relationType: RelationType.MANY_TO_ONE,+ onDelete: RelationOnDeleteAction.CASCADE,+ joinColumnName: 'workflowRunId',+ },+ },+ }),+ writability: MetadataWritability.SYSTEM,+ isAuditLogged: false,+ },+ workflowStepId: {+ ...createStandardFieldFlatMetadata({+ ...args,+ context: {+ fieldName: 'workflowStepId',+ type: FieldMetadataType.TEXT,+ label: i18nLabel(+ msg({ message: 'Workflow Step ID', context: 'fieldMetadata.label' }),+ ),+ description: i18nLabel(+ msg({+ message:+ 'Agent step of the workflow run that held this conversation',+ context: 'fieldMetadata.description',+ }),+ ),+ icon: 'IconId',+ isSystem: true,+ isUIEditable: false,+ isNullable: true,+ },+ }),+ writability: MetadataWritability.SYSTEM,+ isAuditLogged: false,+ },messages: {...createStandardRelationFieldFlatMetadata({...args,diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.tsindex 77aa217b3ab..7ce07eb0e2c 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/field-metadata/compute-workflow-run-standard-flat-field-metadata.util.ts@@ -599,6 +599,36 @@ export const buildWorkflowRunStandardFlatFieldMetadatas = ({twentyStandardApplicationId,now,}),+ agentChatThreads: createStandardRelationFieldFlatMetadata({+ objectName,+ workspaceId,+ context: {+ type: FieldMetadataType.RELATION,+ morphId: null,+ fieldName: 'agentChatThreads',+ label: i18nLabel(+ msg({ message: `Conversations`, context: 'fieldMetadata.label' }),+ ),+ description: i18nLabel(+ msg({+ message: `Conversations held by the run's agent steps`,+ context: 'fieldMetadata.description',+ }),+ ),+ icon: 'IconMessage',+ isNullable: true,+ isUIEditable: false,+ targetObjectName: 'agentChatThread',+ targetFieldName: 'workflowRun',+ settings: {+ relationType: RelationType.ONE_TO_MANY,+ },+ },+ standardObjectMetadataRelatedEntityIds,+ dependencyFlatEntityMaps,+ twentyStandardApplicationId,+ now,+ }),timelineActivities: createStandardRelationFieldFlatMetadata({objectName,workspaceId,diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.tsindex db5d5889d57..3618f882ed5 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-agent-chat-thread-standard-flat-index-metadata.util.ts@@ -25,4 +25,13 @@ export const buildAgentChatThreadStandardFlatIndexMetadatas = (indexWhereClause: null,},}),+ workflowRunIndex: createStandardIndexFlatMetadata({+ ...args,+ context: {+ indexName: 'workflowRunIndex',+ relatedFieldNames: ['workflowRun'],+ isUnique: false,+ indexWhereClause: null,+ },+ }),});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.tsindex 494bfee91d3..757bc9e962a 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/object-metadata/create-standard-flat-object-metadata.util.ts@@ -53,7 +53,11 @@ export const STANDARD_FLAT_OBJECT_METADATA_BUILDERS_BY_OBJECT_NAME = {isAuditLogged: false,isUIEditable: false,isUICreatable: false,- readability: MetadataReadability.PRIVATE,+ // A conversation outside a workflow run has no parent and is read only+ // through its own grants, as a PRIVATE record is. One held by a run's+ // agent step is read by whoever reads the run.+ readability: MetadataReadability.INHERITED,+ readabilityParentFieldMetadataNames: ['workflowRun'],writability: MetadataWritability.OPEN,labelIdentifierFieldMetadataName: 'id',},diff --git a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.tsindex aed4b44d99d..2784b9f1b11 100644--- a/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts+++ b/packages/twenty-server/src/modules/workflow/common/standard-objects/workflow-run.workspace-entity.ts@@ -1,3 +1,4 @@+import { type AgentChatThreadWorkspaceEntity } from 'src/engine/metadata-modules/ai/ai-history/standard-objects/agent-chat-thread.workspace-entity';import { registerEnumType } from '@nestjs/graphql';import { type ActorMetadata } from 'twenty-shared/types';@@ -71,5 +72,6 @@ export class WorkflowRunWorkspaceEntity extends BaseWorkspaceEntity {workflowId: string | null;coreWorkflowId: string | null;coreWorkflowVersionId: string | null;+ agentChatThreads: EntityRelation<AgentChatThreadWorkspaceEntity[]>;timelineActivities: EntityRelation<TimelineActivityWorkspaceEntity[]>;}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-infos-reset.util.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-infos-reset.util.spec.tsindex 8a27a5a6359..64e9e5c9101 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-infos-reset.util.spec.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/__tests__/build-step-infos-reset.util.spec.ts@@ -38,6 +38,20 @@ describe('buildStepInfosReset', () => {});});+ it('should move the conversation to history so the next iteration starts without it', () => {+ const result = buildStepInfosReset({+ stepIds: ['agentStep'],+ stepInfos: {+ agentStep: { status: StepStatus.SUCCESS, threadId: 'thread-1' },+ },+ });++ expect(result.agentStep).toHaveProperty('threadId', undefined);+ expect(result.agentStep.history).toEqual([+ expect.objectContaining({ threadId: 'thread-1' }),+ ]);+ });+it('should leave out steps that were not given', () => {const result = buildStepInfosReset({stepIds: ['step1'],diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.tsindex b5b3ba07cf0..9001c60be40 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/utils/build-step-infos-reset.util.ts@@ -20,12 +20,16 @@ export const buildStepInfosReset = ({status: StepStatus.NOT_STARTED,result: undefined,error: undefined,+ // Step infos are merged on write, so a value left out here would keep+ // pointing the next iteration at the previous one's conversation.+ threadId: undefined,history: [...(stepInfo.history ?? []),{result: stepInfo.result,error: stepInfo.error,status: stepInfo.status,+ threadId: stepInfo.threadId,},],};diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.tsindex 09406609418..05970a3e76e 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent-action.module.ts@@ -4,11 +4,14 @@ import { TypeOrmModule } from '@nestjs/typeorm';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';import { AiAgentExecutionModule } from 'src/engine/metadata-modules/ai/ai-agent-execution/ai-agent-execution.module';+import { AgentHistoryModule } from 'src/engine/metadata-modules/ai/ai-history/ai-history.module';import { AgentEntity } from 'src/engine/metadata-modules/ai/ai-agent/entities/agent.entity';import { RoleModule } from 'src/engine/metadata-modules/role/role.module';import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';import { UserRoleModule } from 'src/engine/metadata-modules/user-role/user-role.module';import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-executor/services/workflow-execution-context.service';+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';import { WorkflowRunModule } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.module';import { AiAgentWorkflowAction } from './ai-agent.workflow-action';@@ -22,9 +25,12 @@ import { AiAgentWorkflowAction } from './ai-agent.workflow-action';UserWorkspaceModule,UserRoleModule,RoleModule,+ AgentHistoryModule,+ WorkspaceCacheModule,],providers: [WorkflowExecutionContextService,+ WorkflowAgentConversationWorkspaceService,AiAgentWorkflowAction,provideWorkspaceScopedRepository(AgentEntity),],diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.tsindex 5a9ba526d02..5e2afd9d7bd 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/ai-agent.workflow-action.ts@@ -19,6 +19,7 @@ import { WorkflowExecutionContextService } from 'src/modules/workflow/workflow-eimport { type WorkflowActionInput } from 'src/modules/workflow/workflow-executor/types/workflow-action-input.type';import { type WorkflowActionOutput } from 'src/modules/workflow/workflow-executor/types/workflow-action-output.type';import { findStepOrThrow } from 'src/modules/workflow/workflow-executor/utils/find-step-or-throw.util';+import { WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';import { buildAiAgentStepLog } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/utils/build-ai-agent-step-log.util';import { WorkflowRunStepLogWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run-step-log.workspace-service';@@ -32,6 +33,7 @@ export class AiAgentWorkflowAction implements WorkflowAction {private readonly aiAgentExecutionService: AgentAsyncExecutorService,private readonly workflowExecutionContextService: WorkflowExecutionContextService,private readonly workflowRunStepLogService: WorkflowRunStepLogWorkspaceService,+ private readonly workflowAgentConversationService: WorkflowAgentConversationWorkspaceService,@InjectWorkspaceScopedRepository(AgentEntity)private readonly agentRepository: WorkspaceScopedRepository<AgentEntity>,) {}@@ -80,25 +82,43 @@ export class AiAgentWorkflowAction implements WorkflowAction {? executionContext.authContext.userWorkspaceId: null;+ const resolvedPrompt = resolveInput(prompt, context) as string;+ const recordConversation = (executionResult?: AgentExecutionResult) =>+ this.recordConversation({+ workspaceId,+ workflowRunId: runInfo.workflowRunId,+ stepId: currentStepId,+ title: step.name,+ agentId: agent?.id ?? null,+ prompt: resolvedPrompt,+ initiatorUserWorkspaceId: userWorkspaceId,+ executionResult,+ });+const startedAtMs = Date.now();- const executionResult = await this.aiAgentExecutionService.executeAgent({- agent,- messages: [- { role: 'user', content: resolveInput(prompt, context) as string },- ],- baseSystemPrompt: WORKFLOW_BASE_SYSTEM_PROMPT,- actorContext: executionContext.isActingOnBehalfOfUser- ? executionContext.initiator- : undefined,- authContext: executionContext.authContext,- workspaceId,- userWorkspaceId,- operationType: UsageOperationType.AI_WORKFLOW_TOKEN,- });+ const executionResult = await this.aiAgentExecutionService+ .executeAgent({+ agent,+ messages: [{ role: 'user', content: resolvedPrompt }],+ baseSystemPrompt: WORKFLOW_BASE_SYSTEM_PROMPT,+ actorContext: executionContext.isActingOnBehalfOfUser+ ? executionContext.initiator+ : undefined,+ authContext: executionContext.authContext,+ workspaceId,+ userWorkspaceId,+ operationType: UsageOperationType.AI_WORKFLOW_TOKEN,+ })+ .catch(async (error: unknown) => {+ await recordConversation();+ throw error;+ });const durationMs = Date.now() - startedAtMs;+ await recordConversation(executionResult);+await this.persistStepLog({workflowRunId: runInfo.workflowRunId,workspaceId,@@ -118,6 +138,24 @@ export class AiAgentWorkflowAction implements WorkflowAction {};}+ // The conversation is a record of the step, not part of its outcome, so a+ // failure to write it must not fail a step whose agent did its work.+ private async recordConversation(+ args: Parameters<+ WorkflowAgentConversationWorkspaceService['recordExecution']+ >[0],+ ): Promise<void> {+ try {+ await this.workflowAgentConversationService.recordExecution(args);+ } catch (error) {+ this.logger.warn(+ `Failed to record the conversation for workflowRun=${args.workflowRunId} step=${args.stepId}: ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ }+private async persistStepLog({workflowRunId,workspaceId,diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.tsnew file mode 100644index 00000000000..7a46207cb2f--- /dev/null+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service.ts@@ -0,0 +1,162 @@+import { Injectable } from '@nestjs/common';++import { randomUUID } from 'node:crypto';++import { type ExtendedUIMessagePart } from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';+import { type QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';++import { type AgentMessagePartEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message-part.entity';+import {+ type AgentMessageEntity,+ AgentMessageRole,+} from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-message.entity';+import { type AgentTurnEntity } from 'src/engine/metadata-modules/ai/ai-agent-execution/entities/agent-turn.entity';+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';+import { mapAiStepsToUiMessageParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/map-ai-steps-to-ui-message-parts.util';+import { mapUIMessagePartsToDBParts } from 'src/engine/metadata-modules/ai/ai-agent-execution/utils/mapUIMessagePartsToDBParts';+import { type AgentChatThreadEntity } from 'src/engine/metadata-modules/ai/ai-chat/entities/agent-chat-thread.entity';+import { AgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/agent-history-repository';+import { InjectAgentHistoryRepository } from 'src/engine/metadata-modules/ai/ai-history/repositories/inject-agent-history-repository.decorator';+import { hasWorkflowRunThreadFields } from 'src/engine/metadata-modules/ai/ai-history/utils/has-workflow-run-thread-fields.util';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';++// Each execution of an agent step gets its own conversation, so a loop+// iteration or a retry never reads or continues another one's messages. The+// conversation has no owner: it belongs to the run and is readable by whoever+// can read the run.+@Injectable()+export class WorkflowAgentConversationWorkspaceService {+ constructor(+ @InjectAgentHistoryRepository('agentChatThread')+ private readonly threadRepository: AgentHistoryRepository<AgentChatThreadEntity>,+ @InjectAgentHistoryRepository('agentTurn')+ private readonly turnRepository: AgentHistoryRepository<AgentTurnEntity>,+ @InjectAgentHistoryRepository('agentMessage')+ private readonly messageRepository: AgentHistoryRepository<AgentMessageEntity>,+ @InjectAgentHistoryRepository('agentMessagePart')+ private readonly messagePartRepository: AgentHistoryRepository<AgentMessagePartEntity>,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workflowRunWorkspaceService: WorkflowRunWorkspaceService,+ ) {}++ async recordExecution({+ workspaceId,+ workflowRunId,+ stepId,+ title,+ agentId,+ prompt,+ initiatorUserWorkspaceId,+ executionResult,+ }: {+ workspaceId: string;+ workflowRunId: string;+ stepId: string;+ title: string;+ agentId: string | null;+ prompt: string;+ initiatorUserWorkspaceId: string | null;+ // Absent when the agent failed before replying; the prompt is still+ // recorded so the run shows what the agent was asked.+ executionResult?: Pick<AgentExecutionResult, 'steps'>;+ }): Promise<string | null> {+ const { flatFieldMetadataMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatFieldMetadataMaps',+ ]);++ if (!hasWorkflowRunThreadFields(flatFieldMetadataMaps)) {+ return null;+ }++ const threadId = randomUUID();++ await this.threadRepository.query(workspaceId, ({ manager, table }) =>+ manager.query(+ `INSERT INTO ${table('agentChatThread')} (id, title, "workflowRunId", "workflowStepId")+ VALUES ($1, $2, $3, $4)`,+ [threadId, title, workflowRunId, stepId],+ ),+ );++ const turnInsertResult = await this.turnRepository.insert(workspaceId, {+ threadId,+ agentId,+ });+ const turnId = turnInsertResult.identifiers[0].id as string;++ await this.insertMessage({+ workspaceId,+ threadId,+ turnId,+ role: AgentMessageRole.USER,+ agentId: null,+ senderUserWorkspaceId: initiatorUserWorkspaceId,+ parts: [{ type: 'text', text: prompt }],+ });++ const replyParts = mapAiStepsToUiMessageParts(executionResult?.steps ?? []);++ if (replyParts.length > 0) {+ await this.insertMessage({+ workspaceId,+ threadId,+ turnId,+ role: AgentMessageRole.ASSISTANT,+ agentId,+ senderUserWorkspaceId: null,+ parts: replyParts,+ });+ }++ await this.workflowRunWorkspaceService.setStepThreadId({+ stepId,+ threadId,+ workflowRunId,+ workspaceId,+ });++ return threadId;+ }++ private async insertMessage({+ workspaceId,+ threadId,+ turnId,+ role,+ agentId,+ senderUserWorkspaceId,+ parts,+ }: {+ workspaceId: string;+ threadId: string;+ turnId: string;+ role: AgentMessageRole;+ agentId: string | null;+ senderUserWorkspaceId: string | null;+ parts: ExtendedUIMessagePart[];+ }): Promise<void> {+ const messageId = randomUUID();++ await this.messageRepository.insert(workspaceId, {+ id: messageId,+ threadId,+ turnId,+ role,+ agentId,+ processedAt: new Date(),+ ...(isDefined(senderUserWorkspaceId) ? { senderUserWorkspaceId } : {}),+ });++ const dbParts = mapUIMessagePartsToDBParts(parts, messageId, workspaceId);++ if (dbParts.length > 0) {+ await this.messagePartRepository.insert(+ workspaceId,+ dbParts as QueryDeepPartialEntity<AgentMessagePartEntity>[],+ );+ }+ }+}diff --git a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.tsindex 835888d7dbd..f67b0fe3e2f 100644--- a/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-executor/workspace-services/workflow-executor.workspace-service.ts@@ -33,7 +33,6 @@ import {type WorkflowBranchExecutorInput,type WorkflowExecutorInput,} from 'src/modules/workflow/workflow-executor/types/workflow-executor-input.type';-import { getStepRetryAttempt } from 'src/modules/workflow/workflow-executor/utils/get-step-retry-attempt.util';import { getStepRetryDelayMs } from 'src/modules/workflow/workflow-executor/utils/get-step-retry-delay-ms.util';import { isUserFacingWorkflowExecutorError } from 'src/modules/workflow/workflow-executor/utils/is-user-facing-workflow-executor-error.util';import { stepHasRetryAttemptsLeft } from 'src/modules/workflow/workflow-executor/utils/step-has-retry-attempts-left.util';@@ -179,7 +178,6 @@ export class WorkflowExecutorWorkspaceService {if (canRetryStep) {await this.scheduleStepRetry({stepId,- stepInfo: stepInfos[stepId],error: actionOutput.error,retryDelayMs: getStepRetryDelayMs({ stepInfo: stepInfos[stepId] }),workflowRunId,@@ -676,34 +674,20 @@ export class WorkflowExecutorWorkspaceService {private async scheduleStepRetry({stepId,- stepInfo,error,retryDelayMs,workflowRunId,workspaceId,}: {stepId: string;- stepInfo?: WorkflowRunStepInfo;error: string;retryDelayMs: number;workflowRunId: string;workspaceId: string;}) {- await this.workflowRunWorkspaceService.updateWorkflowRunStepInfos({- stepInfos: {- [stepId]: {- status: StepStatus.PENDING,- error,- history: [- ...(stepInfo?.history ?? []),- {- status: StepStatus.FAILED,- error,- retryAttempt: getStepRetryAttempt({ stepInfo }) + 1,- },- ],- },- },+ await this.workflowRunWorkspaceService.moveStepToRetry({+ stepId,+ error,workflowRunId,workspaceId,});diff --git a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.tsindex 37ddcbaa1df..2005a2b6a53 100644--- a/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service.ts@@ -19,6 +19,7 @@ import {} from 'src/modules/workflow/common/standard-objects/workflow-run.workspace-entity';import { setAllIteratorsStepInfosAsStopped } from 'src/modules/workflow/common/utils/set-all-iterators-step-infos-as-stopped.util';import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';+import { getStepRetryAttempt } from 'src/modules/workflow/workflow-executor/utils/get-step-retry-attempt.util';import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';import {@@ -250,6 +251,58 @@ export class WorkflowRunWorkspaceService {await this.updateWorkflowRun({ workflowRunId, workspaceId, partialUpdate });}+ // Built from the persisted step info rather than the executor's snapshot:+ // the attempt that just failed recorded its conversation while it ran, and+ // only the stored step info carries it into the history entry.+ @WithLock('workflowRunId')+ async moveStepToRetry({+ stepId,+ error,+ workflowRunId,+ workspaceId,+ }: {+ stepId: string;+ error: string;+ workflowRunId: string;+ workspaceId: string;+ }) {+ const workflowRunToUpdate = await this.getWorkflowRunOrFail({+ workflowRunId,+ workspaceId,+ });++ const currentStepInfo = workflowRunToUpdate.state?.stepInfos?.[stepId];++ await this.updateWorkflowRun({+ workflowRunId,+ workspaceId,+ partialUpdate: {+ state: {+ ...workflowRunToUpdate.state,+ stepInfos: {+ ...workflowRunToUpdate.state?.stepInfos,+ [stepId]: {+ ...currentStepInfo,+ status: StepStatus.PENDING,+ error,+ threadId: undefined,+ history: [+ ...(currentStepInfo?.history ?? []),+ {+ status: StepStatus.FAILED,+ error,+ retryAttempt:+ getStepRetryAttempt({ stepInfo: currentStepInfo }) + 1,+ threadId: currentStepInfo?.threadId,+ },+ ],+ },+ },+ },+ },+ });+ }+@WithLock('workflowRunId')async updateWorkflowRunStepInfos({stepInfos,@@ -384,6 +437,44 @@ export class WorkflowRunWorkspaceService {return true;}+ @WithLock('workflowRunId')+ async setStepThreadId({+ stepId,+ threadId,+ workflowRunId,+ workspaceId,+ }: {+ stepId: string;+ threadId: string;+ workflowRunId: string;+ workspaceId: string;+ }) {+ const workflowRunToUpdate = await this.getWorkflowRunOrFail({+ workflowRunId,+ workspaceId,+ });++ const currentStepInfo = workflowRunToUpdate.state?.stepInfos?.[stepId];++ if (!isDefined(currentStepInfo)) {+ return;+ }++ await this.updateWorkflowRun({+ workflowRunId,+ workspaceId,+ partialUpdate: {+ state: {+ ...workflowRunToUpdate.state,+ stepInfos: {+ ...workflowRunToUpdate.state?.stepInfos,+ [stepId]: { ...currentStepInfo, threadId },+ },+ },+ },+ });+ }+@WithLock('workflowRunId')async updateWorkflowRunStep({workflowRunId,diff --git a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.tsindex 365a84252ff..3429aad8d57 100644--- a/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/admin-panel/admin-chat-threads.integration-spec.ts@@ -493,6 +493,34 @@ describe('Admin panel global chat threads (integration)', () => {});});+ // A workflow run's conversation belongs to no member, and a null owner+ // must not null out a non-null field and fail the whole list.+ it('lists a thread without an owner', async () => {+ const ownerlessThreadId = randomUUID();++ await insertHistory(+ 'agentChatThread',+ ['id', 'userWorkspaceId', 'title'],+ [ownerlessThreadId, null, 'Workflow run conversation'],+ 'ON CONFLICT (id) DO NOTHING',+ );+ seededThreadIds.push(ownerlessThreadId);++ const result = await fetchThreads({+ scope: 'ALL',+ searchTerm: ownerlessThreadId,+ });++ expect(result.threads).toEqual([+ expect.objectContaining({+ id: ownerlessThreadId,+ userWorkspaceId: null,+ userEmail: null,+ isOnboardingThread: false,+ }),+ ]);+ });+it('counts only visible messages and user replies', async () => {const result = await fetchThreads({scope: 'ALL',diff --git a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.tsindex 3da42c144e0..44684f328d2 100644--- a/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/object-records-permissions/chat-thread-sharing.integration-spec.ts@@ -5,6 +5,7 @@ import { type AgentChatActorService } from 'src/engine/metadata-modules/ai/ai-chimport { buildWorkspaceSetupChatThreadId } from 'src/engine/metadata-modules/ai/ai-chat/utils/build-workspace-setup-chat-thread-id.util';import { type RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';import { type BillingSubscriptionService } from 'src/engine/core-modules/billing/services/billing-subscription.service';+import { type AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';import { EnableCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790312694997-enable-common-record-sharing.command';import { type AgentHistoryStorageService } from 'src/engine/metadata-modules/ai/ai-history/services/agent-history-storage.service';import { type WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';@@ -509,6 +510,11 @@ describe('Conversation sharing through the authenticated API', () => {expect((await readThread(owner.threadId)).body.errors).toBeUndefined();} finally {await command.up(options);+ // The 2.43 command sets threads PRIVATE; later upgrades have moved them+ // on, so replay those to leave the workspace as other suites expect it.+ await getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(+ 'AddWorkflowRunToChatThreadsCommand',+ ).up(options);await chatService.hardDeleteThread(owner);await updateFeatureFlag({diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.tsindex 457842d2b50..11f28daad5a 100644--- a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-visibility.integration-spec.ts@@ -16,9 +16,13 @@ import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/woimport { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { type AgentExecutionResult } from 'src/engine/metadata-modules/ai/ai-agent-execution/types/agent-execution-result.type';import { type UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';+import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';import { WORKSPACE_MEMBER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/data/constants/workspace-member-data-seeds.constant';+import { type WorkflowAgentConversationWorkspaceService } from 'src/modules/workflow/workflow-executor/workflow-actions/ai-agent/services/workflow-agent-conversation.workspace-service';+import { type WorkflowRunWorkspaceService } from 'src/modules/workflow/workflow-runner/workflow-run/workflow-run.workspace-service';const client = request(`http://localhost:${APP_PORT}`);@@ -32,6 +36,16 @@ const graphqlRequestAs = (.set('Authorization', `Bearer ${accessToken}`).send({ query, variables });+const metadataRequestAs = (+ accessToken: string,+ query: string,+ variables?: object,+) =>+ client+ .post('/metadata')+ .set('Authorization', `Bearer ${accessToken}`)+ .send({ query, variables });+const asOtherMember = (query: string, variables?: object) =>graphqlRequestAs(APPLE_JONY_MEMBER_ACCESS_TOKEN, query, variables);@@ -772,6 +786,212 @@ describe('core workflow visibility (e2e)', () => {});});+ // An agent step's conversation carries no grants of its own: it is read+ // through its run, so it follows the workflow's visibility like the run does.+ describe('the conversation an agent step records on a run', () => {+ let conversationCoreWorkflowId: string;+ let conversationWorkspaceWorkflowId: string;+ let workflowRunId: string;+ let threadId: string;++ const readConversation = (accessToken: string) =>+ metadataRequestAs(+ accessToken,+ `+ query ReadRunConversation($threadId: UUID!) {+ chatThread(id: $threadId) {+ id+ title+ }+ chatMessages(threadId: $threadId) {+ role+ }+ }+ `,+ { threadId },+ );++ beforeAll(async () => {+ let workspaceWorkflowVersionId: string;++ ({+ coreWorkflowId: conversationCoreWorkflowId,+ workspaceWorkflowId: conversationWorkspaceWorkflowId,+ workspaceWorkflowVersionId,+ } = await createActiveManualWorkflow('Workflow With A Conversation'));++ const runResponse = await workflowGraphqlRequest(LEGACY_RUN_MUTATION, {+ input: { workflowVersionId: workspaceWorkflowVersionId },+ });++ expect(runResponse.body.errors).toBeUndefined();+ workflowRunId = runResponse.body.data.runWorkflowVersion.workflowRunId;++ const conversationService =+ getAppProviderByClassName<WorkflowAgentConversationWorkspaceService>(+ 'WorkflowAgentConversationWorkspaceService',+ );++ const recordedThreadId = await conversationService.recordExecution({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ workflowRunId,+ stepId: 'trigger',+ title: 'Summarize the lead',+ agentId: null,+ prompt: 'Summarize the lead',+ initiatorUserWorkspaceId: null,+ executionResult: {+ steps: [+ { content: [{ type: 'text', text: 'A warm lead.' }] },+ ] as AgentExecutionResult['steps'],+ },+ });++ expect(recordedThreadId).not.toBeNull();+ threadId = recordedThreadId!;+ });++ afterAll(async () => {+ if (isDefined(conversationWorkspaceWorkflowId)) {+ await setVisibility(+ conversationCoreWorkflowId,+ WorkflowVisibility.WORKSPACE,+ );+ await workflowGraphqlRequest(DESTROY_WORKFLOW_MUTATION, {+ id: conversationWorkspaceWorkflowId,+ });+ }+ });++ it('points the step at the conversation, which holds the prompt and the reply', async () => {+ const runResponse = await workflowGraphqlRequest(+ `+ query FindRun($id: UUID!) {+ workflowRun(filter: { id: { eq: $id } }) {+ state+ }+ }+ `,+ { id: workflowRunId },+ );++ expect(runResponse.body.errors).toBeUndefined();+ expect(+ runResponse.body.data.workflowRun.state.stepInfos.trigger.threadId,+ ).toBe(threadId);++ const response = await readConversation(APPLE_JANE_ADMIN_ACCESS_TOKEN);++ expect(response.body.errors).toBeUndefined();+ expect(response.body.data.chatThread.title).toBe('Summarize the lead');+ expect(+ response.body.data.chatMessages.map(+ ({ role }: { role: string }) => role,+ ),+ ).toEqual(['user', 'assistant']);+ });++ it('keeps it out of the chat list of someone who can read it', async () => {+ const response = await metadataRequestAs(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ 'query ReadableThreads { chatThreads { id } }',+ );++ expect(response.body.errors).toBeUndefined();+ expect(+ response.body.data.chatThreads.map(({ id }: { id: string }) => id),+ ).not.toContain(threadId);+ });++ it('refuses to rename it or add to it, even for the workflow creator', async () => {+ const renameResponse = await metadataRequestAs(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ `+ mutation RenameRunConversation($threadId: UUID!) {+ renameChatThread(id: $threadId, title: "Renamed") {+ id+ }+ }+ `,+ { threadId },+ );++ expect(renameResponse.body.errors?.[0]?.extensions?.code).toBe(+ 'FORBIDDEN',+ );++ const archiveResponse = await metadataRequestAs(+ APPLE_JANE_ADMIN_ACCESS_TOKEN,+ `+ mutation ArchiveRunConversation($threadId: UUID!) {+ archiveChatThread(id: $threadId) {+ id+ }+ }+ `,+ { threadId },+ );++ expect(archiveResponse.body.errors?.[0]?.extensions?.code).toBe(+ 'FORBIDDEN',+ );+ });++ it('follows the workflow visibility for another member', async () => {+ const whileVisible = await readConversation(+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(whileVisible.body.errors).toBeUndefined();+ expect(whileVisible.body.data.chatThread.id).toBe(threadId);++ const response = await setVisibility(+ conversationCoreWorkflowId,+ WorkflowVisibility.PRIVATE,+ );++ expect(response.body.errors).toBeUndefined();++ const whilePrivate = await readConversation(+ APPLE_JONY_MEMBER_ACCESS_TOKEN,+ );++ expect(whilePrivate.body.data?.chatThread ?? null).toBeNull();+ expect(whilePrivate.body.errors).toBeDefined();++ const asCreator = await readConversation(APPLE_JANE_ADMIN_ACCESS_TOKEN);++ expect(asCreator.body.errors).toBeUndefined();+ expect(asCreator.body.data.chatThread.id).toBe(threadId);+ });++ it('keeps the conversation of an attempt that is retried in the step history', async () => {+ await getAppProviderByClassName<WorkflowRunWorkspaceService>(+ 'WorkflowRunWorkspaceService',+ ).moveStepToRetry({+ stepId: 'trigger',+ error: 'The agent failed',+ workflowRunId,+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ });++ const [{ state }] = await global.testDataSource.query(+ `SELECT state FROM "${getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID)}"."workflowRun" WHERE id = $1`,+ [workflowRunId],+ );++ expect(state.stepInfos.trigger.status).toBe('PENDING');+ expect(state.stepInfos.trigger.threadId).toBeUndefined();+ const { history } = state.stepInfos.trigger;++ expect(history[history.length - 1]).toMatchObject({+ status: 'FAILED',+ error: 'The agent failed',+ threadId,+ });+ });+ });+// Removing a member deletes their membership, and the database then clears// the creator of every workflow they created.describe('the runs of a private workflow whose creator is removed from the workspace', () => {diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.tsindex 1ad52431562..30645b1b90d 100644--- a/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts+++ b/packages/twenty-server/test/integration/upgrade/suites/2-42-workspace-command-1789914239896-migrate-agent-history-to-workspace.integration-spec.ts@@ -1,4 +1,5 @@import { type EnableCommonRecordSharingCommand } from 'src/database/commands/upgrade-version-command/2-43/2-43-workspace-command-1790312694997-enable-common-record-sharing.command';+import { type AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';import { randomUUID } from 'node:crypto';import { STANDARD_OBJECTS } from 'twenty-shared/metadata';@@ -217,6 +218,15 @@ describe('versioned agent history upgrade (integration)', () => {total: 1,options: {},});+ // The history objects were rebuilt as 2.42 leaves them; replay the later+ // upgrade that links threads to runs for the suites that follow.+ await workspaceOrmManager.executeInWorkspaceContext(+ () =>+ getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(+ 'AddWorkflowRunToChatThreadsCommand',+ ).up({ workspaceId: WORKSPACE_ID, index: 0, total: 1, options: {} }),+ buildSystemAuthContext(WORKSPACE_ID),+ );expect(await describeAgentChatThreadTarget(dataSource)).toEqual(seededAgentChatThreadTarget,);diff --git a/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.tsnew file mode 100644index 00000000000..dc20d2c79aa--- /dev/null+++ b/packages/twenty-server/test/integration/upgrade/suites/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.integration-spec.ts@@ -0,0 +1,277 @@+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { MetadataReadability } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER } from 'src/database/commands/upgrade-version-command/2-44/constants/legacy-chat-thread-owner-field-universal-identifier.constant';+import { type AddWorkflowRunToChatThreadsCommand } from 'src/database/commands/upgrade-version-command/2-44/2-44-workspace-command-1790607161319-add-workflow-run-to-chat-threads.command';+import { type ApplicationService } from 'src/engine/core-modules/application/application.service';+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';+import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { type WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';+import { type WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';+import { type WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';++const RUN_ON_WORKSPACE_ARGS = {+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ options: {},+ index: 0,+ total: 1,+};++const FIELD_UNIVERSAL_IDENTIFIERS = [+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,+ STANDARD_OBJECTS.agentChatThread.fields.workflowStepId.universalIdentifier,+ STANDARD_OBJECTS.workflowRun.fields.agentChatThreads.universalIdentifier,+];++const INDEX_UNIVERSAL_IDENTIFIER =+ STANDARD_OBJECTS.agentChatThread.indexes.workflowRunIndex.universalIdentifier;++describe('2-44 workspace command 1790607161319 - AddWorkflowRunToChatThreadsCommand (integration)', () => {+ let command: AddWorkflowRunToChatThreadsCommand;+ let workspaceOrmManager: WorkspaceOrmManager;+ let workspaceCacheService: WorkspaceCacheService;++ const runCommand = (options: { dryRun?: boolean } = {}) =>+ workspaceOrmManager.executeInWorkspaceContext(+ () => command.runOnWorkspace({ ...RUN_ON_WORKSPACE_ARGS, options }),+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),+ );++ const readState = async () => {+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =+ await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ 'flatIndexMaps',+ ]);+ const threadObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.universalIdentifier+ ];++ return {+ fieldCount: FIELD_UNIVERSAL_IDENTIFIERS.filter((universalIdentifier) =>+ isDefined(+ flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],+ ),+ ).length,+ hasIndex: isDefined(+ flatIndexMaps.byUniversalIdentifier[INDEX_UNIVERSAL_IDENTIFIER],+ ),+ isOwnerRequired:+ flatFieldMetadataMaps.byUniversalIdentifier[+ LEGACY_CHAT_THREAD_OWNER_FIELD_UNIVERSAL_IDENTIFIER+ ]?.isNullable === false,+ readability: threadObject?.readability,+ readabilityParentFieldUniversalIdentifiers:+ threadObject?.readabilityParentFieldUniversalIdentifiers,+ };+ };++ // What a workspace that has not run the command yet looks like: no run link+ // and threads PRIVATE, as 2.43 left them.+ const setPreUpgradeState = async () => {+ const migrationService =+ getAppProviderByClassName<WorkspaceMigrationValidateBuildAndRunService>(+ 'WorkspaceMigrationValidateBuildAndRunService',+ );+ const applicationService =+ getAppProviderByClassName<ApplicationService>('ApplicationService');+ const { twentyStandardFlatApplication } =+ await applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId: SEED_APPLE_WORKSPACE_ID },+ );+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =+ await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ 'flatIndexMaps',+ ]);+ const threadObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.universalIdentifier+ ]!;+ const run = async (+ allFlatEntityOperationByMetadataName: Parameters<+ WorkspaceMigrationValidateBuildAndRunService['validateBuildAndRunLegacyWorkspaceMigration']+ >[0]['allFlatEntityOperationByMetadataName'],+ ) => {+ const result =+ await migrationService.validateBuildAndRunLegacyWorkspaceMigration({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ isSystemBuild: true,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ allFlatEntityOperationByMetadataName,+ });++ expect(result.status).toBe('success');+ };++ await run({+ objectMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: [+ {+ ...threadObject,+ readability: MetadataReadability.PRIVATE,+ readabilityParentFieldUniversalIdentifiers: null,+ },+ ],+ },+ });+ await run({+ fieldMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: FIELD_UNIVERSAL_IDENTIFIERS.map(+ (universalIdentifier) =>+ flatFieldMetadataMaps.byUniversalIdentifier[universalIdentifier],+ ).filter(isDefined) as FlatFieldMetadata[],+ flatEntityToUpdate: [],+ },+ index: {+ flatEntityToCreate: [],+ flatEntityToDelete: [+ flatIndexMaps.byUniversalIdentifier[INDEX_UNIVERSAL_IDENTIFIER],+ ].filter(isDefined) as FlatIndexMetadata[],+ flatEntityToUpdate: [],+ },+ });+ };++ beforeAll(async () => {+ command = getAppProviderByClassName<AddWorkflowRunToChatThreadsCommand>(+ 'AddWorkflowRunToChatThreadsCommand',+ );+ workspaceOrmManager = getAppProviderByClassName<WorkspaceOrmManager>(+ 'WorkspaceOrmManager',+ );+ workspaceCacheService = getAppProviderByClassName<WorkspaceCacheService>(+ 'WorkspaceCacheService',+ );++ await setPreUpgradeState();+ });++ afterAll(async () => {+ await runCommand();+ });++ it('starts from a workspace without the run link', async () => {+ expect(await readState()).toMatchObject({+ fieldCount: 0,+ hasIndex: false,+ readability: MetadataReadability.PRIVATE,+ });+ });++ it('changes nothing on a dry run', async () => {+ await runCommand({ dryRun: true });++ expect(await readState()).toMatchObject({+ fieldCount: 0,+ hasIndex: false,+ readability: MetadataReadability.PRIVATE,+ });+ });++ it('links threads to runs and makes them inherit their run readability, as a fresh install does', async () => {+ await runCommand();++ expect(await readState()).toEqual({+ fieldCount: FIELD_UNIVERSAL_IDENTIFIERS.length,+ hasIndex: true,+ isOwnerRequired: false,+ readability: MetadataReadability.INHERITED,+ readabilityParentFieldUniversalIdentifiers: [+ STANDARD_OBJECTS.agentChatThread.fields.workflowRun.universalIdentifier,+ ],+ });+ });++ it('is a no-op when run again', async () => {+ const before = await readState();++ await runCommand();++ expect(await readState()).toEqual(before);+ });++ it('leaves threads still under SYSTEM protection as they are', async () => {+ const { flatObjectMetadataMaps } =+ await workspaceCacheService.getOrRecompute(SEED_APPLE_WORKSPACE_ID, [+ 'flatObjectMetadataMaps',+ ]);+ const threadObject =+ flatObjectMetadataMaps.byUniversalIdentifier[+ STANDARD_OBJECTS.agentChatThread.universalIdentifier+ ]!;+ const migrationService =+ getAppProviderByClassName<WorkspaceMigrationValidateBuildAndRunService>(+ 'WorkspaceMigrationValidateBuildAndRunService',+ );+ const applicationService =+ getAppProviderByClassName<ApplicationService>('ApplicationService');+ const { twentyStandardFlatApplication } =+ await applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId: SEED_APPLE_WORKSPACE_ID },+ );+ const setThreadProtection = async (+ protection: Pick<+ typeof threadObject,+ 'readability' | 'readabilityParentFieldUniversalIdentifiers'+ >,+ ) => {+ const result =+ await migrationService.validateBuildAndRunLegacyWorkspaceMigration({+ workspaceId: SEED_APPLE_WORKSPACE_ID,+ isSystemBuild: true,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ allFlatEntityOperationByMetadataName: {+ objectMetadata: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: [{ ...threadObject, ...protection }],+ },+ },+ });++ expect(result.status).toBe('success');+ };++ await setThreadProtection({+ readability: MetadataReadability.SYSTEM,+ readabilityParentFieldUniversalIdentifiers: null,+ });+ await runCommand();++ expect(await readState()).toMatchObject({+ readability: MetadataReadability.SYSTEM,+ });++ await setThreadProtection({+ readability: threadObject.readability,+ readabilityParentFieldUniversalIdentifiers:+ threadObject.readabilityParentFieldUniversalIdentifiers,+ });+ });++ it('makes threads PRIVATE again on down', async () => {+ await workspaceOrmManager.executeInWorkspaceContext(+ () => command.down(RUN_ON_WORKSPACE_ARGS),+ buildSystemAuthContext(SEED_APPLE_WORKSPACE_ID),+ );++ expect(await readState()).toMatchObject({+ fieldCount: FIELD_UNIVERSAL_IDENTIFIERS.length,+ readability: MetadataReadability.PRIVATE,+ readabilityParentFieldUniversalIdentifiers: null,+ });+ });+});diff --git a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snapindex 9093a426496..06ccf0d0620 100644--- a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap+++ b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap@@ -70,6 +70,12 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"userWorkspaceId": {"universalIdentifier": "bf830886-b6dc-46e9-a229-eecbb0e66032",},+ "workflowRun": {+ "universalIdentifier": "2187f4c6-bff3-4b80-8585-c82965faf79b",+ },+ "workflowStepId": {+ "universalIdentifier": "ba4091ef-dfa2-4a99-bfb3-322ef9a745ab",+ },"workspaceMember": {"universalIdentifier": "6f3ed3b5-0642-4a2a-9558-98376adb60f4",},@@ -78,6 +84,9 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"ownerIndex": {"universalIdentifier": "c97a4c97-266b-490a-a4d6-76274f5de429",},+ "workflowRunIndex": {+ "universalIdentifier": "cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b",+ },"workspaceMemberIndex": {"universalIdentifier": "079f2dd7-6c11-4eae-be8a-cce2d1bee0fb",},@@ -3760,6 +3769,9 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e},"workflowRun": {"fields": {+ "agentChatThreads": {+ "universalIdentifier": "c664a2e7-ef64-4597-9cdf-ded3eae85ae4",+ },"coreWorkflowId": {"universalIdentifier": "e07d8ac0-6b6e-4685-81fa-50d82ae7f880",},diff --git a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.tsindex aa341b61e8e..72001e333c3 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object-fields.constant.ts@@ -60,6 +60,12 @@ export const STANDARD_OBJECT_FIELDS = {activeStreamId: {universalIdentifier: 'bcead20f-75b3-45be-92b9-ea7ec4bddfcd',},+ workflowRun: {+ universalIdentifier: '2187f4c6-bff3-4b80-8585-c82965faf79b',+ },+ workflowStepId: {+ universalIdentifier: 'ba4091ef-dfa2-4a99-bfb3-322ef9a745ab',+ },pendingQuestionMessageId: {universalIdentifier: '51a9b421-7d90-4a59-9712-036ea9721e65',},@@ -1469,6 +1475,9 @@ export const STANDARD_OBJECT_FIELDS = {coreWorkflowVersionId: {universalIdentifier: '58e3f476-425d-4c66-b391-779d0412e107',},+ agentChatThreads: {+ universalIdentifier: 'c664a2e7-ef64-4597-9cdf-ded3eae85ae4',+ },timelineActivities: {universalIdentifier: getSystemRelationFieldUniversalIdentifier({applicationUniversalIdentifier:diff --git a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object.constant.tsindex 8fcdd5b6a72..d44a7689a51 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts@@ -1418,6 +1418,9 @@ export const STANDARD_OBJECTS = {workspaceMemberIndex: {universalIdentifier: '079f2dd7-6c11-4eae-be8a-cce2d1bee0fb',},+ workflowRunIndex: {+ universalIdentifier: 'cc9f8c37-a1ad-4d8d-8e27-894c2cf01a3b',+ },},},agentChatThreadTarget: {diff --git a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.tsindex 2afb3639c31..eb20772a936 100644--- a/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts+++ b/packages/twenty-shared/src/workflow/schemas/workflow-run-state-step-info-schema.ts@@ -6,6 +6,9 @@ export const workflowRunStateStepInfoSchema = z.object({error: z.any().optional(),status: workflowRunStepStatusSchema,retryAttempt: z.number().optional(),+ // The conversation an agent step held on this execution, kept per history+ // entry so each loop iteration's conversation stays reachable.+ threadId: z.string().optional(),get history() {return z.array(@@ -14,6 +17,7 @@ export const workflowRunStateStepInfoSchema = z.object({status: true,error: true,retryAttempt: true,+ threadId: true,}),).optional();