The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
chore(getting-started): prepare enrichment, marketplace and AI chat pieces (#29289)
Etienne4661adf5eb8c
diff --git a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsxindex 3f67c742d11..451743053dd 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatEditorSection.tsx@@ -21,6 +21,7 @@ import { AiChatDictationButton } from '@/ai/dictation/components/AiChatDictationimport { AiChatDictationEffect } from '@/ai/dictation/components/AiChatDictationEffect';import { AiChatDictationHint } from '@/ai/dictation/components/AiChatDictationHint';import { AiChatComposerActionsRow } from '@/ai/components/internal/AiChatComposerActionsRow';+import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';import { AiChatEditorFocusEffect } from '@/ai/components/internal/AiChatEditorFocusEffect';import { AiChatSentMessageHandOffEffect } from '@/ai/components/internal/AiChatSentMessageHandOffEffect';import { SendMessageButton } from '@/ai/components/internal/SendMessageButton';@@ -183,6 +184,7 @@ const EditableAiChatEditorSection = () => {<><AiChatAddMenu editor={editor} /><AiChatDictationButton />+ <AiChatContextUsageButton /></>}modelTierDropdownId="ai-chat-model-tier-dropdown"diff --git a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsxindex e5effc52b62..504f3289dfb 100644--- a/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx+++ b/packages/twenty-front/src/modules/ai/components/AiChatQuestionCard.tsx@@ -31,6 +31,7 @@ import { useTheme, themeCssVariables } from 'twenty-ui/theme';import { StyledAiChatAskCard } from '@/ai/components/StyledAiChatAskCard';import { TextWithChatReferences } from '@/ai/components/TextWithChatReferences';import { AiChatComposerActionsRow } from '@/ai/components/internal/AiChatComposerActionsRow';+import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';import { AiChatQuestionOtherOption } from '@/ai/components/internal/AiChatQuestionOtherOption';import { useAnswerAgentChatToolCall } from '@/ai/hooks/useAnswerAgentChatToolCall';import { type AgentChatPendingQuestion } from '@/ai/types/AgentChatPendingQuestion';@@ -468,11 +469,14 @@ export const AiChatQuestionCard = ({<StyledComposerSection><AiChatComposerActionsRowleftActions={- isDefined(onSkip) ? (- <Button size="sm" disabled={isSubmitting} onClick={onSkip}>- {t`Skip`}- </Button>- ) : undefined+ <>+ {isDefined(onSkip) && (+ <Button size="sm" disabled={isSubmitting} onClick={onSkip}>+ {t`Skip`}+ </Button>+ )}+ <AiChatContextUsageButton />+ </>}modelTierDropdownId={`ai-chat-question-model-tier-dropdown-${toolCallId}`}sendButton={diff --git a/packages/twenty-front/src/modules/ai/components/internal/AiChatComposerActionsRow.tsx b/packages/twenty-front/src/modules/ai/components/internal/AiChatComposerActionsRow.tsxindex 4e9723037ca..21ff09b6701 100644--- a/packages/twenty-front/src/modules/ai/components/internal/AiChatComposerActionsRow.tsx+++ b/packages/twenty-front/src/modules/ai/components/internal/AiChatComposerActionsRow.tsx@@ -3,7 +3,6 @@ import { type ReactNode } from 'react';import { themeCssVariables } from 'twenty-ui/theme';import { AiModelTierDropdown } from '@/ai/components/AiModelTierDropdown';-import { AiChatContextUsageButton } from '@/ai/components/internal/AiChatContextUsageButton';import { aiModelsState } from '@/client-config/states/aiModelsState';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';@@ -41,10 +40,7 @@ export const AiChatComposerActionsRow = ({return (<StyledActionsRow>- <StyledLeftActions>- {leftActions}- <AiChatContextUsageButton />- </StyledLeftActions>+ <StyledLeftActions>{leftActions}</StyledLeftActions><StyledRightActions><AiModelTierDropdowndropdownId={modelTierDropdownId}diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsxindex 5cbf884762c..9a5bedc2eb0 100644--- a/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsx+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useAiChatFileUpload.test.tsx@@ -54,7 +54,9 @@ describe('useAiChatFileUpload', () => {});const file = new File(['brief'], 'brief.pdf');- let upload: Promise<void> = Promise.resolve();+ let upload: ReturnType<typeof result.current.uploadFiles> = Promise.resolve(+ [],+ );act(() => {upload = result.current.uploadFiles([file]);diff --git a/packages/twenty-front/src/modules/ai/hooks/__tests__/useOpenAskAiPageWithPreprompt.test.tsx b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOpenAskAiPageWithPreprompt.test.tsxnew file mode 100644index 00000000000..cb6696bfa60--- /dev/null+++ b/packages/twenty-front/src/modules/ai/hooks/__tests__/useOpenAskAiPageWithPreprompt.test.tsx@@ -0,0 +1,109 @@+import { act, renderHook } from '@testing-library/react';+import { Provider as JotaiProvider } from 'jotai';+import { type ReactNode } from 'react';++import { useOpenAskAiPageWithPreprompt } from '@/ai/hooks/useOpenAskAiPageWithPreprompt';+import { agentChatDraftsByThreadIdState } from '@/ai/states/agentChatDraftsByThreadIdState';+import { agentChatPrepromptState } from '@/ai/states/agentChatPrepromptState';+import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';+import { type AgentChatFileUIPart } from '@/ai/types/AgentChatFileUIPart';+import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';++const NEW_CHAT_THREAD_ID = 'new-chat-thread-id';+const OTHER_CHAT_THREAD_ID = 'other-chat-thread-id';++const uploadedFile: AgentChatFileUIPart = {+ type: 'file',+ filename: 'contacts.csv',+ mediaType: 'text/csv',+ url: 'https://storage.twenty.com/contacts.csv',+ fileId: 'file-id',+};++let finishUpload: () => void = () => {};++jest.mock('@/ai/hooks/useSwitchToNewAiChat', () => ({+ useSwitchToNewAiChat: () => ({+ switchToNewChat: () =>+ jotaiStore.set(currentAiChatThreadState.atom, NEW_CHAT_THREAD_ID),+ }),+}));++jest.mock('@/ai/hooks/useAiChatFileUpload', () => ({+ useAiChatFileUpload: () => ({+ uploadFiles: () =>+ new Promise<AgentChatFileUIPart[]>((resolve) => {+ finishUpload = () => {+ jotaiStore.set(agentChatUploadedFilesState.atom, [uploadedFile]);+ resolve([uploadedFile]);+ };+ }),+ }),+}));++jest.mock('@/ai/hooks/useWorkspaceAiModelTiers', () => ({+ useWorkspaceAiModelTiers: () => ({ chatTier: 'smart' }),+}));++const Wrapper = ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={jotaiStore}>{children}</JotaiProvider>+);++describe('useOpenAskAiPageWithPreprompt', () => {+ beforeEach(() => {+ jotaiStore.set(agentChatDraftsByThreadIdState.atom, {});+ jotaiStore.set(agentChatPrepromptState.atom, null);+ jotaiStore.set(agentChatUploadedFilesState.atom, []);+ });++ it('sends the prompt in the new chat once the files have uploaded', async () => {+ const { result } = renderHook(() => useOpenAskAiPageWithPreprompt(), {+ wrapper: Wrapper,+ });++ await act(async () => {+ const opening = result.current.openAskAiPageWithPreprompt({+ serializedDocument: 'Import these contacts',+ mode: 'SEND',+ files: [new File(['name'], 'contacts.csv')],+ });++ finishUpload();+ await opening;+ });++ expect(jotaiStore.get(agentChatDraftsByThreadIdState.atom)).toEqual({+ [NEW_CHAT_THREAD_ID]: 'Import these contacts',+ });+ expect(jotaiStore.get(agentChatPrepromptState.atom)).toEqual({+ serializedDocument: 'Import these contacts',+ mode: 'SEND',+ });+ expect(jotaiStore.get(agentChatUploadedFilesState.atom)).toEqual([+ uploadedFile,+ ]);+ });++ it('drops the prompt and its files when the user switches chats during the upload', async () => {+ const { result } = renderHook(() => useOpenAskAiPageWithPreprompt(), {+ wrapper: Wrapper,+ });++ await act(async () => {+ const opening = result.current.openAskAiPageWithPreprompt({+ serializedDocument: 'Import these contacts',+ mode: 'SEND',+ files: [new File(['name'], 'contacts.csv')],+ });++ jotaiStore.set(currentAiChatThreadState.atom, OTHER_CHAT_THREAD_ID);+ finishUpload();+ await opening;+ });++ expect(jotaiStore.get(agentChatDraftsByThreadIdState.atom)).toEqual({});+ expect(jotaiStore.get(agentChatPrepromptState.atom)).toBeNull();+ expect(jotaiStore.get(agentChatUploadedFilesState.atom)).toEqual([]);+ });+});diff --git a/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts b/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.tsindex 9565ea4d76c..535819d7f86 100644--- a/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useAiChatFileUpload.ts@@ -85,6 +85,8 @@ export const useAiChatFileUpload = () => {...successfulUploads,]);}++ return successfulUploads;};return { uploadFiles };diff --git a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.tsindex 30a8c2ff7c9..cf41101306d 100644--- a/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts+++ b/packages/twenty-front/src/modules/ai/hooks/useOpenAskAiPageWithPreprompt.ts@@ -1,10 +1,14 @@+import { useStore } from 'jotai';import { type AiModelTier } from 'twenty-shared/ai';-import { isDefined } from 'twenty-shared/utils';+import { isDefined, isNonEmptyArray } from 'twenty-shared/utils';+import { useAiChatFileUpload } from '@/ai/hooks/useAiChatFileUpload';import { useStageAiChatPreprompt } from '@/ai/hooks/useStageAiChatPreprompt';import { useSwitchToNewAiChat } from '@/ai/hooks/useSwitchToNewAiChat';import { type AgentChatPrepromptMode } from '@/ai/states/agentChatPrepromptState';import { useWorkspaceAiModelTiers } from '@/ai/hooks/useWorkspaceAiModelTiers';+import { agentChatUploadedFilesState } from '@/ai/states/agentChatUploadedFilesState';+import { currentAiChatThreadState } from '@/ai/states/currentAiChatThreadState';import { agentChatUserSelectedModelTierState } from '@/ai/states/agentChatUserSelectedModelTierState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';@@ -17,21 +21,28 @@ const TIER_BY_PRESELECTION: Record<AgentChatModelPreselection, AiModelTier> = {};export const useOpenAskAiPageWithPreprompt = () => {+ const store = useStore();const { switchToNewChat } = useSwitchToNewAiChat();const { stageAiChatPreprompt } = useStageAiChatPreprompt();const setAgentChatUserSelectedModelTier = useSetAtomState(agentChatUserSelectedModelTierState,);const { chatTier } = useWorkspaceAiModelTiers();+ const { uploadFiles } = useAiChatFileUpload();+ const setAgentChatUploadedFiles = useSetAtomState(+ agentChatUploadedFilesState,+ );- const openAskAiPageWithPreprompt = ({+ const openAskAiPageWithPreprompt = async ({serializedDocument,mode = 'PREFILL',model,+ files,}: {serializedDocument: string;mode?: AgentChatPrepromptMode;model?: AgentChatModelPreselection;+ files?: File[];}) => {switchToNewChat();@@ -42,7 +53,30 @@ export const useOpenAskAiPageWithPreprompt = () => {setAgentChatUserSelectedModelTier(tier === chatTier ? null : tier);}- stageAiChatPreprompt({ serializedDocument, mode });+ if (!isNonEmptyArray(files)) {+ stageAiChatPreprompt({ serializedDocument, mode });++ return;+ }++ const threadId = store.get(currentAiChatThreadState.atom);++ const uploadedFiles = await uploadFiles(files);++ if (store.get(currentAiChatThreadState.atom) !== threadId) {+ setAgentChatUploadedFiles((previousUploadedFiles) =>+ previousUploadedFiles.filter(+ (uploadedFile) => !uploadedFiles.includes(uploadedFile),+ ),+ );++ return;+ }++ stageAiChatPreprompt({+ serializedDocument,+ mode: isNonEmptyArray(uploadedFiles) ? mode : 'PREFILL',+ });};return { openAskAiPageWithPreprompt };diff --git a/packages/twenty-front/src/modules/object-record/spreadsheet-import/hooks/useOpenObjectRecordsSpreadsheetImportDialog.ts b/packages/twenty-front/src/modules/object-record/spreadsheet-import/hooks/useOpenObjectRecordsSpreadsheetImportDialog.tsindex 185409bb1f5..59cd846ac8d 100644--- a/packages/twenty-front/src/modules/object-record/spreadsheet-import/hooks/useOpenObjectRecordsSpreadsheetImportDialog.ts+++ b/packages/twenty-front/src/modules/object-record/spreadsheet-import/hooks/useOpenObjectRecordsSpreadsheetImportDialog.ts@@ -49,10 +49,7 @@ export const useOpenObjectRecordsSpreadsheetImportDialog = (});const openObjectRecordsSpreadsheetImportDialog = (- options?: Omit<- SpreadsheetImportDialogOptions,- 'fields' | 'isOpen' | 'onClose'- >,+ options?: Pick<SpreadsheetImportDialogOptions, 'uploadStepHook'>,) => {const availableFieldMetadataItemsToImport =spreadsheetImportFilterAvailableFieldMetadataItems(diff --git a/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx b/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsxindex 000c85a08fb..ec614e83ab6 100644--- a/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx+++ b/packages/twenty-front/src/modules/settings/billing/components/UpdatePaymentMethodModal.tsx@@ -12,10 +12,14 @@ import { Dialog } from 'twenty-ui/primitives/surfaces';type UpdatePaymentMethodModalProps = {modalInstanceId: string;+ title?: string;+ description?: string;};export const UpdatePaymentMethodModal = ({modalInstanceId,+ title,+ description,}: UpdatePaymentMethodModalProps) => {const { t } = useLingui();const { closeDialog } = useDialog();@@ -52,9 +56,12 @@ export const UpdatePaymentMethodModal = ({data-globally-prevent-click-outside><Dialog.Header>- <Dialog.Title>{t`Update your payment method`}</Dialog.Title>+ <Dialog.Title>+ {title ?? t`Update your payment method`}+ </Dialog.Title><Dialog.Description>- {t`Add a card below to update your billing details and retry your payment.`}+ {description ??+ t`Add a card below to update your billing details and retry your payment.`}</Dialog.Description></Dialog.Header><Dialog.Body>diff --git a/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerIcon.ts b/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerIcon.tsindex 6a128ff17b1..a4adf27a5ef 100644--- a/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerIcon.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerIcon.ts@@ -1,7 +1,6 @@import { type WorkflowTrigger } from '@/workflow/types/Workflow';import { splitWorkflowTriggerEventName } from '@/workflow/utils/splitWorkflowTriggerEventName';-import { DATABASE_TRIGGER_TYPES } from '@/workflow/workflow-trigger/constants/DatabaseTriggerTypes';-import { OTHER_TRIGGER_TYPES } from '@/workflow/workflow-trigger/constants/OtherTriggerTypes';+import { getTriggerTypeIcon } from '@/workflow/workflow-trigger/utils/getTriggerTypeIcon';import { isNonEmptyString } from '@sniptt/guards';export const getTriggerIcon = (@@ -11,14 +10,11 @@ export const getTriggerIcon = (return trigger.settings.icon;}- if (trigger.type === 'DATABASE_EVENT') {- const eventName = splitWorkflowTriggerEventName(- trigger.settings.eventName,- ).event;-- return DATABASE_TRIGGER_TYPES.find((type) => type.event === eventName)- ?.icon;- }-- return OTHER_TRIGGER_TYPES.find((item) => item.type === trigger.type)?.icon;+ return getTriggerTypeIcon({+ type: trigger.type,+ databaseEvent:+ trigger.type === 'DATABASE_EVENT'+ ? splitWorkflowTriggerEventName(trigger.settings.eventName).event+ : undefined,+ });};diff --git a/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerTypeIcon.ts b/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerTypeIcon.tsnew file mode 100644index 00000000000..ce2ecb69e96--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-trigger/utils/getTriggerTypeIcon.ts@@ -0,0 +1,20 @@+import { DATABASE_TRIGGER_TYPES } from '@/workflow/workflow-trigger/constants/DatabaseTriggerTypes';+import { OTHER_TRIGGER_TYPES } from '@/workflow/workflow-trigger/constants/OtherTriggerTypes';++export const getTriggerTypeIcon = ({+ type,+ databaseEvent,+}: {+ type: string;+ databaseEvent: string | null | undefined;+}): string | undefined => {+ if (type === 'DATABASE_EVENT') {+ return DATABASE_TRIGGER_TYPES.find(+ (databaseTriggerType) => databaseTriggerType.event === databaseEvent,+ )?.icon;+ }++ return OTHER_TRIGGER_TYPES.find(+ (otherTriggerType) => otherTriggerType.type === type,+ )?.icon;+};diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-upgrade-version-command.module.tsindex 965aad97042..68d05a2a85d 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-upgrade-version-command.module.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-upgrade-version-command.module.ts@@ -8,6 +8,7 @@ import { AddAccessGroupStorageColumnsCommand } from 'src/database/commands/upgraimport { AddPrivateRecordColumnCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793436309311-add-private-record-column.command';import { MakeRestrictedRecordsPrivateCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793457458179-make-restricted-records-private.command';import { MakeChatThreadsPrivateRecordsCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793460623155-make-chat-threads-private-records.command';+import { UpdateDataManipulationSkillImportCheckCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793607354182-update-data-manipulation-skill-import-check.command';import { ApplicationModule } from 'src/engine/core-modules/application/application.module';import { WorkspaceSchemaManagerModule } from 'src/engine/twenty-orm/workspace-schema-manager/workspace-schema-manager.module';import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';@@ -29,6 +30,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspaceAddPrivateRecordColumnCommand,MakeRestrictedRecordsPrivateCommand,MakeChatThreadsPrivateRecordsCommand,+ UpdateDataManipulationSkillImportCheckCommand,],})export class V2_55_UpgradeVersionCommandModule {}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793607354182-update-data-manipulation-skill-import-check.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793607354182-update-data-manipulation-skill-import-check.command.tsnew file mode 100644index 00000000000..2d25e7f3fd7--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-workspace-command-1793607354182-update-data-manipulation-skill-import-check.command.ts@@ -0,0 +1,119 @@+import { Command } from 'nest-commander';+import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';+import { buildSkillContentReplacement } from 'src/database/commands/upgrade-version-command/2-54/utils/build-skill-content-replacement.util';+import { DATA_MANIPULATION_SKILL_CONTENT_BEFORE_IMPORT_CHECK_FIX } from 'src/database/commands/upgrade-version-command/2-55/constants/data-manipulation-skill-content-before-import-check-fix.constant';+import { ApplicationService } from 'src/engine/core-modules/application/application.service';+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { STANDARD_SKILL } from 'src/engine/workspace-manager/twenty-standard-application/constants/standard-skill.constant';+import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';++const DATA_MANIPULATION_SKILL_UNIVERSAL_IDENTIFIER =+ STANDARD_SKILL['data-manipulation'].universalIdentifier;++@RegisteredWorkspaceCommand('2.55.0', 1793607354182)+@Command({+ name: 'upgrade:2-55:update-data-manipulation-skill-import-check',+ description:+ 'Update the data-manipulation skill so a bulk import does not write its 2 check rows twice',+})+export class UpdateDataManipulationSkillImportCheckCommand extends ProvisionedWorkspaceCommandRunner {+ constructor(+ protected readonly workspaceIteratorService: WorkspaceIteratorService,+ private readonly applicationService: ApplicationService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,+ ) {+ super(workspaceIteratorService);+ }++ override async runOnWorkspace({+ workspaceId,+ options,+ }: RunOnWorkspaceArgs): Promise<void> {+ const { twentyStandardFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );++ const { flatSkillMaps } = await this.workspaceCacheService.getOrRecompute(+ workspaceId,+ ['flatSkillMaps'],+ );++ const { allFlatEntityMaps: standardAllFlatEntityMaps } =+ computeTwentyStandardApplicationAllFlatEntityMaps({+ now: new Date().toISOString(),+ workspaceId,+ twentyStandardApplicationId: twentyStandardFlatApplication.id,+ });++ const standardContent =+ standardAllFlatEntityMaps.flatSkillMaps.byUniversalIdentifier[+ DATA_MANIPULATION_SKILL_UNIVERSAL_IDENTIFIER+ ]?.content;++ if (!isDefined(standardContent)) {+ throw new Error(+ 'The data-manipulation skill is missing from the standard application definition',+ );+ }++ const skillToUpdate = buildSkillContentReplacement({+ skill:+ flatSkillMaps.byUniversalIdentifier[+ DATA_MANIPULATION_SKILL_UNIVERSAL_IDENTIFIER+ ],+ fromContent: DATA_MANIPULATION_SKILL_CONTENT_BEFORE_IMPORT_CHECK_FIX,+ toContent: standardContent,+ });++ if (!isDefined(skillToUpdate)) {+ this.logger.log(+ `The data-manipulation skill is missing or its content was edited in workspace ${workspaceId}, skipping`,+ );++ return;+ }++ this.logger.log(+ `${options.dryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId}: updating the data-manipulation skill content`,+ );++ if (options.dryRun) {+ return;+ }++ const result =+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(+ {+ shouldDeferActions: false,+ workspaceId,+ isSystemBuild: true,+ applicationUniversalIdentifier:+ TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER,+ allFlatEntityOperationByMetadataName: {+ skill: {+ flatEntityToCreate: [],+ flatEntityToDelete: [],+ flatEntityToUpdate: [skillToUpdate],+ },+ },+ },+ );++ if (result.status === 'fail') {+ throw new WorkspaceMigrationBuilderException(+ result,+ `Failed to update the data-manipulation skill for workspace ${workspaceId}`,+ );+ }+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/constants/data-manipulation-skill-content-before-import-check-fix.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/constants/data-manipulation-skill-content-before-import-check-fix.constant.tsnew file mode 100644index 00000000000..a27ee29fbc4--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/constants/data-manipulation-skill-content-before-import-check-fix.constant.ts@@ -0,0 +1,115 @@+export const DATA_MANIPULATION_SKILL_CONTENT_BEFORE_IMPORT_CHECK_FIX = `# Data Manipulation Skill++You explore and manage data across companies, people, opportunities, tasks, notes, and custom objects.++## Capabilities++- Search, filter, sort, create, update records+- Manage relationships between records+- Bulk operations and data analysis++## Constraints++- READ and WRITE access to all objects+- CANNOT delete records or access workflow objects+- CANNOT modify workspace settings++## Multi-step Approach++- Chain queries to solve complex requests (e.g., find companies → get their opportunities → calculate totals)+- If a query fails or returns no results, try alternative filters or approaches+- Validate data exists before referencing it (search before update)+- Use results from one query to inform the next+- Try 2-3 different approaches before giving up++## Sorting (Critical)++For "top N" queries, use orderBy with limit:+- Examples: orderBy: [{"employees": "DescNullsLast"}], orderBy: [{"createdAt": "AscNullsFirst"}]+- Valid directions: "AscNullsFirst", "AscNullsLast", "DescNullsFirst", "DescNullsLast"++## Before Bulk Operations++- Confirm the scope and impact+- Explain what will change++## Bulk Import++You import bulk data (CSV, Excel, spreadsheets, pasted tables) into records as cheaply and reliably as possible.++### Golden Rule: one code_interpreter run, not many tool calls++For anything beyond a handful of rows (>~50), do the ENTIRE import inside a SINGLE \`code_interpreter\` execution. Do NOT loop \`execute_tool\` from chat: every chat tool call re-sends the whole conversation as new input tokens, so dozens of small writes explode cost. Inside the sandbox the loop runs server-side and the agent only sees one small summary.++This means: read the file, parse it, inspect schemas, resolve IDs, write all records, and print the summary — all inside one \`code_interpreter\` call. Not two. Not five. One.++The sandbox exposes a pre-bound \`twenty\` object (see the code-interpreter skill). Use its bulk helpers instead of hand-rolling loops.++### Pre-flight: inspect schemas at the LLM level before entering the sandbox++**Before your first \`code_interpreter\` call**, use \`learn_tools\` at the LLM level (not inside the sandbox) to fetch the input schemas for every object you will create or update. For example, if importing companies, people, and opportunities:++\`\`\`+learn_tools(["create_one_company", "create_one_person", "create_one_opportunity"])+\`\`\`++This is free — it runs before the sandbox and does not add a code_interpreter round-trip. You will know the exact field names before writing any code. Do NOT call \`twenty.call_tool('learn_tools', ...)\` from inside the sandbox to learn schemas — that wastes a full sandbox round-trip per schema and pollutes the conversation context.++### Recipe++1. **Read the file robustly** with pandas (\`/home/user/{filename}\`). Real-world files have messy delimiters and ragged rows, so don't rely on defaults:+ \`\`\`python+ # Auto-detect the separator and skip malformed rows instead of crashing.+ df = pd.read_csv(path, sep=None, engine='python', on_bad_lines='skip', dtype=str)+ \`\`\`+ Read and parse the file in the same code cell — never split file reading across multiple \`code_interpreter\` calls.+ Inspect columns and a few rows once with \`df.head()\` — never re-dump the full frame.+2. **Use schemas learned at step 0.** You already know the field names from the pre-flight \`learn_tools\` call. Do not call \`twenty.call_tool('learn_tools', ...)\` inside the sandbox unless you genuinely missed a schema. If you do need it, call it once and cache the result in a Python variable.+3. **Resolve relations to IDs.** Relations link by ID, not by name. Build a lookup map ONCE for only the values referenced in the file:+ \`\`\`python+ company_ids = twenty.lookup_by('companies', 'name', df['company'].dropna().unique().tolist())+ \`\`\`+ Then set each row's relation via the scalar foreign key — NOT a nested object:+ \`\`\`python+ record['companyId'] = company_ids.get(row['company']) # correct+ # record['company'] = {'id': ...} # WRONG: rejected with+ # 'Relation "company" requires connect or disconnect operation'+ \`\`\`+ To-one relations are written by their \`<relation>Id\` scalar (e.g. \`companyId\`), or an explicit \`{'connect': {'id': ...}}\`. A bare nested \`{'id': ...}\` is rejected. Never read the whole related table.+4. **Resolve just-created IDs with a bounded \`lookup_by\` — never paginate the table.** \`bulk_upsert\` returns only a count summary (created / updated / failed), not the records, so to link subsequent records (e.g. people to the companies you just upserted) resolve the IDs you need with a \`lookup_by\` bounded to your own values:+ \`\`\`python+ # After upserting companies, resolve by name using lookup_by (bounded to your values, not the whole table)+ company_ids = twenty.lookup_by('companies', 'name', [r['name'] for r in company_records])+ # Then use company_ids to set companyId on person records+ \`\`\`+ Never paginate through hundreds of existing records with \`find_many_*\` to find the ones you just created.+5. **Confirm the mapping before writing.** Present the proposed column → field mapping to the user (source column → target field, relation strategy such as "Company matched by name → companyId", and any type coercions) and wait for them to confirm or adjust. Do not write anything before this confirmation.+6. **Silently validate the mapping with a 2-row upsert.** Inside the same \`code_interpreter\` run, upsert just 2 rows as an internal correctness check. This is NOT a user-facing step: do not announce or narrate it. Only surface it if it FAILS — then report the error and the offending mapping so it can be fixed before the full import.+7. **Write with bulk_upsert.** Prefer upsert so dedup on unique fields (e.g. email) is handled server-side and re-runs are idempotent:+ \`\`\`python+ summary = twenty.bulk_upsert('people', records)+ print(summary) # { 'created': 4000, 'updated': 380, 'upserted': 4380, 'failed': 0, 'errors': [] }+ \`\`\`+ \`bulk_upsert\` batches at 200 (the platform maximum) and paginates to completion. Never stop at "partial" — if some batches failed, report the count and retry the failed offsets.+8. **Report a compact summary only** — the \`created\` / \`updated\` / \`failed\` split plus a few sample errors. Never echo the created records back into the conversation.++### Anti-patterns — never do these++- **Reading a file across multiple sandbox calls.** Do \`print(content[:3000])\` then \`print(content[3000:])\` in separate calls? That is two wasted round-trips. Read once, parse once, in the same cell.+- **Calling \`twenty.call_tool('learn_tools', ...)\` inside the sandbox** to discover field names. Inspect schemas at the LLM level with \`learn_tools\` before entering the sandbox. Guessing a field name and fixing the failure (e.g. \`annualRecurringRevenue\` → 10 failed writes → re-fetch schema) costs one failed batch plus a round-trip.+- **Re-fetching records you just created** to build an ID map. Use \`lookup_by\` bounded to the values you need, not \`find_many_*\` with pagination through the whole table.+- **Looping \`find_many_*\` one record at a time** inside the sandbox to resolve IDs (N+1 pattern). Use \`lookup_by\` instead — it batches the query server-side.+- **Multiple \`code_interpreter\` calls for a single import.** Each extra call is a full sandbox round-trip that adds latency, costs tokens, and accumulates output in the conversation context. Everything from file reading to final summary belongs in one call.++### Key constraints++- Relations are linked by ID only via the scalar \`<relation>Id\` (e.g. \`companyId\`); there is no name-based relation mapping and a nested \`{'id': ...}\` is rejected. Resolve IDs with \`lookup_by\` first.+- Deduplicate via upsert on unique fields rather than pre-reading existing records. \`bulk_upsert\` already reports how many rows were \`created\` vs \`updated\`, so you do NOT need to scan the whole object first to detect duplicates — just upsert and read back the split.+- If a write fails with 'no permission to write field "X" on "Y"', that field is restricted for the current role. Drop that single field and continue importing the rest instead of retrying the same failing write.+- If the user says "import for me", do it programmatically with this recipe — do not just describe the in-app CSV UI.++### Keep each thread to one objective++Every tool round-trip re-sends the ENTIRE conversation (system prompt, loaded skills, and all prior tool inputs/outputs) as new input tokens, so a long thread makes every later step progressively more expensive. When the user finishes an import and moves on to a distinct objective (e.g. field configuration, segmentation, dashboards, or a second unrelated import), suggest starting a NEW thread for it rather than continuing in the same one, which resets the context and keeps cost low. Keep a single import (inspect, confirm, validate, write, report) within one thread.++Prioritize data integrity and provide clear feedback on operations performed.`;diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-billing-exempt-applications.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-billing-exempt-applications.constant.tsindex 875a4d192a7..18d617afee3 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-billing-exempt-applications.constant.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-billing-exempt-applications.constant.ts@@ -1,4 +1,4 @@-import { TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/application/application-marketplace/constants/twenty-public-app-universal-identifiers.constant';+import { TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/application';// These apps run on every imported record or subscribed event, so metering// each invocation would drain the free-tier allowance.diff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-featured-applications.constant.ts b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-featured-applications.constant.tsindex 7256b080509..790fd10a80c 100644--- a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-featured-applications.constant.ts+++ b/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/marketplace-featured-applications.constant.ts@@ -1,4 +1,4 @@-import { TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS } from 'src/engine/core-modules/application/application-marketplace/constants/twenty-public-app-universal-identifiers.constant';+import { TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS } from 'twenty-shared/application';export const MARKETPLACE_FEATURED_APPLICATIONS: {universalIdentifier: string;@@ -36,4 +36,9 @@ export const MARKETPLACE_FEATURED_APPLICATIONS: {sourcePackage: '@twentyhq/teams',position: 6,},+ {+ universalIdentifier: TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS.FATHOM,+ sourcePackage: '@twentyhq/fathom',+ position: 7,+ },];diff --git a/packages/twenty-server/src/engine/core-modules/company-enrichment/services/company-enrichment.service.ts b/packages/twenty-server/src/engine/core-modules/company-enrichment/services/company-enrichment.service.tsindex a4bc113bab0..6ce35d0e553 100644--- a/packages/twenty-server/src/engine/core-modules/company-enrichment/services/company-enrichment.service.ts+++ b/packages/twenty-server/src/engine/core-modules/company-enrichment/services/company-enrichment.service.ts@@ -15,6 +15,10 @@ import {COMPANY_ENRICHMENT_ATTEMPT_KEY,type CompanyEnrichmentAttemptKeyValueTypeMap,} from 'src/engine/core-modules/company-enrichment/types/company-enrichment-attempt-key-value.type';+import {+ COMPANY_ENRICHMENT_KEY,+ type CompanyEnrichmentKeyValueTypeMap,+} from 'src/engine/core-modules/company-enrichment/types/company-enrichment-key-value.type';import { type PeopleDataLabsCompanyData } from 'src/engine/core-modules/company-enrichment/types/people-data-labs-company-data.type';import { type PeopleDataLabsEnrichResult } from 'src/engine/core-modules/company-enrichment/types/people-data-labs-enrich-result.type';import { toWorkspaceCompanyEnrichment } from 'src/engine/core-modules/company-enrichment/utils/to-workspace-company-enrichment.util';@@ -36,7 +40,9 @@ export class CompanyEnrichmentService {private readonly peopleDataLabsClientService: PeopleDataLabsClientService,private readonly twentyConfigService: TwentyConfigService,private readonly enrichmentThrottleService: EnrichmentThrottleService,- private readonly keyValuePairService: KeyValuePairService<CompanyEnrichmentAttemptKeyValueTypeMap>,+ private readonly keyValuePairService: KeyValuePairService<+ CompanyEnrichmentAttemptKeyValueTypeMap & CompanyEnrichmentKeyValueTypeMap+ >,) {}async enrichCompanyForWorkspaceCreator({@@ -97,6 +103,14 @@ export class CompanyEnrichmentService {await this.recordEnrichmentAttempt({ workspaceId, domain, result });}+ if (enrichmentResult.outcome === 'matched') {+ await this.storeEnrichment({+ workspaceId,+ domain,+ enrichment: enrichmentResult.enrichment,+ });+ }+return enrichmentResult;}@@ -182,4 +196,30 @@ export class CompanyEnrichmentService {);}}++ private async storeEnrichment({+ workspaceId,+ domain,+ enrichment,+ }: {+ workspaceId: string;+ domain: string;+ enrichment: WorkspaceCompanyEnrichment;+ }): Promise<void> {+ try {+ await this.keyValuePairService.set({+ userId: null,+ workspaceId,+ key: COMPANY_ENRICHMENT_KEY,+ value: enrichment,+ type: KeyValuePairType.CONFIG_VARIABLE,+ });+ } catch (error) {+ this.logger.warn(+ `Failed to store company enrichment for workspace ${workspaceId} (${domain}): ${+ error instanceof Error ? error.message : String(error)+ }`,+ );+ }+ }}diff --git a/packages/twenty-server/src/engine/core-modules/company-enrichment/types/company-enrichment-key-value.type.ts b/packages/twenty-server/src/engine/core-modules/company-enrichment/types/company-enrichment-key-value.type.tsnew file mode 100644index 00000000000..ba84fae8050--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/company-enrichment/types/company-enrichment-key-value.type.ts@@ -0,0 +1,7 @@+import { type WorkspaceCompanyEnrichment } from 'twenty-shared/workspace';++export const COMPANY_ENRICHMENT_KEY = 'COMPANY_ENRICHMENT';++export type CompanyEnrichmentKeyValueTypeMap = {+ [COMPANY_ENRICHMENT_KEY]: WorkspaceCompanyEnrichment;+};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.tsindex 93875636e9a..7f77cb78230 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/skill-metadata/create-standard-flat-skill-metadata.util.ts@@ -260,14 +260,14 @@ This is free — it runs before the sandbox and does not add a code_interpreter\`\`\`Never paginate through hundreds of existing records with \`find_many_*\` to find the ones you just created.5. **Confirm the mapping before writing.** Present the proposed column → field mapping to the user (source column → target field, relation strategy such as "Company matched by name → companyId", and any type coercions) and wait for them to confirm or adjust. Do not write anything before this confirmation.-6. **Silently validate the mapping with a 2-row upsert.** Inside the same \`code_interpreter\` run, upsert just 2 rows as an internal correctness check. This is NOT a user-facing step: do not announce or narrate it. Only surface it if it FAILS — then report the error and the offending mapping so it can be fixed before the full import.-7. **Write with bulk_upsert.** Prefer upsert so dedup on unique fields (e.g. email) is handled server-side and re-runs are idempotent:+6. **Silently validate the mapping with a 2-row upsert.** Inside the same \`code_interpreter\` run, upsert just the first 2 rows as an internal correctness check. This is NOT a user-facing step: do not announce or narrate it. Only surface it if it FAILS — then report the error and the offending mapping so it can be fixed before the full import.+7. **Write the remaining rows with bulk_upsert.** Write \`records[2:]\`, never the full list again: objects without a unique field (opportunities, tasks, notes, most custom objects) cannot dedupe, so the 2 check rows would be created twice. Prefer upsert so dedup on unique fields (e.g. email) is handled server-side and re-runs are idempotent:\`\`\`python- summary = twenty.bulk_upsert('people', records)+ summary = twenty.bulk_upsert('people', records[2:])print(summary) # { 'created': 4000, 'updated': 380, 'upserted': 4380, 'failed': 0, 'errors': [] }\`\`\`\`bulk_upsert\` batches at 200 (the platform maximum) and paginates to completion. Never stop at "partial" — if some batches failed, report the count and retry the failed offsets.-8. **Report a compact summary only** — the \`created\` / \`updated\` / \`failed\` split plus a few sample errors. Never echo the created records back into the conversation.+8. **Report a compact summary only** — the \`created\` / \`updated\` / \`failed\` split plus a few sample errors. Add the 2 check rows' \`created\` / \`updated\` counts so the totals cover every row. Never echo the created records back into the conversation.### Anti-patterns — never do thesediff --git a/packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/twenty-public-app-universal-identifiers.constant.ts b/packages/twenty-shared/src/application/constants/TwentyPublicAppUniversalIdentifiers.tssimilarity index 100%rename from packages/twenty-server/src/engine/core-modules/application/application-marketplace/constants/twenty-public-app-universal-identifiers.constant.tsrename to packages/twenty-shared/src/application/constants/TwentyPublicAppUniversalIdentifiers.tsdiff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.tsindex 6ad8621a2d7..b4c8860854d 100644--- a/packages/twenty-shared/src/application/index.ts+++ b/packages/twenty-shared/src/application/index.ts@@ -98,6 +98,7 @@ export { GENERATED_DIR } from './constants/GeneratedDirectory';export { MINIMUM_UNIVERSAL_IDENTIFIER_UUID_VERSION } from './constants/MinimumUniversalIdentifierUuidVersion';export { NODE_ESM_CJS_BANNER } from './constants/NodeEsmCjsBanner';export { OUTPUT_DIR } from './constants/OutputDirectory';+export { TWENTY_PUBLIC_APP_UNIVERSAL_IDENTIFIERS } from './constants/TwentyPublicAppUniversalIdentifiers';export { TWENTY_STANDARD_APPLICATION_NAME } from './constants/TwentyStandardApplicationName';export { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from './constants/TwentyStandardApplicationUniversalIdentifier';export type {