The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
refactor(ai): seed the agent and skill settings forms from the loaded record (#25764)
Félix Malfait489118f25b44
diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsxindex c48038b3e99..5e30e692d4a 100644--- a/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx+++ b/packages/twenty-front/src/pages/settings/ai/SettingsAgentForm.tsx@@ -1,478 +1,68 @@-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { styled } from '@linaria/react';+import { useQuery } from '@apollo/client/react';+import { t } from '@lingui/core/macro';+import { useContext } from 'react';import { useParams } from 'react-router-dom';-import { useDebouncedCallback } from 'use-debounce';+import { isDefined } from 'twenty-shared/utils';+import { useIcons } from 'twenty-ui/icon';+import { Section } from 'twenty-ui/layout';+import { ThemeContext } from 'twenty-ui/theme-constants';-import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';-import { SettingsTabBar } from '@/settings/components/layout/SettingsTabBar';-import { SettingsRolesQueryEffect } from '@/settings/roles/components/SettingsRolesQueryEffect';-import { useSaveDraftRoleToDB } from '@/settings/roles/role/hooks/useSaveDraftRoleToDB';-import { settingsDraftRoleFamilyState } from '@/settings/roles/states/settingsDraftRoleFamilyState';-import { settingsPersistedRoleFamilyState } from '@/settings/roles/states/settingsPersistedRoleFamilyState';-import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';-import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';-import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';-import { t } from '@lingui/core/macro';-import { AppPath, SettingsPath } from 'twenty-shared/types';-import { getSettingsPath, isDefined } from 'twenty-shared/utils';-import {- IconListCheck,- IconLock,- IconSettings,- IconTerminal,- useIcons,-} from 'twenty-ui/icon';-import { Section } from 'twenty-ui/layout';-import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';-import { useMutation, useQuery } from '@apollo/client/react';-import {- type CreateAgentInput,- CreateOneAgentDocument,- FindOneAgentDocument,- UpdateOneAgentDocument,-} from '~/generated-metadata/graphql';-import { useNavigateApp } from '~/hooks/useNavigateApp';-import { useNavigateSettings } from '~/hooks/useNavigateSettings';--import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';-import { useSetAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useSetAtomFamilyState';-import { useContext, useEffect, useState } from 'react';-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';-import { SettingsAgentDetailSkeletonLoader } from './components/SettingsAgentDetailSkeletonLoader';-import { SettingsAgentEvalsTab } from './components/SettingsAgentEvalsTab';-import { SettingsAgentLogsTab } from './components/SettingsAgentLogsTab';-import { SettingsAgentRoleTab } from './components/SettingsAgentRoleTab';-import { SettingsAgentSettingsTab } from './components/SettingsAgentSettingsTab';-import { SETTINGS_AGENT_DETAIL_TABS } from './constants/SettingsAgentDetailTabs';-import { useSettingsAgentFormState } from './hooks/useSettingsAgentFormState';--const StyledContentContainer = styled.div`- display: flex;- flex: 1;- flex-direction: column;- gap: ${themeCssVariables.spacing[8]};- width: 100%;-`;+import { FindOneAgentDocument } from '~/generated-metadata/graphql';+import { SettingsAgentDetailSkeletonLoader } from '~/pages/settings/ai/components/SettingsAgentDetailSkeletonLoader';+import { SettingsAgentFormContent } from '~/pages/settings/ai/components/SettingsAgentFormContent';+import { useNavigateToNotFoundOnLoadFailure } from '~/pages/settings/ai/hooks/useNavigateToNotFoundOnLoadFailure';+import { getSettingsAiBreadcrumbLinks } from '~/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks';export const SettingsAgentForm = ({ mode }: { mode: 'create' | 'edit' }) => {const { theme } = useContext(ThemeContext);const { getIcon } = useIcons();const { agentId = '' } = useParams<{ agentId: string }>();- const navigate = useNavigateSettings();- const navigateApp = useNavigateApp();- const { enqueueErrorSnackBar } = useSnackBar();- const [isReadonlyMode, setIsReadonlyMode] = useState(false);- const [originalFormValues, setOriginalFormValues] = useState<- ReturnType<typeof useSettingsAgentFormState>['formValues'] | null- >(null);- const isEditMode = mode === 'edit';const isCreateMode = mode === 'create';- const tabListComponentId = `${SETTINGS_AGENT_DETAIL_TABS.COMPONENT_INSTANCE_ID}-${agentId}`;- const activeTabId = useAtomComponentStateValue(- activeTabIdComponentState,- tabListComponentId,- );-- const {- formValues,- isSubmitting,- handleFieldChange,- resetForm,- setIsSubmitting,- validateForm,- } = useSettingsAgentFormState(mode);-- const {- data,- loading,- error: agentQueryError,- } = useQuery(FindOneAgentDocument, {+ const { data, loading, error } = useQuery(FindOneAgentDocument, {variables: { id: agentId },skip: isCreateMode || !agentId,});- useEffect(() => {- if (data) {- const agent = data?.findOneAgent;- if (isDefined(agent)) {- if (isDefined(agent.applicationId)) {- setIsReadonlyMode(true);- }- const initialValues = {- name: agent.name,- label: agent.label,- description: agent.description,- icon: agent.icon || 'IconLego',- modelId: agent.modelId,- role: agent.roleId,- prompt: agent.prompt,- isCustom: agent.isCustom,- modelConfiguration: agent.modelConfiguration || {},- // TODO: Fallback can be removed once all text response format agents are migrated.- responseFormat: agent.responseFormat || { type: 'text' },- evaluationInputs: agent.evaluationInputs ?? [],- };- resetForm(initialValues);- setOriginalFormValues(initialValues);- } else {- enqueueErrorSnackBar({- message: t`Agent not found`,- });- navigateApp(AppPath.NotFound);- }- }- }, [data, resetForm, enqueueErrorSnackBar, navigateApp]);-- useEffect(() => {- if (agentQueryError) {- enqueueErrorSnackBar({- apolloError: agentQueryError,- });- navigateApp(AppPath.NotFound);- }- }, [agentQueryError, enqueueErrorSnackBar, navigateApp]);-- const [createAgent] = useMutation(CreateOneAgentDocument);- const [updateAgent] = useMutation(UpdateOneAgentDocument);-const agent = data?.findOneAgent;+ const hasFailedToLoad = !isCreateMode && !loading && !isDefined(agent);- const settingsDraftRole = useAtomFamilyStateValue(- settingsDraftRoleFamilyState,- formValues.role || '',- );- const setSettingsDraftRole = useSetAtomFamilyState(- settingsDraftRoleFamilyState,- formValues.role || '',- );- const settingsPersistedRole = useAtomFamilyStateValue(- settingsPersistedRoleFamilyState,- formValues.role || '',- );-- const { saveDraftRoleToDB } = useSaveDraftRoleToDB({- roleId: formValues.role || '',- isCreateMode: false,+ useNavigateToNotFoundOnLoadFailure({+ hasFailedToLoad,+ error,+ notFoundMessage: t`Agent not found`,});- const isRoleDirty =- isDefined(formValues.role) &&- !isDeeplyEqual(settingsDraftRole, settingsPersistedRole);-- const autoSave = useDebouncedCallback(async () => {- if (- isCreateMode ||- isReadonlyMode ||- !validateForm() ||- isSubmitting ||- !agent- ) {- return;- }-- const hasChanges =- originalFormValues && !isDeeplyEqual(formValues, originalFormValues);-- if (!hasChanges && !isRoleDirty) {- return;- }-- setIsSubmitting(true);-- try {- if (isRoleDirty && isDefined(formValues.role)) {- try {- await saveDraftRoleToDB();- } catch (error) {- if (CombinedGraphQLErrors.is(error)) {- enqueueErrorSnackBar({- apolloError: error,- });- } else {- const errorMessage =- error instanceof Error ? error.message : String(error);- enqueueErrorSnackBar({- message: t`Failed to save role permissions: ${errorMessage}`,- });- }- setIsSubmitting(false);- return;- }- }-- await updateAgent({- variables: {- input: {- id: agent.id,- name: formValues.name || '',- label: formValues.label,- description: formValues.description,- icon: formValues.icon,- modelId: formValues.modelId,- roleId: formValues.role,- prompt: formValues.prompt,- modelConfiguration: formValues.modelConfiguration,- responseFormat: formValues.responseFormat,- evaluationInputs: formValues.evaluationInputs,- },- },- });-- setOriginalFormValues({ ...formValues });- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- }, 1_000);-- useEffect(() => {- if (isEditMode && !loading && isDefined(originalFormValues)) {- autoSave();- }- }, [- formValues,- isRoleDirty,- isEditMode,- loading,- originalFormValues,- autoSave,- ]);-- useEffect(() => {- return () => {- autoSave.flush();- };- }, [autoSave]);+ if (isCreateMode) {+ return <SettingsAgentFormContent />;+ }- if (!isCreateMode && !loading && !agent) {+ if (hasFailedToLoad) {return null;}- const canSave = !isReadonlyMode && validateForm() && !isSubmitting;-- const tabs = [- {- id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.SETTINGS,- title: t`Settings`,- Icon: IconSettings,- },- {- id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.ROLE,- title: t`Role`,- Icon: IconLock,- },- {- id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.EVALS,- title: t`Evals`,- Icon: IconListCheck,- },- {- id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.LOGS,- title: t`Logs`,- Icon: IconTerminal,- },- ];-- const handleSave = async () => {- if (isReadonlyMode) {- return;- }-- if (!validateForm()) {- return;- }-- setIsSubmitting(true);-- try {- if (isRoleDirty && isDefined(formValues.role)) {- try {- await saveDraftRoleToDB();- } catch (error) {- if (CombinedGraphQLErrors.is(error)) {- enqueueErrorSnackBar({- apolloError: error,- });- } else {- const errorMessage =- error instanceof Error ? error.message : String(error);- enqueueErrorSnackBar({- message: t`Failed to save role permissions: ${errorMessage}`,- });- }- setIsSubmitting(false);- return;- }- }-- if (isCreateMode) {- const input: CreateAgentInput = {- name: formValues.name,- label: formValues.label,- description: formValues.description,- icon: formValues.icon,- modelId: formValues.modelId,- roleId: formValues.role,- prompt: formValues.prompt,- modelConfiguration: formValues.modelConfiguration,- responseFormat: formValues.responseFormat,- evaluationInputs: formValues.evaluationInputs,- };-- await createAgent({- variables: { input },- });- navigate(SettingsPath.AI);- return;- }-- if (!agent) {- return;- }-- await updateAgent({- variables: {- input: {- id: agent.id,- name: formValues.name || '',- label: formValues.label,- description: formValues.description,- icon: formValues.icon,- modelId: formValues.modelId,- roleId: formValues.role,- prompt: formValues.prompt,- modelConfiguration: formValues.modelConfiguration,- responseFormat: formValues.responseFormat,- evaluationInputs: formValues.evaluationInputs,- },- },- });+ if (!isDefined(agent)) {+ const AgentIcon = getIcon('IconLego');- navigate(SettingsPath.AI);- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- };-- const handleCancel = () => {- resetForm();-- if (isRoleDirty && isDefined(settingsPersistedRole)) {- setSettingsDraftRole(settingsPersistedRole);- }-- navigate(SettingsPath.AI);- };-- const title = !isCreateMode- ? loading- ? t`Agent`- : agent?.label- : t`New Agent`;- const AgentIcon = getIcon(formValues.icon || 'IconLego');- const breadcrumbText = !isCreateMode- ? loading- ? t`Agent`- : agent?.label- : t`New Agent`;-- const isRoleTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.ROLE;- const isSettingsTab =- activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.SETTINGS;- const isEvalsTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.EVALS;- const isLogsTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.LOGS;-- const isFormDisabled =- isReadonlyMode || (isEditMode ? !agent?.isCustom : false);- const isEvalsDisabled =- process.env.NODE_ENV === 'development' ? isReadonlyMode : isFormDisabled;-- return (- <>- <SettingsRolesQueryEffect />+ return (<SettingsPageLayout- title={title}+ title={t`Agent`}icon={<AgentIcon size={theme.icon.size.md} stroke={theme.icon.stroke.sm} />}- actionButton={- isCreateMode ? (- <SaveAndCancelButtons- onSave={handleSave}- onCancel={handleCancel}- isSaveDisabled={!canSave}- isLoading={isSubmitting}- isCancelDisabled={isSubmitting}- />- ) : undefined- }- links={[- {- children: t`Workspace`,- href: getSettingsPath(SettingsPath.General),- },- { children: t`AI`, href: getSettingsPath(SettingsPath.AI) },- { children: breadcrumbText },- ]}- secondaryBar={- isEditMode && loading ? undefined : (- <SettingsTabBar- tabs={tabs}- componentInstanceId={tabListComponentId}- />- )- }+ links={getSettingsAiBreadcrumbLinks(t`Agent`)}><SettingsPageContainer><Section>- {isEditMode && loading ? (- <SettingsAgentDetailSkeletonLoader />- ) : (- <StyledContentContainer>- {isRoleTab && (- <SettingsAgentRoleTab- formValues={formValues}- onFieldChange={handleFieldChange}- disabled={isFormDisabled}- agentId={agentId}- agentLabel={formValues.label}- />- )}- {isSettingsTab && (- <SettingsAgentSettingsTab- formValues={formValues}- onFieldChange={handleFieldChange}- disabled={isFormDisabled}- agent={agent}- />- )}- {isEvalsTab && (- <SettingsAgentEvalsTab- agentId={agentId}- evaluationInputs={formValues.evaluationInputs}- onEvaluationInputsChange={(inputs) =>- handleFieldChange('evaluationInputs', inputs)- }- disabled={isEvalsDisabled}- />- )}- {isLogsTab && <SettingsAgentLogsTab agentId={agentId} />}- </StyledContentContainer>- )}+ <SettingsAgentDetailSkeletonLoader /></Section></SettingsPageContainer></SettingsPageLayout>- </>- );+ );+ }++ return <SettingsAgentFormContent key={agent.id} agent={agent} />;};diff --git a/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx b/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsxindex eafab11f8a9..22c2781a6a4 100644--- a/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx+++ b/packages/twenty-front/src/pages/settings/ai/SettingsSkillForm.tsx@@ -1,604 +1,66 @@-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { styled } from '@linaria/react';+import { useQuery } from '@apollo/client/react';+import { t } from '@lingui/core/macro';+import { useContext } from 'react';+import Skeleton from 'react-loading-skeleton';import { useParams } from 'react-router-dom';-import { useDebouncedCallback } from 'use-debounce';+import { isDefined } from 'twenty-shared/utils';+import { useIcons } from 'twenty-ui/icon';+import { Section } from 'twenty-ui/layout';+import { ThemeContext } from 'twenty-ui/theme-constants';-import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';-import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';-import { AdvancedSettingsWrapper } from '@/settings/components/AdvancedSettingsWrapper';-import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';-import { SettingsEditableTitle } from '@/settings/components/SettingsEditableTitle';-import { SettingsOptionCardContentSwitch } from '@/settings/components/SettingsOptions/SettingsOptionCardContentSwitch';import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';-import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';-import { IconPicker } from '@/ui/input/components/IconPicker';-import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';-import { TextArea } from '@/ui/input/components/TextArea';import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';-import { t } from '@lingui/core/macro';-import { AppPath, SettingsPath } from 'twenty-shared/types';-import { getSettingsPath, isDefined } from 'twenty-shared/utils';-import {- IconArchive,- IconArchiveOff,- IconInfoCircle,- IconRefresh,- IconTrash,- useIcons,-} from 'twenty-ui/icon';-import { AppTooltip, Card, TooltipDelay } from 'twenty-ui/surfaces';-import { H2Title } from 'twenty-ui/typography';-import { Button } from 'twenty-ui/input';-import { Section } from 'twenty-ui/layout';-import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';-import { useMutation, useQuery } from '@apollo/client/react';-import {- ActivateSkillDocument,- CreateSkillDocument,- DeactivateSkillDocument,- DeleteSkillDocument,- FindOneSkillDocument,- UpdateSkillDocument,-} from '~/generated-metadata/graphql';-import { useNavigateApp } from '~/hooks/useNavigateApp';-import { useNavigateSettings } from '~/hooks/useNavigateSettings';-import { computeMetadataNameFromLabel } from '~/pages/settings/data-model/utils/computeMetadataNameFromLabel';--import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';-import { useModal } from '@/ui/layout/modal/hooks/useModal';-import { useContext, useEffect, useState } from 'react';-import Skeleton from 'react-loading-skeleton';-import { isDeeplyEqual } from '~/utils/isDeeplyEqual';--const StyledFormContainer = styled.div`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[4]};-`;--const StyledIconNameRow = styled.div`- align-items: flex-start;- display: flex;- gap: ${themeCssVariables.spacing[2]};-`;--const StyledNameContainer = styled.div`- flex: 1;-`;--const StyledAdvancedSettingsOuterContainer = styled.div`- padding-top: ${themeCssVariables.spacing[4]};-`;--const StyledAdvancedSettingsContainer = styled.div`- display: flex;- flex-direction: column;- gap: ${themeCssVariables.spacing[4]};- width: 100%;-`;--const StyledDangerButtonsContainer = styled.div`- display: flex;- gap: ${themeCssVariables.spacing[2]};-`;--type SkillFormValues = {- name: string;- label: string;- description: string;- content: string;- icon: string;- isLabelSyncedWithName: boolean;-};--const DELETE_SKILL_MODAL_ID = 'delete-skill-modal';+import { FindOneSkillDocument } from '~/generated-metadata/graphql';+import { SettingsSkillFormContent } from '~/pages/settings/ai/components/SettingsSkillFormContent';+import { useNavigateToNotFoundOnLoadFailure } from '~/pages/settings/ai/hooks/useNavigateToNotFoundOnLoadFailure';+import { getSettingsAiBreadcrumbLinks } from '~/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks';export const SettingsSkillForm = ({ mode }: { mode: 'create' | 'edit' }) => {const { theme } = useContext(ThemeContext);const { getIcon } = useIcons();const { skillId = '' } = useParams<{ skillId: string }>();- const navigate = useNavigateSettings();- const navigateApp = useNavigateApp();- const { enqueueErrorSnackBar } = useSnackBar();- const [isSubmitting, setIsSubmitting] = useState(false);- const [isReadonlyMode, setIsReadonlyMode] = useState(false);- const [originalFormValues, setOriginalFormValues] =- useState<SkillFormValues | null>(null);- const [initializedSkillId, setInitializedSkillId] = useState<string | null>(- null,- );- const { openModal, closeModal } = useModal();- const isEditMode = mode === 'edit';const isCreateMode = mode === 'create';- const [formValues, setFormValues] = useState<SkillFormValues>({- name: '',- label: '',- description: '',- content: '',- icon: 'IconBook',- isLabelSyncedWithName: true,- });-- const {- data,- loading,- error: skillQueryError,- } = useQuery(FindOneSkillDocument, {+ const { data, loading, error } = useQuery(FindOneSkillDocument, {variables: { id: skillId },skip: isCreateMode || !skillId,});- useEffect(() => {- if (data) {- const skill = data?.skill;- if (isDefined(skill)) {- if (initializedSkillId === skill.id) {- return;- }-- setInitializedSkillId(skill.id);- setIsReadonlyMode(!skill.isCustom);-- const computedNameFromLabel = computeMetadataNameFromLabel(skill.label);- const isLabelSyncedWithName = skill.name === computedNameFromLabel;-- const initialValues: SkillFormValues = {- name: skill.name,- label: skill.label,- description: skill.description ?? '',- content: skill.content,- icon: skill.icon ?? 'IconBook',- isLabelSyncedWithName,- };- setFormValues(initialValues);- setOriginalFormValues(initialValues);- } else {- enqueueErrorSnackBar({- message: t`Skill not found`,- });- navigateApp(AppPath.NotFound);- }- }- }, [data, enqueueErrorSnackBar, initializedSkillId, navigateApp]);-- useEffect(() => {- if (skillQueryError) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(skillQueryError)- ? skillQueryError- : undefined,- });- navigateApp(AppPath.NotFound);- }- }, [skillQueryError, enqueueErrorSnackBar, navigateApp]);-- const [createSkill] = useMutation(CreateSkillDocument);- const [updateSkill] = useMutation(UpdateSkillDocument);- const [deleteSkill] = useMutation(DeleteSkillDocument);- const [activateSkill] = useMutation(ActivateSkillDocument);- const [deactivateSkill] = useMutation(DeactivateSkillDocument);-const skill = data?.skill;+ const hasFailedToLoad = !isCreateMode && !loading && !isDefined(skill);- const handleFieldChange = <K extends keyof SkillFormValues>(- fieldName: K,- value: SkillFormValues[K],- ) => {- setFormValues((prev) => {- const newValues = { ...prev, [fieldName]: value };-- if (fieldName === 'label' && prev.isLabelSyncedWithName) {- newValues.name = computeMetadataNameFromLabel(value as string);- }-- if (fieldName === 'isLabelSyncedWithName' && value === true) {- newValues.name = computeMetadataNameFromLabel(prev.label);- }-- return newValues;- });- };-- const validateForm = (): boolean => {- return (- formValues.name.trim().length > 0 &&- formValues.label.trim().length > 0 &&- formValues.content.trim().length > 0- );- };-- const autoSave = useDebouncedCallback(async () => {- if (- isCreateMode ||- isReadonlyMode ||- !validateForm() ||- isSubmitting ||- !skill- ) {- return;- }-- const hasChanges =- originalFormValues && !isDeeplyEqual(formValues, originalFormValues);-- if (!hasChanges) {- return;- }-- setIsSubmitting(true);-- try {- await updateSkill({- variables: {- input: {- id: skill.id,- name: formValues.name,- label: formValues.label,- description: formValues.description || undefined,- content: formValues.content,- icon: formValues.icon || undefined,- },- },- });-- setOriginalFormValues({ ...formValues });- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- }, 1_000);-- useEffect(() => {- if (isEditMode && !loading && isDefined(originalFormValues)) {- autoSave();- }- }, [formValues, isEditMode, loading, originalFormValues, autoSave]);+ useNavigateToNotFoundOnLoadFailure({+ hasFailedToLoad,+ error,+ notFoundMessage: t`Skill not found`,+ });- useEffect(() => {- return () => {- autoSave.flush();- };- }, [autoSave]);+ if (isCreateMode) {+ return <SettingsSkillFormContent />;+ }- if (!isCreateMode && !loading && !skill) {+ if (hasFailedToLoad) {return null;}- const canSave = !isReadonlyMode && validateForm() && !isSubmitting;-- const handleSave = async () => {- if (isReadonlyMode || !validateForm()) {- return;- }-- setIsSubmitting(true);-- try {- if (isCreateMode) {- await createSkill({- variables: {- input: {- name: formValues.name,- label: formValues.label,- description: formValues.description || undefined,- content: formValues.content,- icon: formValues.icon || undefined,- },- },- });- navigate(SettingsPath.AI);- return;- }-- if (!skill) {- return;- }-- await updateSkill({- variables: {- input: {- id: skill.id,- name: formValues.name,- label: formValues.label,- description: formValues.description || undefined,- content: formValues.content,- icon: formValues.icon || undefined,- },- },- });-- navigate(SettingsPath.AI);- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- };-- const handleDelete = async () => {- if (!skill) return;-- setIsSubmitting(true);- try {- await deleteSkill({- variables: { id: skill.id },- });- closeModal(DELETE_SKILL_MODAL_ID);- navigate(SettingsPath.AI);- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- };-- const handleDeactivate = async () => {- if (!skill) return;+ if (!isDefined(skill)) {+ const SkillIcon = getIcon('IconBook');- setIsSubmitting(true);- try {- await deactivateSkill({- variables: { id: skill.id },- });- navigate(SettingsPath.AI);- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- };-- const handleActivate = async () => {- if (!skill) return;-- setIsSubmitting(true);- try {- await activateSkill({- variables: { id: skill.id },- });- navigate(SettingsPath.AI);- } catch (error) {- enqueueErrorSnackBar({- apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,- });- } finally {- setIsSubmitting(false);- }- };-- const handleCancel = () => {- setFormValues({- name: '',- label: '',- description: '',- content: '',- icon: 'IconBook',- isLabelSyncedWithName: true,- });- navigate(SettingsPath.AI);- };-- const breadcrumbText = !isCreateMode- ? loading- ? t`Skill`- : skill?.label- : t`New Skill`;-- const isNameEditEnabled =- !isReadonlyMode && !formValues.isLabelSyncedWithName;-- const apiNameTooltipText = formValues.isLabelSyncedWithName- ? t`Deactivate "Synchronize Label and API Name" to set a custom API name`- : t`Input must be in camel case and cannot start with a number`;-- const title = isCreateMode ? (- t`New Skill`- ) : loading ? (- t`Skill`- ) : (- <SettingsEditableTitle- instanceId="skill-label-input"- disabled={isReadonlyMode}- value={formValues.label}- onChange={(value) => handleFieldChange('label', value)}- placeholder={t`Skill name`}- />- );-- const SkillIcon = getIcon(formValues.icon || 'IconBook');-- return (- <SettingsPageLayout- title={title}- icon={<SkillIcon size={theme.icon.size.md} color={theme.color.blue9} />}- actionButton={- isCreateMode ? (- <SaveAndCancelButtons- onSave={handleSave}- onCancel={handleCancel}- isSaveDisabled={!canSave}- isLoading={isSubmitting}- isCancelDisabled={isSubmitting}- />- ) : undefined- }- links={[- {- children: t`Workspace`,- href: getSettingsPath(SettingsPath.General),- },- { children: t`AI`, href: getSettingsPath(SettingsPath.AI) },- { children: breadcrumbText },- ]}- >- <SettingsPageContainer>- {isEditMode && loading ? (+ return (+ <SettingsPageLayout+ title={t`Skill`}+ icon={<SkillIcon size={theme.icon.size.md} color={theme.color.blue9} />}+ links={getSettingsAiBreadcrumbLinks(t`Skill`)}+ >+ <SettingsPageContainer><Section><Skeleton height={400} borderRadius={4} /></Section>- ) : (- <>- <Section>- <H2Title- title={t`About`}- description={t`Define the name and instructions for this skill`}- />- <StyledFormContainer>- <StyledIconNameRow>- <IconPicker- selectedIconKey={formValues.icon || 'IconBook'}- onChange={({ iconKey }) =>- handleFieldChange('icon', iconKey)- }- disabled={isReadonlyMode}- />- <StyledNameContainer>- <SettingsTextInput- instanceId="skill-label-field-input"- placeholder={t`Skill name`}- value={formValues.label}- onChange={(value) => handleFieldChange('label', value)}- disabled={isReadonlyMode}- fullWidth- />- </StyledNameContainer>- </StyledIconNameRow>-- <TextArea- textAreaId="skill-description-textarea"- placeholder={t`Write a description`}- minRows={3}- maxRows={5}- value={formValues.description}- onChange={(value) =>- handleFieldChange('description', value ?? '')- }- disabled={isReadonlyMode}- />-- <FormAdvancedTextFieldInput- key={originalFormValues?.content ?? 'loading'}- label={t`Instructions`}- readonly={isReadonlyMode}- defaultValue={formValues.content}- profile={AI_INSTRUCTIONS_EDITOR_PROFILE}- onChange={(content: string) =>- handleFieldChange('content', content)- }- enableFullScreen={true}- fullScreenBreadcrumbs={[- {- children: formValues.label || t`Skill`,- href: '#',- },- {- children: t`Instructions Editor`,- },- ]}- minHeight={300}- />-- <AdvancedSettingsWrapper hideDot>- <StyledAdvancedSettingsOuterContainer>- <StyledAdvancedSettingsContainer>- <SettingsTextInput- instanceId="skill-api-name"- label={t`API Name`}- placeholder={t`mySkill`}- value={formValues.name}- onChange={(value) => handleFieldChange('name', value)}- disabled={!isNameEditEnabled}- fullWidth- RightIcon={() =>- apiNameTooltipText && (- <>- <IconInfoCircle- id="info-circle-id-skill-name"- size={theme.icon.size.md}- color={theme.font.color.tertiary}- style={{ outline: 'none' }}- />- <AppTooltip- anchorSelect="#info-circle-id-skill-name"- title={apiNameTooltipText}- offset={5}- noArrow- place="bottom"- positionStrategy="fixed"- delay={TooltipDelay.shortDelay}- />- </>- )- }- />- <Card rounded>- <SettingsOptionCardContentSwitch- Icon={IconRefresh}- title={t`Synchronize Label and API Name`}- description={t`Should changing the label also change the API name?`}- checked={formValues.isLabelSyncedWithName}- disabled={isReadonlyMode}- advancedMode- onChange={(value) =>- handleFieldChange('isLabelSyncedWithName', value)- }- />- </Card>- </StyledAdvancedSettingsContainer>- </StyledAdvancedSettingsOuterContainer>- </AdvancedSettingsWrapper>- </StyledFormContainer>- </Section>-- {skill && (- <Section>- <H2Title- title={t`Danger zone`}- description={t`Deactivate or delete this skill`}- />- <StyledDangerButtonsContainer>- <Button- Icon={skill.isActive ? IconArchive : IconArchiveOff}- title={skill.isActive ? t`Deactivate` : t`Activate`}- size="small"- onClick={skill.isActive ? handleDeactivate : handleActivate}- />- {skill.isCustom && (- <Button- Icon={IconTrash}- title={t`Delete`}- size="small"- accent="danger"- variant="secondary"- onClick={() => openModal(DELETE_SKILL_MODAL_ID)}- />- )}- </StyledDangerButtonsContainer>- </Section>- )}- </>- )}- </SettingsPageContainer>+ </SettingsPageContainer>+ </SettingsPageLayout>+ );+ }- <ConfirmationModal- modalInstanceId={DELETE_SKILL_MODAL_ID}- title={t`Delete Skill`}- subtitle={t`Are you sure you want to delete this skill? This action cannot be undone.`}- onConfirmClick={handleDelete}- confirmButtonText={t`Delete`}- loading={isSubmitting}- />- </SettingsPageLayout>- );+ return <SettingsSkillFormContent key={skill.id} skill={skill} />;};diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentFormContent.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentFormContent.tsxnew file mode 100644index 00000000000..a43ee48c4b4--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentFormContent.tsx@@ -0,0 +1,233 @@+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { useContext, useState } from 'react';+import { SettingsPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import {+ IconListCheck,+ IconLock,+ IconSettings,+ IconTerminal,+ useIcons,+} from 'twenty-ui/icon';+import { Section } from 'twenty-ui/layout';+import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';++import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';+import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';+import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';+import { SettingsTabBar } from '@/settings/components/layout/SettingsTabBar';+import { SettingsRolesQueryEffect } from '@/settings/roles/components/SettingsRolesQueryEffect';+import { settingsDraftRoleFamilyState } from '@/settings/roles/states/settingsDraftRoleFamilyState';+import { settingsPersistedRoleFamilyState } from '@/settings/roles/states/settingsPersistedRoleFamilyState';+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';+import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';+import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';+import { useAtomFamilyStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilyStateValue';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { useSetAtomFamilyState } from '@/ui/utilities/state/jotai/hooks/useSetAtomFamilyState';+import { type FindOneAgentQuery } from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';+import { SettingsAgentEvalsTab } from '~/pages/settings/ai/components/SettingsAgentEvalsTab';+import { SettingsAgentLogsTab } from '~/pages/settings/ai/components/SettingsAgentLogsTab';+import { SettingsAgentRoleTab } from '~/pages/settings/ai/components/SettingsAgentRoleTab';+import { SettingsAgentSettingsTab } from '~/pages/settings/ai/components/SettingsAgentSettingsTab';+import { SETTINGS_AGENT_DETAIL_TABS } from '~/pages/settings/ai/constants/SettingsAgentDetailTabs';+import { useSettingsAgentFormState } from '~/pages/settings/ai/hooks/useSettingsAgentFormState';+import { useSettingsAgentSave } from '~/pages/settings/ai/hooks/useSettingsAgentSave';+import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';+import { getSettingsAgentInitialFormValues } from '~/pages/settings/ai/utils/getSettingsAgentInitialFormValues';+import { getSettingsAiBreadcrumbLinks } from '~/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks';+import { isOwnedByInstalledApplication } from '~/pages/settings/ai/utils/isOwnedByInstalledApplication';+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';++const StyledContentContainer = styled.div`+ display: flex;+ flex: 1;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[8]};+ width: 100%;+`;++type SettingsAgentFormContentProps = {+ agent?: FindOneAgentQuery['findOneAgent'];+};++export const SettingsAgentFormContent = ({+ agent,+}: SettingsAgentFormContentProps) => {+ const { theme } = useContext(ThemeContext);+ const { getIcon } = useIcons();+ const navigate = useNavigateSettings();+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);++ const isCreateMode = !isDefined(agent);+ const isReadonlyMode = isOwnedByInstalledApplication({+ applicationId: agent?.applicationId,+ workspaceCustomApplicationId:+ currentWorkspace?.workspaceCustomApplication?.id,+ });+ const agentId = agent?.id ?? '';++ const [initialFormValues] = useState(() =>+ getSettingsAgentInitialFormValues(agent),+ );++ const tabListComponentId = `${SETTINGS_AGENT_DETAIL_TABS.COMPONENT_INSTANCE_ID}-${agentId}`;+ const activeTabId = useAtomComponentStateValue(+ activeTabIdComponentState,+ tabListComponentId,+ );++ const { formValues, setFieldValue, validateForm } =+ useSettingsAgentFormState(initialFormValues);++ const settingsDraftRole = useAtomFamilyStateValue(+ settingsDraftRoleFamilyState,+ formValues.role || '',+ );+ const setSettingsDraftRole = useSetAtomFamilyState(+ settingsDraftRoleFamilyState,+ formValues.role || '',+ );+ const settingsPersistedRole = useAtomFamilyStateValue(+ settingsPersistedRoleFamilyState,+ formValues.role || '',+ );++ const isRoleDirty =+ isDefined(formValues.role) &&+ !isDeeplyEqual(settingsDraftRole, settingsPersistedRole);++ const { handleSave, isSubmitting, scheduleAutoSave } = useSettingsAgentSave({+ agent,+ formValues,+ initialFormValues,+ isReadonlyMode,+ isRoleDirty,+ validateForm,+ });++ const handleFieldChange = (+ field: keyof SettingsAiAgentFormValues,+ value: SettingsAiAgentFormValues[keyof SettingsAiAgentFormValues],+ ) => {+ setFieldValue(field, value);++ if (isDefined(agent)) {+ scheduleAutoSave();+ }+ };++ const canSave = !isReadonlyMode && validateForm() && !isSubmitting;++ const tabs = [+ {+ id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.SETTINGS,+ title: t`Settings`,+ Icon: IconSettings,+ },+ {+ id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.ROLE,+ title: t`Role`,+ Icon: IconLock,+ },+ {+ id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.EVALS,+ title: t`Evals`,+ Icon: IconListCheck,+ },+ {+ id: SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.LOGS,+ title: t`Logs`,+ Icon: IconTerminal,+ },+ ];++ const handleCancel = () => {+ if (isRoleDirty && isDefined(settingsPersistedRole)) {+ setSettingsDraftRole(settingsPersistedRole);+ }++ navigate(SettingsPath.AI);+ };++ const title = isDefined(agent) ? agent.label : t`New Agent`;+ const AgentIcon = getIcon(formValues.icon || 'IconLego');++ const isRoleTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.ROLE;+ const isSettingsTab =+ activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.SETTINGS;+ const isEvalsTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.EVALS;+ const isLogsTab = activeTabId === SETTINGS_AGENT_DETAIL_TABS.TABS_IDS.LOGS;++ const isFormDisabled =+ isReadonlyMode || (isDefined(agent) ? !agent.isCustom : false);+ const isEvalsDisabled =+ process.env.NODE_ENV === 'development' ? isReadonlyMode : isFormDisabled;++ return (+ <>+ <SettingsRolesQueryEffect />+ <SettingsPageLayout+ title={title}+ icon={+ <AgentIcon size={theme.icon.size.md} stroke={theme.icon.stroke.sm} />+ }+ actionButton={+ isCreateMode ? (+ <SaveAndCancelButtons+ onSave={handleSave}+ onCancel={handleCancel}+ isSaveDisabled={!canSave}+ isLoading={isSubmitting}+ isCancelDisabled={isSubmitting}+ />+ ) : undefined+ }+ links={getSettingsAiBreadcrumbLinks(title)}+ secondaryBar={+ <SettingsTabBar+ tabs={tabs}+ componentInstanceId={tabListComponentId}+ />+ }+ >+ <SettingsPageContainer>+ <Section>+ <StyledContentContainer>+ {isRoleTab && (+ <SettingsAgentRoleTab+ formValues={formValues}+ onFieldChange={handleFieldChange}+ disabled={isFormDisabled}+ agentId={agentId}+ agentLabel={formValues.label}+ />+ )}+ {isSettingsTab && (+ <SettingsAgentSettingsTab+ formValues={formValues}+ onFieldChange={handleFieldChange}+ disabled={isFormDisabled}+ agent={agent}+ />+ )}+ {isEvalsTab && (+ <SettingsAgentEvalsTab+ agentId={agentId}+ evaluationInputs={formValues.evaluationInputs}+ onEvaluationInputsChange={(inputs) =>+ handleFieldChange('evaluationInputs', inputs)+ }+ disabled={isEvalsDisabled}+ />+ )}+ {isLogsTab && <SettingsAgentLogsTab agentId={agentId} />}+ </StyledContentContainer>+ </Section>+ </SettingsPageContainer>+ </SettingsPageLayout>+ </>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsxindex ad45f8893ee..cf700859e93 100644--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentRoleTab.tsx@@ -21,7 +21,7 @@ import {CreateOneRoleDocument,GetRolesDocument,} from '~/generated-metadata/graphql';-import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/hooks/useSettingsAgentFormState';+import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';const StyledWarningText = styled.div`color: ${themeCssVariables.font.color.tertiary};diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSettingsTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSettingsTab.tsxindex 03fe668ae06..6e42f1fd1fe 100644--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSettingsTab.tsx+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentSettingsTab.tsx@@ -18,7 +18,7 @@ import { type Agent } from '~/generated-metadata/graphql';import { SettingsAgentDeleteConfirmationModal } from '~/pages/settings/ai/components/SettingsAgentDeleteConfirmationModal';import { SettingsAgentResponseFormat } from '~/pages/settings/ai/components/SettingsAgentResponseFormat';import { computeMetadataNameFromLabel } from '~/pages/settings/data-model/utils/computeMetadataNameFromLabel';-import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/hooks/useSettingsAgentFormState';+import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';const StyledFormContainer = styled.div`diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentToolsTab.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentToolsTab.tsxindex 890d3f30cbe..15d7bc4a6e8 100644--- a/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentToolsTab.tsx+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsAgentToolsTab.tsx@@ -15,6 +15,7 @@ import { themeCssVariables } from 'twenty-ui/theme-constants';import { SettingsAgentToolsTable } from '~/pages/settings/ai/components/SettingsAgentToolsTable';import { useSettingsAgentToolsTable } from '~/pages/settings/ai/hooks/useSettingsAgentToolsTable';import { type SettingsAgentToolItem } from '~/pages/settings/ai/types/SettingsAgentToolItem';+import { isOwnedByInstalledApplication } from '~/pages/settings/ai/utils/isOwnedByInstalledApplication';import { normalizeSearchText } from '~/utils/normalizeSearchText';const StyledSearchContainer = styled.div`@@ -40,7 +41,10 @@ export const SettingsAgentToolsTab = () => {currentWorkspace?.workspaceCustomApplication?.id;const isManaged = (applicationId?: string | null) =>- isDefined(applicationId) && applicationId !== workspaceCustomApplicationId;+ isOwnedByInstalledApplication({+ applicationId,+ workspaceCustomApplicationId,+ });const isCustom = (tool: SettingsAgentToolItem) =>isDefined(tool.applicationId);diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillDangerZone.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillDangerZone.tsxnew file mode 100644index 00000000000..bfd19c20791--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillDangerZone.tsx@@ -0,0 +1,111 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { useMutation } from '@apollo/client/react';+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { useState } from 'react';+import { SettingsPath } from 'twenty-shared/types';+import { IconArchive, IconArchiveOff, IconTrash } from 'twenty-ui/icon';+import { Button } from 'twenty-ui/input';+import { Section } from 'twenty-ui/layout';+import { themeCssVariables } from 'twenty-ui/theme-constants';+import { H2Title } from 'twenty-ui/typography';++import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';+import { ConfirmationModal } from '@/ui/layout/modal/components/ConfirmationModal';+import { useModal } from '@/ui/layout/modal/hooks/useModal';+import {+ ActivateSkillDocument,+ DeactivateSkillDocument,+ DeleteSkillDocument,+ type FindOneSkillQuery,+} from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';++const StyledDangerButtonsContainer = styled.div`+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+`;++const DELETE_SKILL_MODAL_ID = 'delete-skill-modal';++type SettingsSkillDangerZoneProps = {+ skill: Pick<+ NonNullable<FindOneSkillQuery['skill']>,+ 'id' | 'isActive' | 'isCustom'+ >;+};++export const SettingsSkillDangerZone = ({+ skill,+}: SettingsSkillDangerZoneProps) => {+ const navigate = useNavigateSettings();+ const { enqueueErrorSnackBar } = useSnackBar();+ const { openModal, closeModal } = useModal();+ const [isSubmitting, setIsSubmitting] = useState(false);++ const [deleteSkill] = useMutation(DeleteSkillDocument);+ const [activateSkill] = useMutation(ActivateSkillDocument);+ const [deactivateSkill] = useMutation(DeactivateSkillDocument);++ const runAndLeave = async (mutation: () => Promise<unknown>) => {+ setIsSubmitting(true);+ try {+ await mutation();+ navigate(SettingsPath.AI);+ } catch (error) {+ enqueueErrorSnackBar({+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,+ });+ } finally {+ setIsSubmitting(false);+ }+ };++ const handleDelete = () =>+ runAndLeave(async () => {+ await deleteSkill({ variables: { id: skill.id } });+ closeModal(DELETE_SKILL_MODAL_ID);+ });++ const handleToggleActive = () =>+ runAndLeave(() =>+ skill.isActive+ ? deactivateSkill({ variables: { id: skill.id } })+ : activateSkill({ variables: { id: skill.id } }),+ );++ return (+ <Section>+ <H2Title+ title={t`Danger zone`}+ description={t`Deactivate or delete this skill`}+ />+ <StyledDangerButtonsContainer>+ <Button+ Icon={skill.isActive ? IconArchive : IconArchiveOff}+ title={skill.isActive ? t`Deactivate` : t`Activate`}+ size="small"+ onClick={handleToggleActive}+ />+ {skill.isCustom && (+ <Button+ Icon={IconTrash}+ title={t`Delete`}+ size="small"+ accent="danger"+ variant="secondary"+ onClick={() => openModal(DELETE_SKILL_MODAL_ID)}+ />+ )}+ </StyledDangerButtonsContainer>+ <ConfirmationModal+ modalInstanceId={DELETE_SKILL_MODAL_ID}+ title={t`Delete Skill`}+ subtitle={t`Are you sure you want to delete this skill? This action cannot be undone.`}+ onConfirmClick={handleDelete}+ confirmButtonText={t`Delete`}+ loading={isSubmitting}+ />+ </Section>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillFormContent.tsx b/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillFormContent.tsxnew file mode 100644index 00000000000..313e77a34db--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/components/SettingsSkillFormContent.tsx@@ -0,0 +1,278 @@+import { styled } from '@linaria/react';+import { t } from '@lingui/core/macro';+import { useContext, useState } from 'react';+import { SettingsPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { IconInfoCircle, IconRefresh, useIcons } from 'twenty-ui/icon';+import { Section } from 'twenty-ui/layout';+import { AppTooltip, Card, TooltipDelay } from 'twenty-ui/surfaces';+import { ThemeContext, themeCssVariables } from 'twenty-ui/theme-constants';+import { H2Title } from 'twenty-ui/typography';++import { FormAdvancedTextFieldInput } from '@/advanced-text-editor/components/FormAdvancedTextFieldInput';+import { AI_INSTRUCTIONS_EDITOR_PROFILE } from '@/ai/constants/AiInstructionsEditorProfile';+import { AdvancedSettingsWrapper } from '@/settings/components/AdvancedSettingsWrapper';+import { SaveAndCancelButtons } from '@/settings/components/SaveAndCancelButtons/SaveAndCancelButtons';+import { SettingsEditableTitle } from '@/settings/components/SettingsEditableTitle';+import { SettingsOptionCardContentSwitch } from '@/settings/components/SettingsOptions/SettingsOptionCardContentSwitch';+import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';+import { SettingsPageLayout } from '@/settings/components/layout/SettingsPageLayout';+import { IconPicker } from '@/ui/input/components/IconPicker';+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';+import { TextArea } from '@/ui/input/components/TextArea';+import { type FindOneSkillQuery } from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';+import { SettingsSkillDangerZone } from '~/pages/settings/ai/components/SettingsSkillDangerZone';+import { useSettingsSkillSave } from '~/pages/settings/ai/hooks/useSettingsSkillSave';+import { type SettingsSkillFormValues } from '~/pages/settings/ai/types/SettingsSkillFormValues';+import { getSettingsAiBreadcrumbLinks } from '~/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks';+import { getSettingsSkillInitialFormValues } from '~/pages/settings/ai/utils/getSettingsSkillInitialFormValues';+import { computeMetadataNameFromLabel } from '~/pages/settings/data-model/utils/computeMetadataNameFromLabel';++const StyledFormContainer = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[4]};+`;++const StyledIconNameRow = styled.div`+ align-items: flex-start;+ display: flex;+ gap: ${themeCssVariables.spacing[2]};+`;++const StyledNameContainer = styled.div`+ flex: 1;+`;++const StyledAdvancedSettingsOuterContainer = styled.div`+ padding-top: ${themeCssVariables.spacing[4]};+`;++const StyledAdvancedSettingsContainer = styled.div`+ display: flex;+ flex-direction: column;+ gap: ${themeCssVariables.spacing[4]};+ width: 100%;+`;++type SettingsSkillFormContentProps = {+ skill?: NonNullable<FindOneSkillQuery['skill']>;+};++export const SettingsSkillFormContent = ({+ skill,+}: SettingsSkillFormContentProps) => {+ const { theme } = useContext(ThemeContext);+ const { getIcon } = useIcons();+ const navigate = useNavigateSettings();++ const isCreateMode = !isDefined(skill);+ const isReadonlyMode = isDefined(skill) && !skill.isCustom;++ const [initialFormValues] = useState(() =>+ getSettingsSkillInitialFormValues(skill),+ );+ const [formValues, setFormValues] = useState(initialFormValues);++ const validateForm = (): boolean => {+ return (+ formValues.name.trim().length > 0 &&+ formValues.label.trim().length > 0 &&+ formValues.content.trim().length > 0+ );+ };++ const { handleSave, isSubmitting, scheduleAutoSave } = useSettingsSkillSave({+ skill,+ formValues,+ initialFormValues,+ isReadonlyMode,+ validateForm,+ });++ const handleFieldChange = <TField extends keyof SettingsSkillFormValues>(+ fieldName: TField,+ value: SettingsSkillFormValues[TField],+ ) => {+ setFormValues((previousValues) => {+ const newValues = { ...previousValues, [fieldName]: value };++ if (fieldName === 'label' && previousValues.isLabelSyncedWithName) {+ newValues.name = computeMetadataNameFromLabel(value as string);+ }++ if (fieldName === 'isLabelSyncedWithName' && value === true) {+ newValues.name = computeMetadataNameFromLabel(previousValues.label);+ }++ return newValues;+ });++ if (isDefined(skill)) {+ scheduleAutoSave();+ }+ };++ const canSave = !isReadonlyMode && validateForm() && !isSubmitting;++ const handleCancel = () => {+ setFormValues(initialFormValues);+ navigate(SettingsPath.AI);+ };++ const breadcrumbText = isDefined(skill) ? skill.label : t`New Skill`;++ const isNameEditEnabled =+ !isReadonlyMode && !formValues.isLabelSyncedWithName;++ const apiNameTooltipText = formValues.isLabelSyncedWithName+ ? t`Deactivate "Synchronize Label and API Name" to set a custom API name`+ : t`Input must be in camel case and cannot start with a number`;++ const title = isCreateMode ? (+ t`New Skill`+ ) : (+ <SettingsEditableTitle+ instanceId="skill-label-input"+ disabled={isReadonlyMode}+ value={formValues.label}+ onChange={(value) => handleFieldChange('label', value)}+ placeholder={t`Skill name`}+ />+ );++ const SkillIcon = getIcon(formValues.icon || 'IconBook');++ return (+ <SettingsPageLayout+ title={title}+ icon={<SkillIcon size={theme.icon.size.md} color={theme.color.blue9} />}+ actionButton={+ isCreateMode ? (+ <SaveAndCancelButtons+ onSave={handleSave}+ onCancel={handleCancel}+ isSaveDisabled={!canSave}+ isLoading={isSubmitting}+ isCancelDisabled={isSubmitting}+ />+ ) : undefined+ }+ links={getSettingsAiBreadcrumbLinks(breadcrumbText)}+ >+ <SettingsPageContainer>+ <Section>+ <H2Title+ title={t`About`}+ description={t`Define the name and instructions for this skill`}+ />+ <StyledFormContainer>+ <StyledIconNameRow>+ <IconPicker+ selectedIconKey={formValues.icon || 'IconBook'}+ onChange={({ iconKey }) => handleFieldChange('icon', iconKey)}+ disabled={isReadonlyMode}+ />+ <StyledNameContainer>+ <SettingsTextInput+ instanceId="skill-label-field-input"+ placeholder={t`Skill name`}+ value={formValues.label}+ onChange={(value) => handleFieldChange('label', value)}+ disabled={isReadonlyMode}+ fullWidth+ />+ </StyledNameContainer>+ </StyledIconNameRow>++ <TextArea+ textAreaId="skill-description-textarea"+ placeholder={t`Write a description`}+ minRows={3}+ maxRows={5}+ value={formValues.description}+ onChange={(value) =>+ handleFieldChange('description', value ?? '')+ }+ disabled={isReadonlyMode}+ />++ <FormAdvancedTextFieldInput+ label={t`Instructions`}+ readonly={isReadonlyMode}+ defaultValue={initialFormValues.content}+ profile={AI_INSTRUCTIONS_EDITOR_PROFILE}+ onChange={(content: string) =>+ handleFieldChange('content', content)+ }+ enableFullScreen={true}+ fullScreenBreadcrumbs={[+ {+ children: formValues.label || t`Skill`,+ href: '#',+ },+ {+ children: t`Instructions Editor`,+ },+ ]}+ minHeight={300}+ />++ <AdvancedSettingsWrapper hideDot>+ <StyledAdvancedSettingsOuterContainer>+ <StyledAdvancedSettingsContainer>+ <SettingsTextInput+ instanceId="skill-api-name"+ label={t`API Name`}+ placeholder={t`mySkill`}+ value={formValues.name}+ onChange={(value) => handleFieldChange('name', value)}+ disabled={!isNameEditEnabled}+ fullWidth+ RightIcon={() =>+ apiNameTooltipText && (+ <>+ <IconInfoCircle+ id="info-circle-id-skill-name"+ size={theme.icon.size.md}+ color={theme.font.color.tertiary}+ style={{ outline: 'none' }}+ />+ <AppTooltip+ anchorSelect="#info-circle-id-skill-name"+ title={apiNameTooltipText}+ offset={5}+ noArrow+ place="bottom"+ positionStrategy="fixed"+ delay={TooltipDelay.shortDelay}+ />+ </>+ )+ }+ />+ <Card rounded>+ <SettingsOptionCardContentSwitch+ Icon={IconRefresh}+ title={t`Synchronize Label and API Name`}+ description={t`Should changing the label also change the API name?`}+ checked={formValues.isLabelSyncedWithName}+ disabled={isReadonlyMode}+ advancedMode+ onChange={(value) =>+ handleFieldChange('isLabelSyncedWithName', value)+ }+ />+ </Card>+ </StyledAdvancedSettingsContainer>+ </StyledAdvancedSettingsOuterContainer>+ </AdvancedSettingsWrapper>+ </StyledFormContainer>+ </Section>++ {isDefined(skill) && <SettingsSkillDangerZone skill={skill} />}+ </SettingsPageContainer>+ </SettingsPageLayout>+ );+};diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useNavigateToNotFoundOnLoadFailure.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useNavigateToNotFoundOnLoadFailure.tsnew file mode 100644index 00000000000..b530c7e1b48--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useNavigateToNotFoundOnLoadFailure.ts@@ -0,0 +1,37 @@+import { type ErrorLike } from '@apollo/client';+import { useEffect } from 'react';+import { AppPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';+import { useNavigateApp } from '~/hooks/useNavigateApp';++export const useNavigateToNotFoundOnLoadFailure = ({+ hasFailedToLoad,+ error,+ notFoundMessage,+}: {+ hasFailedToLoad: boolean;+ error?: ErrorLike;+ notFoundMessage: string;+}) => {+ const navigateApp = useNavigateApp();+ const { enqueueErrorSnackBar } = useSnackBar();++ useEffect(() => {+ if (!hasFailedToLoad) {+ return;+ }++ enqueueErrorSnackBar(+ isDefined(error) ? { apolloError: error } : { message: notFoundMessage },+ );+ navigateApp(AppPath.NotFound);+ }, [+ hasFailedToLoad,+ error,+ notFoundMessage,+ enqueueErrorSnackBar,+ navigateApp,+ ]);+};diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentFormState.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentFormState.tsindex 6292c25103c..3c10752813d 100644--- a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentFormState.ts+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentFormState.ts@@ -1,87 +1,27 @@-import { useCallback, useState } from 'react';-import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';-import { isDefined } from 'twenty-shared/utils';-import { type z } from 'zod';-import { settingsAiAgentFormSchema } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';+import { useState } from 'react';+import {+ settingsAiAgentFormSchema,+ type SettingsAiAgentFormValues,+} from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';-export type SettingsAiAgentFormValues = z.infer<- typeof settingsAiAgentFormSchema->;+export const useSettingsAgentFormState = (+ initialValues: SettingsAiAgentFormValues,+) => {+ const [formValues, setFormValues] =+ useState<SettingsAiAgentFormValues>(initialValues);+ const validateForm = (): boolean =>+ settingsAiAgentFormSchema.safeParse(formValues).success;-export const useSettingsAgentFormState = (mode: 'create' | 'edit') => {- const [formValues, setFormValues] = useState<SettingsAiAgentFormValues>({- name: '',- label: '',- description: '',- icon: 'IconLego',- modelId: mode === 'edit' ? '' : AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,- role: null,- prompt: '',- isCustom: true,- modelConfiguration: {},- responseFormat: {- // TODO: Keep text default until legacy text agents are migrated in production.- type: 'text',- },- evaluationInputs: [],- });-- const [isSubmitting, setIsSubmitting] = useState(false);-- const validateForm = (): boolean => {- try {- settingsAiAgentFormSchema.parse(formValues);- return true;- } catch {- return false;- }+ const setFieldValue = (+ field: keyof SettingsAiAgentFormValues,+ value: SettingsAiAgentFormValues[keyof SettingsAiAgentFormValues],+ ) => {+ setFormValues((previousValues) => ({ ...previousValues, [field]: value }));};- const handleFieldChange = useCallback(- (- field: keyof SettingsAiAgentFormValues,- value: SettingsAiAgentFormValues[keyof SettingsAiAgentFormValues],- ) => {- setFormValues((prev) => ({ ...prev, [field]: value }));- },- [],- );-- // Stable so the effect that loads an agent into the form can list it as a- // dependency without re-running, and re-setting state, on every render.- const resetForm = useCallback(- (values?: Partial<SettingsAiAgentFormValues>) => {- if (isDefined(values)) {- setFormValues((prev) => ({ ...prev, ...values }));- } else {- setFormValues({- name: '',- label: '',- description: '',- icon: 'IconLego',- modelId:- mode === 'edit' ? '' : AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,- role: '',- prompt: '',- isCustom: true,- modelConfiguration: {},- responseFormat: {- // TODO: Keep text default until legacy text agents are migrated in production.- type: 'text',- },- evaluationInputs: [],- });- }- },- [mode],- );-return {formValues,- isSubmitting,- handleFieldChange,- resetForm,- setIsSubmitting,+ setFieldValue,validateForm,};};diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.tsnew file mode 100644index 00000000000..e5ca21e6825--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsAgentSave.ts@@ -0,0 +1,195 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { useMutation } from '@apollo/client/react';+import { t } from '@lingui/core/macro';+import { useEffect, useState } from 'react';+import { useDebouncedCallback } from 'use-debounce';+import { SettingsPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { useSaveDraftRoleToDB } from '@/settings/roles/role/hooks/useSaveDraftRoleToDB';+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';+import {+ type CreateAgentInput,+ CreateOneAgentDocument,+ type FindOneAgentQuery,+ UpdateOneAgentDocument,+} from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';+import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';++export const useSettingsAgentSave = ({+ agent,+ formValues,+ initialFormValues,+ isReadonlyMode,+ isRoleDirty,+ validateForm,+}: {+ agent?: FindOneAgentQuery['findOneAgent'];+ formValues: SettingsAiAgentFormValues;+ initialFormValues: SettingsAiAgentFormValues;+ isReadonlyMode: boolean;+ isRoleDirty: boolean;+ validateForm: () => boolean;+}) => {+ const navigate = useNavigateSettings();+ const { enqueueErrorSnackBar } = useSnackBar();+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [originalFormValues, setOriginalFormValues] =+ useState(initialFormValues);++ const [createAgent] = useMutation(CreateOneAgentDocument);+ const [updateAgent] = useMutation(UpdateOneAgentDocument);++ const { saveDraftRoleToDB } = useSaveDraftRoleToDB({+ roleId: formValues.role || '',+ isCreateMode: false,+ });++ const saveDraftRole = async (): Promise<boolean> => {+ try {+ await saveDraftRoleToDB();++ return true;+ } catch (error) {+ if (CombinedGraphQLErrors.is(error)) {+ enqueueErrorSnackBar({+ apolloError: error,+ });+ } else {+ const errorMessage =+ error instanceof Error ? error.message : String(error);+ enqueueErrorSnackBar({+ message: t`Failed to save role permissions: ${errorMessage}`,+ });+ }++ return false;+ }+ };++ const buildUpdateInput = (agentIdToUpdate: string) => ({+ id: agentIdToUpdate,+ name: formValues.name || '',+ label: formValues.label,+ description: formValues.description,+ icon: formValues.icon,+ modelId: formValues.modelId,+ roleId: formValues.role,+ prompt: formValues.prompt,+ modelConfiguration: formValues.modelConfiguration,+ responseFormat: formValues.responseFormat,+ evaluationInputs: formValues.evaluationInputs,+ });++ const autoSave = useDebouncedCallback(async () => {+ if (+ !isDefined(agent) ||+ isReadonlyMode ||+ !validateForm() ||+ isSubmitting+ ) {+ return;+ }++ const hasChanges = !isDeeplyEqual(formValues, originalFormValues);++ if (!hasChanges && !isRoleDirty) {+ return;+ }++ setIsSubmitting(true);++ try {+ if (isRoleDirty && isDefined(formValues.role)) {+ const isRoleSaved = await saveDraftRole();++ if (!isRoleSaved) {+ setIsSubmitting(false);+ return;+ }+ }++ await updateAgent({+ variables: { input: buildUpdateInput(agent.id) },+ });++ setOriginalFormValues({ ...formValues });+ } catch (error) {+ enqueueErrorSnackBar({+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,+ });+ } finally {+ setIsSubmitting(false);+ }+ }, 1_000);++ // Role permissions are edited by the shared roles module through Jotai+ // state, so there is no change handler to schedule the save from.+ useEffect(() => {+ if (isRoleDirty) {+ autoSave();+ }+ }, [isRoleDirty, autoSave]);++ useEffect(() => {+ return () => {+ autoSave.flush();+ };+ }, [autoSave]);++ const handleSave = async () => {+ if (isReadonlyMode || !validateForm()) {+ return;+ }++ setIsSubmitting(true);++ try {+ if (isRoleDirty && isDefined(formValues.role)) {+ const isRoleSaved = await saveDraftRole();++ if (!isRoleSaved) {+ setIsSubmitting(false);+ return;+ }+ }++ if (!isDefined(agent)) {+ const input: CreateAgentInput = {+ name: formValues.name,+ label: formValues.label,+ description: formValues.description,+ icon: formValues.icon,+ modelId: formValues.modelId,+ roleId: formValues.role,+ prompt: formValues.prompt,+ modelConfiguration: formValues.modelConfiguration,+ responseFormat: formValues.responseFormat,+ evaluationInputs: formValues.evaluationInputs,+ };++ await createAgent({+ variables: { input },+ });+ navigate(SettingsPath.AI);+ return;+ }++ await updateAgent({+ variables: { input: buildUpdateInput(agent.id) },+ });++ navigate(SettingsPath.AI);+ } catch (error) {+ enqueueErrorSnackBar({+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,+ });+ } finally {+ setIsSubmitting(false);+ }+ };++ return { handleSave, isSubmitting, scheduleAutoSave: autoSave };+};diff --git a/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsSkillSave.ts b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsSkillSave.tsnew file mode 100644index 00000000000..3e8d55ed9b3--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/hooks/useSettingsSkillSave.ts@@ -0,0 +1,122 @@+import { CombinedGraphQLErrors } from '@apollo/client/errors';+import { useMutation } from '@apollo/client/react';+import { useEffect, useState } from 'react';+import { useDebouncedCallback } from 'use-debounce';+import { SettingsPath } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';+import {+ CreateSkillDocument,+ type FindOneSkillQuery,+ UpdateSkillDocument,+} from '~/generated-metadata/graphql';+import { useNavigateSettings } from '~/hooks/useNavigateSettings';+import { type SettingsSkillFormValues } from '~/pages/settings/ai/types/SettingsSkillFormValues';+import { isDeeplyEqual } from '~/utils/isDeeplyEqual';++export const useSettingsSkillSave = ({+ skill,+ formValues,+ initialFormValues,+ isReadonlyMode,+ validateForm,+}: {+ skill?: Pick<NonNullable<FindOneSkillQuery['skill']>, 'id'>;+ formValues: SettingsSkillFormValues;+ initialFormValues: SettingsSkillFormValues;+ isReadonlyMode: boolean;+ validateForm: () => boolean;+}) => {+ const navigate = useNavigateSettings();+ const { enqueueErrorSnackBar } = useSnackBar();+ const [isSubmitting, setIsSubmitting] = useState(false);+ const [originalFormValues, setOriginalFormValues] =+ useState(initialFormValues);++ const [createSkill] = useMutation(CreateSkillDocument);+ const [updateSkill] = useMutation(UpdateSkillDocument);++ const buildInput = () => ({+ name: formValues.name,+ label: formValues.label,+ description: formValues.description || undefined,+ content: formValues.content,+ icon: formValues.icon || undefined,+ });++ const autoSave = useDebouncedCallback(async () => {+ if (+ !isDefined(skill) ||+ isReadonlyMode ||+ !validateForm() ||+ isSubmitting+ ) {+ return;+ }++ if (isDeeplyEqual(formValues, originalFormValues)) {+ return;+ }++ setIsSubmitting(true);++ try {+ await updateSkill({+ variables: {+ input: { id: skill.id, ...buildInput() },+ },+ });++ setOriginalFormValues({ ...formValues });+ } catch (error) {+ enqueueErrorSnackBar({+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,+ });+ } finally {+ setIsSubmitting(false);+ }+ }, 1_000);++ useEffect(() => {+ return () => {+ autoSave.flush();+ };+ }, [autoSave]);++ const handleSave = async () => {+ if (isReadonlyMode || !validateForm()) {+ return;+ }++ setIsSubmitting(true);++ try {+ if (!isDefined(skill)) {+ await createSkill({+ variables: {+ input: buildInput(),+ },+ });+ navigate(SettingsPath.AI);+ return;+ }++ await updateSkill({+ variables: {+ input: { id: skill.id, ...buildInput() },+ },+ });++ navigate(SettingsPath.AI);+ } catch (error) {+ enqueueErrorSnackBar({+ apolloError: CombinedGraphQLErrors.is(error) ? error : undefined,+ });+ } finally {+ setIsSubmitting(false);+ }+ };++ return { handleSave, isSubmitting, scheduleAutoSave: autoSave };+};diff --git a/packages/twenty-front/src/pages/settings/ai/types/SettingsSkillFormValues.ts b/packages/twenty-front/src/pages/settings/ai/types/SettingsSkillFormValues.tsnew file mode 100644index 00000000000..b18f824e086--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/types/SettingsSkillFormValues.ts@@ -0,0 +1,8 @@+export type SettingsSkillFormValues = {+ name: string;+ label: string;+ description: string;+ content: string;+ icon: string;+ isLabelSyncedWithName: boolean;+};diff --git a/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsAgentInitialFormValues.test.ts b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsAgentInitialFormValues.test.tsnew file mode 100644index 00000000000..e06ae6d0b3c--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsAgentInitialFormValues.test.ts@@ -0,0 +1,68 @@+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';+import { getSettingsAgentInitialFormValues } from '~/pages/settings/ai/utils/getSettingsAgentInitialFormValues';++const agent = {+ __typename: 'Agent' as const,+ id: 'agent-id',+ name: 'salesAssistant',+ label: 'Sales assistant',+ description: 'Qualifies leads',+ icon: 'IconRobot',+ prompt: 'You qualify leads.',+ modelId: 'anthropic/claude-sonnet-5',+ responseFormat: { type: 'json', schema: {} },+ roleId: 'role-id',+ isCustom: true,+ modelConfiguration: { webSearch: { enabled: true } },+ evaluationInputs: ['Is Acme a good fit?'],+ applicationId: 'application-id',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+};++describe('getSettingsAgentInitialFormValues', () => {+ it('starts a new agent on the workspace default model with an empty form', () => {+ expect(getSettingsAgentInitialFormValues()).toEqual({+ name: '',+ label: '',+ description: '',+ icon: 'IconLego',+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ role: null,+ prompt: '',+ isCustom: true,+ modelConfiguration: {},+ responseFormat: { type: 'text' },+ evaluationInputs: [],+ });+ });++ it('maps a loaded agent onto the form fields', () => {+ expect(getSettingsAgentInitialFormValues(agent)).toEqual({+ name: 'salesAssistant',+ label: 'Sales assistant',+ description: 'Qualifies leads',+ icon: 'IconRobot',+ modelId: 'anthropic/claude-sonnet-5',+ role: 'role-id',+ prompt: 'You qualify leads.',+ isCustom: true,+ modelConfiguration: { webSearch: { enabled: true } },+ responseFormat: { type: 'json', schema: {} },+ evaluationInputs: ['Is Acme a good fit?'],+ });+ });++ it('falls back to the default icon, empty configuration and text format when the agent has none', () => {+ const formValues = getSettingsAgentInitialFormValues({+ ...agent,+ icon: null,+ modelConfiguration: null,+ responseFormat: null,+ });++ expect(formValues.icon).toBe('IconLego');+ expect(formValues.modelConfiguration).toEqual({});+ expect(formValues.responseFormat).toEqual({ type: 'text' });+ });+});diff --git a/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsSkillInitialFormValues.test.ts b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsSkillInitialFormValues.test.tsnew file mode 100644index 00000000000..542f6ce1ba8--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/getSettingsSkillInitialFormValues.test.ts@@ -0,0 +1,52 @@+import { getSettingsSkillInitialFormValues } from '~/pages/settings/ai/utils/getSettingsSkillInitialFormValues';++const skill = {+ __typename: 'Skill' as const,+ id: 'skill-id',+ name: 'leadResearch',+ label: 'Lead research',+ description: 'Finds context on a lead',+ icon: 'IconSearch',+ content: 'Search the web for the company.',+ isCustom: true,+ isActive: true,+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+};++describe('getSettingsSkillInitialFormValues', () => {+ it('starts a new skill with an empty form and the label synced to the name', () => {+ expect(getSettingsSkillInitialFormValues()).toEqual({+ name: '',+ label: '',+ description: '',+ content: '',+ icon: 'IconBook',+ isLabelSyncedWithName: true,+ });+ });++ it('maps a loaded skill and keeps the sync on when the name derives from the label', () => {+ expect(getSettingsSkillInitialFormValues(skill)).toEqual({+ name: 'leadResearch',+ label: 'Lead research',+ description: 'Finds context on a lead',+ content: 'Search the web for the company.',+ icon: 'IconSearch',+ isLabelSyncedWithName: true,+ });+ });++ it('turns the sync off for a custom name and falls back to the default icon and empty description', () => {+ const formValues = getSettingsSkillInitialFormValues({+ ...skill,+ name: 'customApiName',+ description: null,+ icon: null,+ });++ expect(formValues.isLabelSyncedWithName).toBe(false);+ expect(formValues.description).toBe('');+ expect(formValues.icon).toBe('IconBook');+ });+});diff --git a/packages/twenty-front/src/pages/settings/ai/utils/__tests__/isOwnedByInstalledApplication.test.ts b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/isOwnedByInstalledApplication.test.tsnew file mode 100644index 00000000000..5003426f207--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/__tests__/isOwnedByInstalledApplication.test.ts@@ -0,0 +1,30 @@+import { isOwnedByInstalledApplication } from '~/pages/settings/ai/utils/isOwnedByInstalledApplication';++describe('isOwnedByInstalledApplication', () => {+ it('is false without an application', () => {+ expect(+ isOwnedByInstalledApplication({+ applicationId: null,+ workspaceCustomApplicationId: 'workspace-app',+ }),+ ).toBe(false);+ });++ it("is false for the workspace's own application", () => {+ expect(+ isOwnedByInstalledApplication({+ applicationId: 'workspace-app',+ workspaceCustomApplicationId: 'workspace-app',+ }),+ ).toBe(false);+ });++ it('is true for any other application', () => {+ expect(+ isOwnedByInstalledApplication({+ applicationId: 'installed-app',+ workspaceCustomApplicationId: 'workspace-app',+ }),+ ).toBe(true);+ });+});diff --git a/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAgentInitialFormValues.ts b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAgentInitialFormValues.tsnew file mode 100644index 00000000000..57236921630--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAgentInitialFormValues.ts@@ -0,0 +1,42 @@+import { AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID } from 'twenty-shared/ai';+import { isDefined } from 'twenty-shared/utils';+import { type FindOneAgentQuery } from '~/generated-metadata/graphql';+import { type SettingsAiAgentFormValues } from '~/pages/settings/ai/validation-schemas/settingsAiAgentFormSchema';++export const getSettingsAgentInitialFormValues = (+ agent?: FindOneAgentQuery['findOneAgent'],+): SettingsAiAgentFormValues => {+ if (!isDefined(agent)) {+ return {+ name: '',+ label: '',+ description: '',+ icon: 'IconLego',+ modelId: AUTO_SELECT_WORKSPACE_DEFAULT_MODEL_ID,+ role: null,+ prompt: '',+ isCustom: true,+ modelConfiguration: {},+ responseFormat: {+ // TODO: Keep text default until legacy text agents are migrated in production.+ type: 'text',+ },+ evaluationInputs: [],+ };+ }++ return {+ name: agent.name,+ label: agent.label,+ description: agent.description,+ icon: agent.icon || 'IconLego',+ modelId: agent.modelId,+ role: agent.roleId,+ prompt: agent.prompt,+ isCustom: agent.isCustom,+ modelConfiguration: agent.modelConfiguration || {},+ // TODO: Fallback can be removed once all text response format agents are migrated.+ responseFormat: agent.responseFormat || { type: 'text' },+ evaluationInputs: agent.evaluationInputs ?? [],+ };+};diff --git a/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks.ts b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks.tsnew file mode 100644index 00000000000..a93df0a2cfe--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsAiBreadcrumbLinks.ts@@ -0,0 +1,12 @@+import { t } from '@lingui/core/macro';+import { SettingsPath } from 'twenty-shared/types';+import { getSettingsPath } from 'twenty-shared/utils';++export const getSettingsAiBreadcrumbLinks = (currentPageLabel: string) => [+ {+ children: t`Workspace`,+ href: getSettingsPath(SettingsPath.General),+ },+ { children: t`AI`, href: getSettingsPath(SettingsPath.AI) },+ { children: currentPageLabel },+];diff --git a/packages/twenty-front/src/pages/settings/ai/utils/getSettingsSkillInitialFormValues.ts b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsSkillInitialFormValues.tsnew file mode 100644index 00000000000..a713326b919--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/getSettingsSkillInitialFormValues.ts@@ -0,0 +1,29 @@+import { isDefined } from 'twenty-shared/utils';+import { type FindOneSkillQuery } from '~/generated-metadata/graphql';+import { computeMetadataNameFromLabel } from '~/pages/settings/data-model/utils/computeMetadataNameFromLabel';+import { type SettingsSkillFormValues } from '~/pages/settings/ai/types/SettingsSkillFormValues';++export const getSettingsSkillInitialFormValues = (+ skill?: FindOneSkillQuery['skill'],+): SettingsSkillFormValues => {+ if (!isDefined(skill)) {+ return {+ name: '',+ label: '',+ description: '',+ content: '',+ icon: 'IconBook',+ isLabelSyncedWithName: true,+ };+ }++ return {+ name: skill.name,+ label: skill.label,+ description: skill.description ?? '',+ content: skill.content,+ icon: skill.icon ?? 'IconBook',+ isLabelSyncedWithName:+ skill.name === computeMetadataNameFromLabel(skill.label),+ };+};diff --git a/packages/twenty-front/src/pages/settings/ai/utils/isOwnedByInstalledApplication.ts b/packages/twenty-front/src/pages/settings/ai/utils/isOwnedByInstalledApplication.tsnew file mode 100644index 00000000000..e8709617d5d--- /dev/null+++ b/packages/twenty-front/src/pages/settings/ai/utils/isOwnedByInstalledApplication.ts@@ -0,0 +1,10 @@+import { isDefined } from 'twenty-shared/utils';++export const isOwnedByInstalledApplication = ({+ applicationId,+ workspaceCustomApplicationId,+}: {+ applicationId?: string | null;+ workspaceCustomApplicationId?: string | null;+}): boolean =>+ isDefined(applicationId) && applicationId !== workspaceCustomApplicationId;