The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add a Triggers tab to the agent page (3/3) (#27324)
Félix Malfait23f1e1ec1f11
diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsxindex d079c1d5484..97cf3f3b159 100644--- a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentFormContent.tsx@@ -3,7 +3,7 @@ import { t } from '@lingui/core/macro';import { useState } from 'react';import { isDefined } from 'twenty-shared/utils';import { Section } from 'twenty-ui/components';-import { IconLock, IconSettings, useIcons } from 'twenty-ui/icon';+import { IconBolt, IconLock, IconSettings, useIcons } from 'twenty-ui/icon';import { useTheme, themeCssVariables } from 'twenty-ui/theme';import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';@@ -21,6 +21,7 @@ import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateimport { type FindOneAgentQuery } from '~/generated-metadata/graphql';import { CoreAgentRoleTab } from '@/object-core/agents/components/CoreAgentRoleTab';import { CoreAgentSettingsTab } from '@/object-core/agents/components/CoreAgentSettingsTab';+import { CoreAgentTriggersTab } from '@/object-core/agents/components/CoreAgentTriggersTab';import { CORE_AGENT_DETAIL_TABS } from '@/object-core/agents/constants/CoreAgentDetailTabs';import { useCoreAgentFormState } from '@/object-core/agents/hooks/useCoreAgentFormState';import { useCoreAgentSave } from '@/object-core/agents/hooks/useCoreAgentSave';@@ -107,6 +108,11 @@ export const CoreAgentFormContent = ({ agent }: CoreAgentFormContentProps) => {title: t`Role`,Icon: IconLock,},+ {+ id: CORE_AGENT_DETAIL_TABS.TABS_IDS.TRIGGERS,+ title: t`Triggers`,+ Icon: IconBolt,+ },];const title = agent.label;@@ -115,6 +121,8 @@ export const CoreAgentFormContent = ({ agent }: CoreAgentFormContentProps) => {const isRoleTab = activeTabId === CORE_AGENT_DETAIL_TABS.TABS_IDS.ROLE;const isSettingsTab =activeTabId === CORE_AGENT_DETAIL_TABS.TABS_IDS.SETTINGS;+ const isTriggersTab =+ activeTabId === CORE_AGENT_DETAIL_TABS.TABS_IDS.TRIGGERS;const isFormDisabled = isReadonlyMode || !agent.isCustom;@@ -155,6 +163,15 @@ export const CoreAgentFormContent = ({ agent }: CoreAgentFormContentProps) => {agent={agent}/>)}+ {isTriggersTab && (+ <CoreAgentTriggersTab+ triggers={formValues.triggers}+ onTriggersChange={(triggers) =>+ handleFieldChange('triggers', triggers)+ }+ disabled={isFormDisabled}+ />+ )}</StyledContentContainer></Section.Root></SettingsPageContainer>diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggerCard.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggerCard.tsxnew file mode 100644index 00000000000..ce53bd858cc--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggerCard.tsx@@ -0,0 +1,274 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import { isNonEmptyString } from '@sniptt/guards';+import { type AgentTrigger } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';+import { LightIconButton } from 'twenty-ui/components';+import { IconClock, IconAddressBook, IconTrash } from 'twenty-ui/icon';+import { Checkbox, type SelectOption } from 'twenty-ui/primitives/input';+import { themeCssVariables, useTheme } from 'twenty-ui/theme';++import { useFilteredObjectMetadataItems } from '@/object-metadata/hooks/useFilteredObjectMetadataItems';+import { type FieldMultiSelectValue } from '@/object-record/record-field/ui/types/FieldMetadata';+import { Select } from '@/ui/input/components/Select';+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';+import { TextArea } from '@/ui/input/components/TextArea';+import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';+import { WorkflowFieldsMultiSelect } from '@/workflow/components/WorkflowEditUpdateEventFieldsMultiSelect';+import { useWorkflowObjectSelectOptions } from '@/workflow/hooks/useWorkflowObjectSelectOptions';+import { describeCronExpression } from '@/workflow/workflow-trigger/utils/cron-to-human/describeCronExpression';++const StyledCard = styled.div`+ border: 1px solid ${themeCssVariables.border.color.medium};+ border-radius: ${themeCssVariables.border.radius.md};+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[3]};+ padding: ${themeCssVariables.spacing[3]};+`;++const StyledHeader = styled.div`+ align-items: center;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+`;++const StyledTitle = styled.div`+ color: ${themeCssVariables.font.color.primary};+ flex: 1;+ font-weight: ${themeCssVariables.font.weight.medium};+`;++const StyledActiveLabel = styled.label`+ align-items: center;+ color: ${themeCssVariables.font.color.secondary};+ display: flex;+ font-size: ${themeCssVariables.font.size.sm};+ gap: ${themeCssVariables.spacing[1]};+`;++const StyledRow = styled.div`+ display: flex;+ gap: ${themeCssVariables.spacing[2]};++ > * {+ flex: 1;+ }+`;++const StyledHint = styled.div<{ isError: boolean }>`+ color: ${({ isError }) =>+ isError+ ? themeCssVariables.color.red+ : themeCssVariables.font.color.tertiary};+ font-size: ${themeCssVariables.font.size.sm};+`;++const toFieldNames = (fields: FieldMultiSelectValue | string): string[] => {+ if (Array.isArray(fields)) {+ return fields;+ }++ return isDefined(fields) ? [fields] : [];+};++type CoreAgentTriggerCardProps = {+ trigger: AgentTrigger;+ onChange: (trigger: AgentTrigger) => void;+ onDelete: () => void;+ disabled: boolean;+};++export const CoreAgentTriggerCard = ({+ trigger,+ onChange,+ onDelete,+ disabled,+}: CoreAgentTriggerCardProps) => {+ const { t } = useLingui();+ const theme = useTheme();+ const { objectMetadataItems } = useFilteredObjectMetadataItems();++ const [objectNameSingular = '', action = 'created'] =+ trigger.type === 'DATABASE_EVENT'+ ? trigger.settings.eventName.split('.')+ : [];++ const objectOptions = useWorkflowObjectSelectOptions({+ selectedObjectNameSingular: objectNameSingular,+ });++ const actionOptions: SelectOption<string>[] = [+ { label: t`Created`, value: 'created' },+ { label: t`Updated`, value: 'updated' },+ { label: t`Created or updated`, value: 'upserted' },+ { label: t`Deleted`, value: 'deleted' },+ { label: t`Permanently deleted`, value: 'destroyed' },+ { label: t`Restored`, value: 'restored' },+ ];++ const selectedObjectMetadataItem = objectMetadataItems.find(+ (objectMetadataItem) =>+ objectMetadataItem.nameSingular === objectNameSingular,+ );++ const updateDatabaseEvent = ({+ nextObjectNameSingular = objectNameSingular,+ nextAction = action,+ updatedFields,+ }: {+ nextObjectNameSingular?: string;+ nextAction?: string;+ updatedFields?: string[];+ }) => {+ if (trigger.type !== 'DATABASE_EVENT') {+ return;+ }++ onChange({+ ...trigger,+ settings: {+ ...trigger.settings,+ eventName: `${nextObjectNameSingular}.${nextAction}`,+ updatedFields: nextAction === 'updated' ? updatedFields : undefined,+ },+ });+ };++ const handleWatchedFieldsChange = (+ fields: FieldMultiSelectValue | string,+ ) => {+ const updatedFields = toFieldNames(fields);++ updateDatabaseEvent({+ updatedFields: updatedFields.length > 0 ? updatedFields : undefined,+ });+ };++ const scheduleDescription = (() => {+ if (trigger.type !== 'CRON') {+ return null;+ }++ try {+ return {+ text: describeCronExpression(trigger.settings.pattern, {+ use24HourTimeFormat: true,+ }),+ isError: false,+ };+ } catch {+ return { text: t`This cron pattern is not valid`, isError: true };+ }+ })();++ const title =+ trigger.type === 'CRON' ? t`On a schedule` : t`When a record changes`;++ const TriggerIcon = trigger.type === 'CRON' ? IconClock : IconAddressBook;++ return (+ <StyledCard>+ <StyledHeader>+ <TriggerIcon size={theme.icon.size.md} />+ <StyledTitle>{title}</StyledTitle>+ <StyledActiveLabel>+ <Checkbox+ aria-label={t`Active`}+ checked={trigger.isActive}+ onCheckedChange={(isChecked) =>+ onChange({ ...trigger, isActive: isChecked })+ }+ disabled={disabled}+ />+ {t`Active`}+ </StyledActiveLabel>+ <LightIconButton+ emphasis="subtle"+ aria-label={t`Remove trigger`}+ onClick={onDelete}+ disabled={disabled}+ >+ <IconTrash />+ </LightIconButton>+ </StyledHeader>+ {trigger.type === 'DATABASE_EVENT' && (+ <>+ <StyledRow>+ <Select+ dropdownId={`agent-trigger-object-${trigger.id}`}+ label={t`Record type`}+ fullWidth+ disabled={disabled}+ value={objectNameSingular}+ options={objectOptions}+ onChange={(value) =>+ updateDatabaseEvent({ nextObjectNameSingular: value })+ }+ withSearchInput+ dropdownWidth={GenericDropdownContentWidth.ExtraLarge}+ />+ <Select+ dropdownId={`agent-trigger-action-${trigger.id}`}+ label={t`Event`}+ fullWidth+ disabled={disabled}+ value={action}+ options={actionOptions}+ onChange={(value) => updateDatabaseEvent({ nextAction: value })}+ />+ </StyledRow>+ {action === 'updated' && isDefined(selectedObjectMetadataItem) && (+ <WorkflowFieldsMultiSelect+ key={objectNameSingular}+ label={t`Fields (optional)`}+ placeholder={t`Only run when one of these fields changes`}+ objectMetadataItem={selectedObjectMetadataItem}+ handleFieldsChange={handleWatchedFieldsChange}+ readonly={disabled}+ defaultFields={trigger.settings.updatedFields}+ actionType="DATABASE_EVENT"+ />+ )}+ </>+ )}+ {trigger.type === 'CRON' && (+ <div>+ <SettingsTextInput+ instanceId={`agent-trigger-cron-${trigger.id}`}+ label={t`Cron pattern`}+ placeholder="0 9 * * 1"+ value={trigger.settings.pattern}+ onChange={(pattern) =>+ onChange({ ...trigger, settings: { pattern } })+ }+ disabled={disabled}+ fullWidth+ />+ {isDefined(scheduleDescription) && (+ <StyledHint isError={scheduleDescription.isError}>+ {scheduleDescription.text}+ </StyledHint>+ )}+ </div>+ )}+ <TextArea+ textAreaId={`agent-trigger-instructions-${trigger.id}`}+ label={t`Instructions`}+ placeholder={t`What should the agent do when this trigger fires?`}+ minRows={2}+ maxRows={8}+ value={trigger.instructions ?? ''}+ onChange={(instructions) =>+ onChange({+ ...trigger,+ instructions: isNonEmptyString(instructions.trim())+ ? instructions+ : null,+ })+ }+ disabled={disabled}+ />+ </StyledCard>+ );+};diff --git a/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggersTab.tsx b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggersTab.tsxnew file mode 100644index 00000000000..8a314ff1cbe--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/components/CoreAgentTriggersTab.tsx@@ -0,0 +1,113 @@+import { styled } from '@linaria/react';+import { useLingui } from '@lingui/react/macro';+import {+ AGENT_TRIGGER_LIMITS,+ type AgentTrigger,+} from 'twenty-shared/application';+import { Section } from 'twenty-ui/components';+import { IconClock, IconAddressBook } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/primitives/input';+import { themeCssVariables } from 'twenty-ui/theme';++import { CoreAgentTriggerCard } from '@/object-core/agents/components/CoreAgentTriggerCard';+import { buildDefaultCoreAgentTrigger } from '@/object-core/agents/utils/buildDefaultCoreAgentTrigger';+import { useWorkflowObjectSelectOptions } from '@/workflow/hooks/useWorkflowObjectSelectOptions';++const StyledTriggerList = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[3]};+`;++const StyledActions = styled.div`+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+ margin-top: ${themeCssVariables.spacing[3]};+`;++const StyledEmptyMessage = styled.div`+ color: ${themeCssVariables.font.color.tertiary};+`;++type CoreAgentTriggersTabProps = {+ triggers: AgentTrigger[];+ onTriggersChange: (triggers: AgentTrigger[]) => void;+ disabled: boolean;+};++export const CoreAgentTriggersTab = ({+ triggers,+ onTriggersChange,+ disabled,+}: CoreAgentTriggersTabProps) => {+ const { t } = useLingui();+ const objectOptions = useWorkflowObjectSelectOptions();++ const defaultObjectNameSingular =+ objectOptions.find((option) => option.value === 'company')?.value ??+ objectOptions[0]?.value ??+ 'company';++ const canAddTrigger =+ !disabled && triggers.length < AGENT_TRIGGER_LIMITS.MAX_TRIGGERS_PER_AGENT;++ const addTrigger = (type: AgentTrigger['type']) =>+ onTriggersChange([+ ...triggers,+ buildDefaultCoreAgentTrigger({+ type,+ objectNameSingular: defaultObjectNameSingular,+ }),+ ]);++ const updateTrigger = (updatedTrigger: AgentTrigger) =>+ onTriggersChange(+ triggers.map((trigger) =>+ trigger.id === updatedTrigger.id ? updatedTrigger : trigger,+ ),+ );++ const deleteTrigger = (triggerId: string) =>+ onTriggersChange(triggers.filter((trigger) => trigger.id !== triggerId));++ return (+ <Section.Root>+ <Section.Header+ title={t`Triggers`}+ description={t`Run this agent on its own when records change or on a schedule. It runs with its role's permissions.`}+ />+ <StyledTriggerList>+ {triggers.length === 0 && (+ <StyledEmptyMessage>+ {t`This agent only runs when someone sends it a message.`}+ </StyledEmptyMessage>+ )}+ {triggers.map((trigger) => (+ <CoreAgentTriggerCard+ key={trigger.id}+ trigger={trigger}+ onChange={updateTrigger}+ onDelete={() => deleteTrigger(trigger.id)}+ disabled={disabled}+ />+ ))}+ </StyledTriggerList>+ {canAddTrigger && (+ <StyledActions>+ <Button+ startIcon={<IconAddressBook />}+ size="sm"+ variant="outline"+ onClick={() => addTrigger('DATABASE_EVENT')}+ >{t`Add record trigger`}</Button>+ <Button+ startIcon={<IconClock />}+ size="sm"+ variant="outline"+ onClick={() => addTrigger('CRON')}+ >{t`Add schedule`}</Button>+ </StyledActions>+ )}+ </Section.Root>+ );+};diff --git a/packages/twenty-front/src/modules/object-core/agents/constants/CoreAgentDetailTabs.ts b/packages/twenty-front/src/modules/object-core/agents/constants/CoreAgentDetailTabs.tsindex 95f7b8e7d91..b172f8cefa3 100644--- a/packages/twenty-front/src/modules/object-core/agents/constants/CoreAgentDetailTabs.ts+++ b/packages/twenty-front/src/modules/object-core/agents/constants/CoreAgentDetailTabs.ts@@ -3,5 +3,6 @@ export const CORE_AGENT_DETAIL_TABS = {TABS_IDS: {ROLE: 'role',SETTINGS: 'settings',+ TRIGGERS: 'triggers',},};diff --git a/packages/twenty-front/src/modules/object-core/agents/hooks/useCoreAgentSave.ts b/packages/twenty-front/src/modules/object-core/agents/hooks/useCoreAgentSave.tsindex e10d9e684bd..254de1d4916 100644--- a/packages/twenty-front/src/modules/object-core/agents/hooks/useCoreAgentSave.ts+++ b/packages/twenty-front/src/modules/object-core/agents/hooks/useCoreAgentSave.ts@@ -74,6 +74,11 @@ export const useCoreAgentSave = ({prompt: formValues.prompt,modelConfiguration: formValues.modelConfiguration,responseFormat: formValues.responseFormat,+ // Stored triggers the form could not parse are left out of formValues, so+ // only send triggers when the user edited them to avoid deleting those+ ...(!isDeeplyEqual(formValues.triggers, originalFormValues.triggers) && {+ triggers: formValues.triggers,+ }),});const autoSave = useDebouncedCallback(async () => {diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/getCoreAgentInitialFormValues.test.ts b/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/getCoreAgentInitialFormValues.test.tsindex ad2d77ee40f..fe3b88441f4 100644--- a/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/getCoreAgentInitialFormValues.test.ts+++ b/packages/twenty-front/src/modules/object-core/agents/utils/__tests__/getCoreAgentInitialFormValues.test.ts@@ -14,7 +14,15 @@ const agent = {isCustom: true,isSystem: false,modelConfiguration: { webSearch: { enabled: true } },- triggers: [],+ triggers: [+ {+ id: '6f1b5a3e-3c3f-4f4a-9a43-0a7f5d6c2b11',+ type: 'CRON',+ isActive: true,+ instructions: 'Send the weekly digest',+ settings: { pattern: '0 9 * * 1' },+ },+ ],applicationId: 'application-id',createdAt: '2026-01-01T00:00:00.000Z',updatedAt: '2026-01-01T00:00:00.000Z',@@ -33,6 +41,15 @@ describe('getCoreAgentInitialFormValues', () => {isCustom: true,modelConfiguration: { webSearch: { enabled: true } },responseFormat: { type: 'json', schema: {} },+ triggers: [+ {+ id: '6f1b5a3e-3c3f-4f4a-9a43-0a7f5d6c2b11',+ type: 'CRON',+ isActive: true,+ instructions: 'Send the weekly digest',+ settings: { pattern: '0 9 * * 1' },+ },+ ],});});diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/buildDefaultCoreAgentTrigger.ts b/packages/twenty-front/src/modules/object-core/agents/utils/buildDefaultCoreAgentTrigger.tsnew file mode 100644index 00000000000..b222e7bf313--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/utils/buildDefaultCoreAgentTrigger.ts@@ -0,0 +1,28 @@+import { type AgentTrigger } from 'twenty-shared/application';+import { v4 } from 'uuid';++export const buildDefaultCoreAgentTrigger = ({+ type,+ objectNameSingular,+}: {+ type: AgentTrigger['type'];+ objectNameSingular: string;+}): AgentTrigger => {+ if (type === 'CRON') {+ return {+ id: v4(),+ type: 'CRON',+ isActive: true,+ instructions: null,+ settings: { pattern: '0 9 * * 1' },+ };+ }++ return {+ id: v4(),+ type: 'DATABASE_EVENT',+ isActive: true,+ instructions: null,+ settings: { eventName: `${objectNameSingular}.created` },+ };+};diff --git a/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts b/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.tsindex 5e802c1de00..8ba668cd555 100644--- a/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts+++ b/packages/twenty-front/src/modules/object-core/agents/utils/getCoreAgentInitialFormValues.ts@@ -1,5 +1,15 @@import { type FindOneAgentQuery } from '~/generated-metadata/graphql';import { type CoreAgentFormValues } from '@/object-core/agents/validation-schemas/coreAgentFormSchema';+import { coreAgentTriggerSchema } from '@/object-core/agents/validation-schemas/coreAgentTriggerSchema';++const parseAgentTriggers = (+ triggers: unknown[],+): CoreAgentFormValues['triggers'] =>+ triggers.flatMap((trigger) => {+ const parsedTrigger = coreAgentTriggerSchema.safeParse(trigger);++ return parsedTrigger.success ? [parsedTrigger.data] : [];+ });export const getCoreAgentInitialFormValues = (agent: FindOneAgentQuery['findOneAgent'],@@ -16,5 +26,6 @@ export const getCoreAgentInitialFormValues = (modelConfiguration: agent.modelConfiguration || {},// TODO: Fallback can be removed once all text response format agents are migrated.responseFormat: agent.responseFormat || { type: 'text' },+ triggers: parseAgentTriggers(agent.triggers ?? []),};};diff --git a/packages/twenty-front/src/modules/object-core/agents/validation-schemas/__tests__/coreAgentTriggerSchema.test.ts b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/__tests__/coreAgentTriggerSchema.test.tsnew file mode 100644index 00000000000..5f8e70167e2--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/__tests__/coreAgentTriggerSchema.test.ts@@ -0,0 +1,83 @@+import { coreAgentTriggerSchema } from '@/object-core/agents/validation-schemas/coreAgentTriggerSchema';++const CRON_TRIGGER = {+ id: '6f1b5a3e-3c3f-4f4a-9a43-0a7f5d6c2b11',+ type: 'CRON' as const,+ isActive: true,+ instructions: null,+ settings: { pattern: '0 9 * * 1' },+};++const DATABASE_EVENT_TRIGGER = {+ id: '0d2b1a8c-77a4-4e2e-8f0c-3a8e9f6b4c22',+ type: 'DATABASE_EVENT' as const,+ isActive: true,+ instructions: 'Qualify the new company',+ settings: { eventName: 'company.created' },+};++describe('coreAgentTriggerSchema', () => {+ it('accepts valid cron and database event triggers', () => {+ expect(coreAgentTriggerSchema.safeParse(CRON_TRIGGER).success).toBe(true);+ expect(+ coreAgentTriggerSchema.safeParse(DATABASE_EVENT_TRIGGER).success,+ ).toBe(true);+ });++ it('rejects a cron pattern that is still being typed', () => {+ expect(+ coreAgentTriggerSchema.safeParse({+ ...CRON_TRIGGER,+ settings: { pattern: '0 9 *' },+ }).success,+ ).toBe(false);+ });++ it('rejects a cleared cron pattern', () => {+ expect(+ coreAgentTriggerSchema.safeParse({+ ...CRON_TRIGGER,+ settings: { pattern: ' ' },+ }).success,+ ).toBe(false);+ });++ it('rejects an event name without an action', () => {+ expect(+ coreAgentTriggerSchema.safeParse({+ ...DATABASE_EVENT_TRIGGER,+ settings: { eventName: 'company' },+ }).success,+ ).toBe(false);+ });++ it('rejects instructions longer than the server accepts', () => {+ expect(+ coreAgentTriggerSchema.safeParse({+ ...CRON_TRIGGER,+ instructions: 'a'.repeat(10_001),+ }).success,+ ).toBe(false);+ });++ it('rejects watched fields outside of an updated event or with empty names', () => {+ expect(+ coreAgentTriggerSchema.safeParse({+ ...DATABASE_EVENT_TRIGGER,+ settings: { eventName: 'company.created', updatedFields: ['name'] },+ }).success,+ ).toBe(false);+ expect(+ coreAgentTriggerSchema.safeParse({+ ...DATABASE_EVENT_TRIGGER,+ settings: { eventName: 'company.updated', updatedFields: [''] },+ }).success,+ ).toBe(false);+ expect(+ coreAgentTriggerSchema.safeParse({+ ...DATABASE_EVENT_TRIGGER,+ settings: { eventName: 'company.updated', updatedFields: ['name'] },+ }).success,+ ).toBe(true);+ });+});diff --git a/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentFormSchema.ts b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentFormSchema.tsindex cda906f9f77..0fa2bb3c717 100644--- a/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentFormSchema.ts+++ b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentFormSchema.ts@@ -1,5 +1,7 @@import { type AgentResponseSchema } from 'twenty-shared/ai';+import { AGENT_TRIGGER_LIMITS } from 'twenty-shared/application';import { z } from 'zod';+import { coreAgentTriggerSchema } from '@/object-core/agents/validation-schemas/coreAgentTriggerSchema';import { zodNonEmptyString } from '~/types/ZodNonEmptyString';export const coreAgentFormSchema = z.object({@@ -33,6 +35,10 @@ export const coreAgentFormSchema = z.object({schema: z.custom<AgentResponseSchema>().optional(),}).optional(),+ triggers: z+ .array(coreAgentTriggerSchema)+ .max(AGENT_TRIGGER_LIMITS.MAX_TRIGGERS_PER_AGENT)+ .default([]),});export type CoreAgentFormValues = z.infer<typeof coreAgentFormSchema>;diff --git a/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentTriggerSchema.ts b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentTriggerSchema.tsnew file mode 100644index 00000000000..b34a56fd40e--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/agents/validation-schemas/coreAgentTriggerSchema.ts@@ -0,0 +1,49 @@+import { CronExpressionParser } from 'cron-parser';+import {+ AGENT_TRIGGER_EVENT_NAME_PATTERN,+ AGENT_TRIGGER_LIMITS,+} from 'twenty-shared/application';+import { z } from 'zod';++const isValidCronPattern = (pattern: string): boolean => {+ try {+ CronExpressionParser.parse(pattern);++ return true;+ } catch {+ return false;+ }+};++const agentTriggerBaseShape = {+ id: z.uuid(),+ isActive: z.boolean(),+ instructions: z+ .string()+ .max(AGENT_TRIGGER_LIMITS.MAX_INSTRUCTIONS_LENGTH)+ .nullable(),+};++export const coreAgentTriggerSchema = z.discriminatedUnion('type', [+ z.object({+ ...agentTriggerBaseShape,+ type: z.literal('DATABASE_EVENT'),+ settings: z+ .object({+ eventName: z.string().regex(AGENT_TRIGGER_EVENT_NAME_PATTERN),+ updatedFields: z.array(z.string().min(1)).optional(),+ batchMode: z.boolean().optional(),+ })+ .refine(+ ({ eventName, updatedFields }) =>+ updatedFields === undefined || eventName.endsWith('.updated'),+ ),+ }),+ z.object({+ ...agentTriggerBaseShape,+ type: z.literal('CRON'),+ settings: z.object({+ pattern: z.string().trim().min(1).refine(isValidCronPattern),+ }),+ }),+]);