Skip to content

The open alternative to Salesforce, designed for AI.

Create temporary AI chat drafts with mocked previews (#28470)

Weikobe8fc79c5179
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 7bdf84f76a0..3c7490a7daa 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2312,6 +2312,7 @@ type FeatureFlag {
}
enum FeatureFlagKey {
+ IS_AI_CHAT_COMPONENT_BUILDER_ENABLED
IS_AI_CHAT_INBOX_ENABLED
IS_APP_PREFERENCES_ENABLED
IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 4b6db88831c..4d2d42c2018 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1524,7 +1524,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_AI_CHAT_INBOX_ENABLED' | 'IS_APP_PREFERENCES_ENABLED' | 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_MCP_SERVERS_ENABLED' | 'IS_PRIVATE_RECORD_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_RELATED_RECORD_PATHS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_ROW_LEVEL_PERMISSION_RELATION_HOP_ENABLED'
+export type FeatureFlagKey = 'IS_AI_CHAT_COMPONENT_BUILDER_ENABLED' | 'IS_AI_CHAT_INBOX_ENABLED' | 'IS_APP_PREFERENCES_ENABLED' | 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_MCP_SERVERS_ENABLED' | 'IS_PRIVATE_RECORD_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_RELATED_RECORD_PATHS_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_ROW_LEVEL_PERMISSION_RELATION_HOP_ENABLED'
export interface Field {
applicationId: Scalars['UUID']
@@ -12365,6 +12365,7 @@ export const enumEventLogTable = {
}
export const enumFeatureFlagKey = {
+ IS_AI_CHAT_COMPONENT_BUILDER_ENABLED: 'IS_AI_CHAT_COMPONENT_BUILDER_ENABLED' as const,
IS_AI_CHAT_INBOX_ENABLED: 'IS_AI_CHAT_INBOX_ENABLED' as const,
IS_APP_PREFERENCES_ENABLED: 'IS_APP_PREFERENCES_ENABLED' as const,
IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED: 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED' as const,
diff --git a/packages/twenty-front-component-renderer/src/host/component-source/utils/__tests__/createMockSdkClientSources.test.ts b/packages/twenty-front-component-renderer/src/host/component-source/utils/__tests__/createMockSdkClientSources.test.ts
new file mode 100644
index 00000000000..37794dd57ba
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/component-source/utils/__tests__/createMockSdkClientSources.test.ts
@@ -0,0 +1,41 @@
+import { createMockSdkClientSources } from '../createMockSdkClientSources';
+
+const loadModule = (
+ source: string,
+): {
+ CoreApiClient: new () => {
+ query: () => Promise<unknown>;
+ mutation: () => Promise<never>;
+ };
+ MetadataApiClient: new () => object;
+} =>
+ new Function(`${source.replace('export class', 'class')}; return {
+ CoreApiClient: typeof CoreApiClient === 'undefined' ? undefined : CoreApiClient,
+ MetadataApiClient: typeof MetadataApiClient === 'undefined' ? undefined : MetadataApiClient,
+ };`)();
+
+describe('createMockSdkClientSources', () => {
+ it('returns sample query results without executing embedded strings', async () => {
+ const result = {
+ companies: {
+ edges: [{ node: { name: `"; throw new Error('injected'); //` } }],
+ },
+ };
+ const { core } = createMockSdkClientSources(result);
+ const client = new (loadModule(core).CoreApiClient)();
+
+ expect(await client.query()).toEqual(result);
+ });
+
+ it('rejects writes and metadata access in previews', async () => {
+ const { core, metadata } = createMockSdkClientSources({});
+ const client = new (loadModule(core).CoreApiClient)();
+
+ await expect(client.mutation()).rejects.toThrow(
+ 'Mutations are unavailable',
+ );
+ expect(() => new (loadModule(metadata).MetadataApiClient)()).toThrow(
+ 'Metadata API calls are unavailable',
+ );
+ });
+});
diff --git a/packages/twenty-front-component-renderer/src/host/component-source/utils/createMockSdkClientSources.ts b/packages/twenty-front-component-renderer/src/host/component-source/utils/createMockSdkClientSources.ts
new file mode 100644
index 00000000000..e08acb433a9
--- /dev/null
+++ b/packages/twenty-front-component-renderer/src/host/component-source/utils/createMockSdkClientSources.ts
@@ -0,0 +1,13 @@
+import { type SdkClientSources } from '@/types/SdkClientSources';
+
+export const createMockSdkClientSources = (
+ queryResult: Record<string, unknown>,
+): SdkClientSources => ({
+ core: `export class CoreApiClient {
+ async query() { return ${JSON.stringify(queryResult)}; }
+ async mutation() { throw new Error('Mutations are unavailable in previews.'); }
+ }`,
+ metadata: `export class MetadataApiClient {
+ constructor() { throw new Error('Metadata API calls are unavailable in previews.'); }
+ }`,
+});
diff --git a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
index d765a02c759..7db06acd851 100644
--- a/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
+++ b/packages/twenty-front-component-renderer/src/host/components/FrontComponentRenderer.tsx
@@ -22,6 +22,7 @@ import { FrontComponentUpdateHostCommunicationApiEffect } from '@/host/effect-co
import { type FrontComponentMediaSessionHost } from '@/host/media/types/FrontComponentMediaSessionHost';
import { type FrontComponentHostCommunicationApi } from '@/types/FrontComponentHostCommunicationApi';
import { type FrontComponentThread } from '@/types/FrontComponentThread';
+import { type SdkClientSources } from '@/types/SdkClientSources';
import { type SdkClientUrls } from '@/types/SdkClientUrls';
import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
import { type RemoteReceiver } from '@remote-dom/react/host';
@@ -48,6 +49,7 @@ type FrontComponentRendererProps = {
apiUrl?: string;
functionsBaseUrl?: string;
sdkClientUrls?: SdkClientUrls;
+ sdkClientSources?: SdkClientSources;
sharedDependenciesUrl?: string;
applicationVariables?: Record<string, string>;
storageNamespace?: string;
@@ -69,6 +71,7 @@ export const FrontComponentRenderer = ({
apiUrl,
functionsBaseUrl,
sdkClientUrls,
+ sdkClientSources,
sharedDependenciesUrl,
applicationVariables,
storageNamespace,
@@ -126,6 +129,7 @@ export const FrontComponentRenderer = ({
apiUrl={apiUrl}
functionsBaseUrl={functionsBaseUrl}
sdkClientUrls={sdkClientUrls}
+ sdkClientSources={sdkClientSources}
sharedDependenciesUrl={sharedDependenciesUrl}
applicationVariables={applicationVariables}
storageNamespace={storageNamespace}
diff --git a/packages/twenty-front-component-renderer/src/host/components/FrontComponentSourceRenderer.tsx b/packages/twenty-front-component-renderer/src/host/components/FrontComponentSourceRenderer.tsx
index 9ef71c06176..e35778f54e5 100644
--- a/packages/twenty-front-component-renderer/src/host/components/FrontComponentSourceRenderer.tsx
+++ b/packages/twenty-front-component-renderer/src/host/components/FrontComponentSourceRenderer.tsx
@@ -1,5 +1,7 @@
import { useMemo } from 'react';
+import { createMockSdkClientSources } from '@/host/component-source/utils/createMockSdkClientSources';
+
import { FrontComponentRenderer } from '@/host/components/FrontComponentRenderer';
import { FRONT_COMPONENT_HOST_COMMUNICATION_API_NOOP } from '@/host/thread/constants/FrontComponentHostCommunicationApiNoop';
@@ -7,7 +9,7 @@ type FrontComponentSourceRendererProps = {
componentId: string;
componentSource: string;
sharedDependenciesSource?: string;
- data: Record<string, unknown>;
+ mockQueryResult: Record<string, unknown>;
colorScheme: 'light' | 'dark';
onReady?: () => void;
onError: (error?: Error) => void;
@@ -17,11 +19,15 @@ export const FrontComponentSourceRenderer = ({
componentId,
componentSource,
sharedDependenciesSource,
- data,
+ mockQueryResult,
colorScheme,
onReady,
onError,
}: FrontComponentSourceRendererProps) => {
+ const sdkClientSources = useMemo(
+ () => createMockSdkClientSources(mockQueryResult),
+ [mockQueryResult],
+ );
const executionContext = useMemo(
() => ({
frontComponentId: componentId,
@@ -39,7 +45,7 @@ export const FrontComponentSourceRenderer = ({
componentUrl={`about:blank#${componentId}`}
componentSource={componentSource}
sharedDependenciesSource={sharedDependenciesSource}
- componentProps={data}
+ sdkClientSources={sdkClientSources}
executionContext={executionContext}
frontComponentHostCommunicationApi={
FRONT_COMPONENT_HOST_COMMUNICATION_API_NOOP
diff --git a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
index b361e7064ff..1213043f9cd 100644
--- a/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
+++ b/packages/twenty-front-component-renderer/src/host/effect-components/FrontComponentWorkerEffect.tsx
@@ -24,6 +24,7 @@ import { createFrontComponentSandboxMessageHandler } from '@/remote/sandbox/util
import { type FrontComponentExecutionContext } from 'twenty-sdk/front-component';
import { type FrontComponentThread } from '@/types/FrontComponentThread';
+import { type SdkClientSources } from '@/types/SdkClientSources';
import { type SdkClientUrls } from '@/types/SdkClientUrls';
import { buildAuthorizationHeadersFromAccessToken } from '@/host/component-source/utils/buildAuthorizationHeadersFromAccessToken';
import { containsSdkClientImportSpecifier } from '@/utils/module-imports/containsSdkClientImportSpecifier';
@@ -39,6 +40,7 @@ type FrontComponentWorkerEffectProps = {
apiUrl?: string;
functionsBaseUrl?: string;
sdkClientUrls?: SdkClientUrls;
+ sdkClientSources?: SdkClientSources;
sharedDependenciesUrl?: string;
applicationVariables?: Record<string, string>;
storageNamespace?: string;
@@ -66,6 +68,7 @@ export const FrontComponentWorkerEffect = ({
apiUrl,
functionsBaseUrl,
sdkClientUrls,
+ sdkClientSources: providedSdkClientSources,
sharedDependenciesUrl,
applicationVariables,
storageNamespace,
@@ -175,13 +178,14 @@ export const FrontComponentWorkerEffect = ({
};
const [sdkClientSources, sharedDependenciesSource] = await Promise.all([
- isDefined(sdkClientUrls) &&
- containsSdkClientImportSpecifier(componentSource)
- ? fetchSdkClientSources({
- sdkClientUrls,
- headers: authorizationHeaders,
- })
- : undefined,
+ providedSdkClientSources ??
+ (isDefined(sdkClientUrls) &&
+ containsSdkClientImportSpecifier(componentSource)
+ ? fetchSdkClientSources({
+ sdkClientUrls,
+ headers: authorizationHeaders,
+ })
+ : undefined),
resolveSharedDependenciesSource(),
]);
@@ -251,6 +255,7 @@ export const FrontComponentWorkerEffect = ({
}, [
componentUrl,
providedComponentSource,
+ providedSdkClientSources,
stableComponentProps,
providedSharedDependenciesSource,
applicationAccessToken,
diff --git a/packages/twenty-front-component-renderer/src/host/effect-components/__tests__/FrontComponentWorkerEffect.test.ts b/packages/twenty-front-component-renderer/src/host/effect-components/__tests__/FrontComponentWorkerEffect.test.ts
index c59c4a6a03f..9d315640958 100644
--- a/packages/twenty-front-component-renderer/src/host/effect-components/__tests__/FrontComponentWorkerEffect.test.ts
+++ b/packages/twenty-front-component-renderer/src/host/effect-components/__tests__/FrontComponentWorkerEffect.test.ts
@@ -163,6 +163,40 @@ describe('FrontComponentWorkerEffect', () => {
return renderEffect;
};
+ it('renders supplied SDK sources without granting network or app credentials', async () => {
+ const render = jest.fn().mockResolvedValue(undefined);
+ mockThreadRender(render);
+ const setError = jest.fn();
+ const rerender = mountEffect({ setReceiver: jest.fn(), setError });
+ await flushPendingWork();
+ jest.mocked(fetchComponentSource).mockClear();
+ render.mockClear();
+ const sdkClientSources = {
+ core: 'export class CoreApiClient {}',
+ metadata: 'export class MetadataApiClient {}',
+ };
+
+ rerender({
+ componentUrl: 'about:blank#preview',
+ componentSource:
+ 'import { CoreApiClient } from "twenty-client-sdk/core";',
+ sdkClientSources,
+ });
+ await flushPendingWork();
+
+ expect(fetchComponentSource).not.toHaveBeenCalled();
+ expect(setError).toHaveBeenLastCalledWith(null);
+ expect(render).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ sdkClientSources,
+ hostFetchOrigins: [],
+ applicationAccessToken: undefined,
+ apiUrl: undefined,
+ }),
+ );
+ });
+
it('keeps the receiver connected while waiting for readiness', async () => {
const { render, resolveRender } = createDeferredRender();
mockThreadRender(render);
diff --git a/packages/twenty-front/src/generated-admin/schema.ts b/packages/twenty-front/src/generated-admin/schema.ts
index 13d91b1bba5..51f2b414d25 100644
--- a/packages/twenty-front/src/generated-admin/schema.ts
+++ b/packages/twenty-front/src/generated-admin/schema.ts
@@ -537,6 +537,7 @@ export type FeatureFlag = {
};
export enum FeatureFlagKey {
+ IS_AI_CHAT_COMPONENT_BUILDER_ENABLED = 'IS_AI_CHAT_COMPONENT_BUILDER_ENABLED',
IS_AI_CHAT_INBOX_ENABLED = 'IS_AI_CHAT_INBOX_ENABLED',
IS_APP_PREFERENCES_ENABLED = 'IS_APP_PREFERENCES_ENABLED',
IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED = 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/schema.ts b/packages/twenty-front/src/generated-metadata/schema.ts
index a3f64107b09..a5fed96e000 100644
--- a/packages/twenty-front/src/generated-metadata/schema.ts
+++ b/packages/twenty-front/src/generated-metadata/schema.ts
@@ -2444,6 +2444,7 @@ export type FeatureFlag = {
};
export enum FeatureFlagKey {
+ IS_AI_CHAT_COMPONENT_BUILDER_ENABLED = 'IS_AI_CHAT_COMPONENT_BUILDER_ENABLED',
IS_AI_CHAT_INBOX_ENABLED = 'IS_AI_CHAT_INBOX_ENABLED',
IS_APP_PREFERENCES_ENABLED = 'IS_APP_PREFERENCES_ENABLED',
IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED = 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED',
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index 02f9cd24d93..7fd43d91b62 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -28,6 +28,10 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Record<
label: msg`Share calendar events across channels`,
description: msg`Store a meeting synced by several calendars of the same provider once, instead of once per calendar.`,
},
+ [FeatureFlagKey.IS_AI_CHAT_COMPONENT_BUILDER_ENABLED]: {
+ label: msg`AI chat component builder`,
+ description: msg`Create and preview frontend components in AI chat before adding them to the Workspace app.`,
+ },
[FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED]: {
label: msg`AI chat inbox`,
description: msg`Turn the AI tab into an inbox to triage, assign, snooze and follow chats, let workflows send messages and agent questions to a member's inbox, and show a Conversations tab on record pages.`,
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-instance-command-slow-1793462047826-index-temporary-file-expiration.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-instance-command-slow-1793462047826-index-temporary-file-expiration.ts
new file mode 100644
index 00000000000..a59c465171a
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-55/2-55-instance-command-slow-1793462047826-index-temporary-file-expiration.ts
@@ -0,0 +1,27 @@
+import { type DataSource, type QueryRunner } from 'typeorm';
+
+import { createCoreIndexConcurrently } from 'src/database/commands/upgrade-version-command/2-46/utils/create-core-index-concurrently.util';
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { type SlowInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/slow-instance-command.interface';
+
+const INDEX_NAME = 'IDX_FILE_TEMPORARY_EXPIRES_AT';
+const CREATE_INDEX_QUERY = `CREATE INDEX IF NOT EXISTS "${INDEX_NAME}" ON "core"."file" (("settings"->>'expiresAt')) WHERE "status" = 'UPLOADED' AND "workspaceId" IS NOT NULL AND "deletedAt" IS NULL AND "settings" @> '{"isTemporaryFile":true}'`;
+
+@RegisteredInstanceCommand('2.55.0', 1793462047826, { type: 'slow' })
+export class IndexTemporaryFileExpirationSlowInstanceCommand implements SlowInstanceCommand {
+ async runDataMigration(dataSource: DataSource): Promise<void> {
+ await createCoreIndexConcurrently({
+ dataSource,
+ indexName: INDEX_NAME,
+ createIndexQuery: CREATE_INDEX_QUERY,
+ });
+ }
+
+ async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(CREATE_INDEX_QUERY);
+ }
+
+ async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(`DROP INDEX IF EXISTS "core"."${INDEX_NAME}"`);
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index fe8c860c274..b35be06fd24 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -276,6 +276,7 @@ import { AddWorkspaceIframeMediaPermissionsFastInstanceCommand } from 'src/datab
import { RenameWorkspaceAllowedIframeOriginsToAllowedEmbeddingOriginsFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-instance-command-fast-1793371022971-rename-workspace-allowed-iframe-origins-to-allowed-embedding-origins';
import { AddRelatedRecordPathIsInherentFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-instance-command-fast-1793375358574-add-related-record-path-is-inherent';
import { AddRelationFieldMetadataIdToRowLevelPermissionPredicateFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-instance-command-fast-1793381326752-add-relation-field-metadata-id-to-row-level-permission-predicate';
+import { IndexTemporaryFileExpirationSlowInstanceCommand } from 'src/database/commands/upgrade-version-command/2-55/2-55-instance-command-slow-1793462047826-index-temporary-file-expiration';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -554,4 +555,5 @@ export const INSTANCE_COMMANDS = [
RenameWorkspaceAllowedIframeOriginsToAllowedEmbeddingOriginsFastInstanceCommand,
AddRelatedRecordPathIsInherentFastInstanceCommand,
AddRelationFieldMetadataIdToRowLevelPermissionPredicateFastInstanceCommand,
+ IndexTemporaryFileExpirationSlowInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
index 0297e75f0b5..e7ad4379bff 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/__tests__/local.driver.spec.ts
@@ -1,6 +1,7 @@
import {
mkdtemp,
mkdir,
+ open,
readFile,
readdir,
rm,
@@ -82,6 +83,37 @@ describe('LocalDriver', () => {
await expect(readFile(outsideFilePath, 'utf8')).resolves.toBe('outside');
});
+ it('should preserve an active read when replacing a file', async () => {
+ const storagePath = await createTempDirectory('local-driver-storage-');
+ const driver = new LocalDriver({ storagePath });
+ const filePath = 'workspace/app/draft.json';
+ const original = JSON.stringify({ source: 'original' });
+ const replacement = JSON.stringify({ source: 'replacement' });
+
+ await driver.writeFile({
+ filePath,
+ sourceFile: original,
+ mimeType: 'application/json',
+ });
+
+ const activeRead = await open(path.join(storagePath, filePath));
+
+ try {
+ await driver.writeFile({
+ filePath,
+ sourceFile: Buffer.from(replacement),
+ mimeType: 'application/json',
+ });
+
+ await expect(activeRead.readFile('utf8')).resolves.toBe(original);
+ await expect(
+ readFile(path.join(storagePath, filePath), 'utf8'),
+ ).resolves.toBe(replacement);
+ } finally {
+ await activeRead.close();
+ }
+ });
+
it('should reject downloadFile when path resolves outside storage', async () => {
const storagePath = await createTempDirectory('local-driver-storage-');
const outsidePath = await createTempDirectory('local-driver-outside-');
diff --git a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
index 61aa97169ff..7aa1a09b4b3 100644
--- a/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
+++ b/packages/twenty-server/src/engine/core-modules/file-storage/drivers/local.driver.ts
@@ -7,7 +7,7 @@ import {
} from 'fs';
import * as fs from 'fs/promises';
import path, { dirname, join } from 'path';
-import { type Readable } from 'stream';
+import { Readable } from 'stream';
import { pipeline } from 'stream/promises';
import { Logger } from '@nestjs/common';
@@ -169,11 +169,11 @@ export class LocalDriver implements StorageDriver {
sourceFile: Buffer | Uint8Array | string;
mimeType: string | undefined;
}): Promise<void> {
- const realFilePath = await this.resolveWritableRealPathOrThrow(
- params.filePath,
- );
-
- await fs.writeFile(realFilePath, params.sourceFile);
+ await this.writeFileStream({
+ filePath: params.filePath,
+ stream: Readable.from([params.sourceFile]),
+ mimeType: params.mimeType,
+ });
}
async writeFileStream(params: {
diff --git a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
index 768d77cc479..3e7e7f218b5 100644
--- a/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/entities/file.entity.ts
@@ -41,6 +41,7 @@ import { nullableBigintColumnTransformer } from 'src/engine/twenty-orm/utils/nul
)
@Index('IDX_FILE_WORKSPACE_ID', ['workspaceId'])
@Index('IDX_FILE_STATUS', ['status'])
+@Index('IDX_FILE_TEMPORARY_EXPIRES_AT', { synchronize: false })
@Unique('IDX_FILE_APPLICATION_ID_WORKSPACE_ID_PATH_UNIQUE', [
'applicationId',
'workspaceId',
diff --git a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
index fff9df6a78c..8e03eaf3a0a 100644
--- a/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/file-upload/services/pending-file-cleanup.service.ts
@@ -3,10 +3,14 @@ import { InjectRepository } from '@nestjs/typeorm';
import { FileFolder } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
-import { IsNull, LessThan, Like, Not, Repository } from 'typeorm';
+import { In, IsNull, LessThan, Like, Not, Repository } from 'typeorm';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import {
+ FileException,
+ FileExceptionCode,
+} from 'src/engine/core-modules/file/file.exception';
import { FileEntity } from 'src/engine/core-modules/file/entities/file.entity';
import {
PENDING_FILE_CLEANUP_BATCH_SIZE,
@@ -55,18 +59,52 @@ export class PendingFileCleanupService {
take: PENDING_FILE_CLEANUP_BATCH_SIZE,
});
+ if (staleFiles.length < PENDING_FILE_CLEANUP_BATCH_SIZE) {
+ const expiredTemporaryFiles = await this.fileRepository
+ .createQueryBuilder('file')
+ .where({
+ status: FILE_STATUS.UPLOADED,
+ workspaceId: Not(IsNull()),
+ id: Not(In(staleFiles.map((file) => file.id))),
+ })
+ .andWhere(`"file"."settings" @> '{"isTemporaryFile":true}'`)
+ .andWhere(`"file"."settings"->>'expiresAt' <= :now`, {
+ now: new Date().toISOString(),
+ })
+ .orderBy(`"file"."settings"->>'expiresAt'`)
+ .take(PENDING_FILE_CLEANUP_BATCH_SIZE - staleFiles.length)
+ .getMany();
+
+ staleFiles.push(...expiredTemporaryFiles);
+ }
+
+ const fileFolders = Object.values(FileFolder);
let deletedCount = 0;
for (const file of staleFiles) {
try {
if (
- file.path.startsWith(`${FileFolder.RecordExport}/`) &&
+ (file.path.startsWith(`${FileFolder.RecordExport}/`) ||
+ (file.status === FILE_STATUS.UPLOADED &&
+ file.settings?.isTemporaryFile &&
+ isDefined(file.settings.expiresAt))) &&
isDefined(file.workspaceId)
) {
+ const fileFolder = fileFolders.find(
+ (folder) => folder === file.path.split('/')[0],
+ );
+
+ if (!isDefined(fileFolder)) {
+ throw new FileException(
+ `Invalid folder for stale file ${file.id}`,
+ FileExceptionCode.INVALID_FILE_FOLDER,
+ );
+ }
+
await this.fileStorageService.deleteByFileId({
fileId: file.id,
workspaceId: file.workspaceId,
- fileFolder: FileFolder.RecordExport,
+ fileFolder,
});
deletedCount++;
diff --git a/packages/twenty-server/src/engine/core-modules/file/types/file-settings.type.ts b/packages/twenty-server/src/engine/core-modules/file/types/file-settings.type.ts
index 5b1512824f8..df51f7eb430 100644
--- a/packages/twenty-server/src/engine/core-modules/file/types/file-settings.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/file/types/file-settings.type.ts
@@ -3,4 +3,6 @@ export type FileFieldSettings = {
toDelete: boolean;
};
-export type FileSettings = FileFieldSettings;
+export type FileSettings = FileFieldSettings & {
+ expiresAt?: string;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.controller.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.controller.ts
new file mode 100644
index 00000000000..c6698e3d9e9
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.controller.ts
@@ -0,0 +1,100 @@
+import { msg } from '@lingui/core/macro';
+import { z } from 'zod';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { ApplicationRestApiExceptionFilter } from 'src/engine/core-modules/application/application-rest-api-exception.filter';
+import {
+ Body,
+ Controller,
+ Get,
+ Header,
+ Param,
+ ParseUUIDPipe,
+ Post,
+ UseGuards,
+ UseFilters,
+} from '@nestjs/common';
+import { ApiPath } from 'twenty-shared/types';
+import { doNotTranslate } from 'twenty-shared/i18n';
+
+import { getWorkspaceAuthContext } from 'src/engine/core-modules/auth/storage/workspace-auth-context.storage';
+import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
+import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { AiFrontComponentService } from 'src/engine/metadata-modules/ai/ai-front-component/ai-front-component.service';
+
+@Controller(`${ApiPath.Rest}/ai-front-components`)
+@UseFilters(ApplicationRestApiExceptionFilter)
+export class AiFrontComponentController {
+ constructor(private readonly components: AiFrontComponentService) {}
+
+ @Get('drafts/:draftId')
+ @Header('Cache-Control', 'no-store')
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ NoPermissionGuard,
+ )
+ getPreview(
+ @Param('draftId', ParseUUIDPipe) draftId: string,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ ) {
+ return this.components.getPreview({
+ userWorkspaceId,
+ draftId,
+ authContext: getWorkspaceAuthContext(),
+ });
+ }
+
+ @Post('drafts/:draftId/preview-error')
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: true,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ NoPermissionGuard,
+ )
+ reportPreviewError(
+ @Param('draftId', ParseUUIDPipe) draftId: string,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthUserWorkspaceId() userWorkspaceId: string,
+ @Body('message') message: unknown,
+ ) {
+ const validation = z.string().min(1).max(2000).safeParse(message);
+
+ if (!validation.success) {
+ throw new ApplicationException(
+ doNotTranslate('Invalid preview error message.'),
+ ApplicationExceptionCode.INVALID_INPUT,
+ { userFriendlyMessage: msg`Invalid preview error message.` },
+ );
+ }
+
+ return this.components.reportPreviewError({
+ workspaceId: workspace.id,
+ userWorkspaceId,
+ draftId,
+ previewError: validation.data,
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.module.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.module.ts
new file mode 100644
index 00000000000..87216d00ec9
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.module.ts
@@ -0,0 +1,32 @@
+import { Module } from '@nestjs/common';
+import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
+
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';
+import { PermissionsModule } from 'src/engine/permissions/permissions.module';
+import { ApplicationPackageModule } from 'src/engine/core-modules/application/application-package/application-package.module';
+import { WorkspaceFrontComponentDependenciesService } from 'src/engine/metadata-modules/ai/ai-front-component/workspace-front-component-dependencies.service';
+import { FrontComponentCompilerService } from 'src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service';
+import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
+import { RecordCrudModule } from 'src/engine/core-modules/record-crud/record-crud.module';
+import { AiFrontComponentController } from 'src/engine/metadata-modules/ai/ai-front-component/ai-front-component.controller';
+import { AiFrontComponentService } from 'src/engine/metadata-modules/ai/ai-front-component/ai-front-component.service';
+
+@Module({
+ imports: [
+ TypeORMModule,
+ ApplicationModule,
+ ApplicationPackageModule,
+ CacheLockModule,
+ PermissionsModule,
+ FeatureFlagModule,
+ RecordCrudModule,
+ ],
+ controllers: [AiFrontComponentController],
+ providers: [
+ AiFrontComponentService,
+ FrontComponentCompilerService,
+ WorkspaceFrontComponentDependenciesService,
+ ],
+})
+export class AiFrontComponentModule {}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.service.ts
new file mode 100644
index 00000000000..34f7dcb5158
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/ai-front-component.service.ts
@@ -0,0 +1,421 @@
+import { PostgresAdvisoryLockService } from 'src/database/typeorm/postgres-advisory-lock.service';
+import { FileStorageExceptionCode } from 'src/engine/core-modules/file-storage/interfaces/file-storage-exception';
+import { FileStorageService } from 'src/engine/core-modules/file-storage/services/file-storage.service';
+import { streamToBuffer } from 'src/utils/stream-to-buffer';
+import { validateFrontComponentSampleRecordsOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-sample-records-or-throw.util';
+import { PermissionFlagType } from 'twenty-shared/constants';
+import { v4 } from 'uuid';
+import { PermissionsService } from 'src/engine/permissions/permissions.service';
+import { type FrontComponentDraft } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft.type';
+import { type FrontComponentDraftInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft-input.type';
+import { FrontComponentCompilerService } from 'src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service';
+import { frontComponentDraftSchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema';
+import { Injectable } from '@nestjs/common';
+import { msg } from '@lingui/core/macro';
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+
+import { FeatureFlagKey, FileFolder } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { doNotTranslate } from 'twenty-shared/i18n';
+
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { type WorkspaceAuthContext } from 'src/engine/core-modules/auth/types/workspace-auth-context.type';
+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
+import { CommonApiContextBuilderService } from 'src/engine/core-modules/record-crud/services/common-api-context-builder.service';
+import { type ToolProviderContext } from 'src/engine/core-modules/tool-provider/interfaces/tool-provider-context.type';
+import { type FrontComponentQuery } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type';
+
+const DRAFT_TIME_TO_LIVE_IN_MILLISECONDS = 24 * 60 * 60 * 1000;
+
+@Injectable()
+export class AiFrontComponentService {
+ constructor(
+ private readonly featureFlags: FeatureFlagService,
+ private readonly applications: ApplicationService,
+ private readonly queryContext: CommonApiContextBuilderService,
+ private readonly compiler: FrontComponentCompilerService,
+ private readonly postgresAdvisoryLockService: PostgresAdvisoryLockService,
+ private readonly permissions: PermissionsService,
+ private readonly fileStorageService: FileStorageService,
+ ) {}
+
+ private isEnabled(workspaceId: string) {
+ return this.featureFlags.isFeatureEnabled(
+ FeatureFlagKey.IS_AI_CHAT_COMPONENT_BUILDER_ENABLED,
+ workspaceId,
+ );
+ }
+
+ async assertEnabledOrThrow(workspaceId: string) {
+ if (!(await this.isEnabled(workspaceId))) {
+ throw new ApplicationException(
+ doNotTranslate('AI component builder is disabled.'),
+ ApplicationExceptionCode.FORBIDDEN,
+ { userFriendlyMessage: msg`AI component builder is disabled.` },
+ );
+ }
+ }
+
+ async assertCanAuthorOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ }) {
+ await this.assertEnabledOrThrow(workspaceId);
+ if (
+ !(await this.permissions.userHasWorkspaceSettingPermission({
+ workspaceId,
+ userWorkspaceId,
+ setting: PermissionFlagType.APPLICATIONS,
+ applicationId: undefined,
+ agentId: undefined,
+ }))
+ ) {
+ throw new ApplicationException(
+ doNotTranslate('Managing applications is required.'),
+ ApplicationExceptionCode.FORBIDDEN,
+ { userFriendlyMessage: msg`Managing applications is required.` },
+ );
+ }
+ }
+
+ private async withDraftLock<TResult>({
+ workspaceId,
+ draftId,
+ callback,
+ }: {
+ workspaceId: string;
+ draftId: string;
+ callback: () => Promise<TResult>;
+ }): Promise<TResult> {
+ const result = await this.postgresAdvisoryLockService.tryWithLock(
+ `ai-front-component-draft:${workspaceId}:${draftId}`,
+ callback,
+ );
+
+ if (!result.acquired) {
+ throw new ApplicationException(
+ doNotTranslate('This draft is being updated. Try again.'),
+ ApplicationExceptionCode.INVALID_INPUT,
+ { userFriendlyMessage: msg`This draft is being updated. Try again.` },
+ );
+ }
+
+ return result.value;
+ }
+
+ private async saveDraft({
+ workspaceId,
+ draft,
+ }: {
+ workspaceId: string;
+ draft: FrontComponentDraft;
+ }) {
+ const application =
+ await this.applications.findOneApplicationWithRelationsOrThrow({
+ id: draft.applicationId,
+ workspaceId,
+ });
+
+ await this.fileStorageService.writeFile({
+ workspaceId,
+ applicationUniversalIdentifier: application.universalIdentifier,
+ applicationId: draft.applicationId,
+ fileFolder: FileFolder.AgentChat,
+ resourcePath: `front-component-drafts/${draft.id}.json`,
+ fileId: draft.id,
+ sourceFile: JSON.stringify(draft),
+ settings: {
+ isTemporaryFile: true,
+ toDelete: false,
+ expiresAt: new Date(draft.expiresAt).toISOString(),
+ },
+ });
+ }
+
+ async getDraftOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ draftId,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ draftId: string;
+ }): Promise<FrontComponentDraft> {
+ await this.assertCanAuthorOrThrow({ workspaceId, userWorkspaceId });
+ const { workspaceCustomFlatApplication: application } =
+ await this.applications.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId },
+ );
+ let draft: FrontComponentDraft | undefined;
+
+ try {
+ const stream = await this.fileStorageService.readFile({
+ workspaceId,
+ applicationUniversalIdentifier: application.universalIdentifier,
+ fileFolder: FileFolder.AgentChat,
+ resourcePath: `front-component-drafts/${draftId}.json`,
+ });
+ draft = JSON.parse((await streamToBuffer(stream)).toString());
+ } catch (error) {
+ if (error.code !== FileStorageExceptionCode.FILE_NOT_FOUND) {
+ throw error;
+ }
+ }
+
+ if (
+ !isDefined(draft) ||
+ draft.expiresAt <= Date.now() ||
+ draft.userWorkspaceId !== userWorkspaceId
+ ) {
+ throw new ApplicationException(
+ doNotTranslate('Component draft not found or expired.'),
+ ApplicationExceptionCode.FRONT_COMPONENT_NOT_FOUND,
+ { userFriendlyMessage: msg`Component draft not found or expired.` },
+ );
+ }
+
+ return draft;
+ }
+
+ async createDraft({
+ draftInput,
+ context,
+ }: {
+ draftInput: FrontComponentDraftInput;
+ context: Pick<
+ ToolProviderContext,
+ | 'workspaceId'
+ | 'userWorkspaceId'
+ | 'threadId'
+ | 'authContext'
+ | 'rolePermissionConfig'
+ >;
+ }) {
+ const { userWorkspaceId, threadId } = context;
+ const validation = frontComponentDraftSchema.safeParse(draftInput);
+
+ if (!validation.success) {
+ throw new ApplicationException(
+ doNotTranslate('Invalid component draft input.'),
+ ApplicationExceptionCode.INVALID_INPUT,
+ { userFriendlyMessage: msg`Invalid component draft input.` },
+ );
+ }
+
+ const input = validation.data;
+
+ if (
+ !isDefined(userWorkspaceId) ||
+ !isDefined(threadId) ||
+ !isDefined(context.authContext)
+ ) {
+ throw new ApplicationException(
+ doNotTranslate('A signed-in chat is required.'),
+ ApplicationExceptionCode.FORBIDDEN,
+ { userFriendlyMessage: msg`A signed-in chat is required.` },
+ );
+ }
+ await this.assertCanAuthorOrThrow({
+ workspaceId: context.workspaceId,
+ userWorkspaceId,
+ });
+ const objectNamePlural = await this.getQueryObjectNamePluralOrThrow({
+ query: input.query,
+ authContext: context.authContext,
+ rolePermissionConfig: context.rolePermissionConfig,
+ });
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: input.sampleRecords,
+ selectedFields: input.query.select,
+ });
+ let previous = isDefined(input.previousDraftId)
+ ? await this.getDraftOrThrow({
+ workspaceId: context.workspaceId,
+ userWorkspaceId,
+ draftId: input.previousDraftId,
+ })
+ : undefined;
+ const id = v4();
+ const { workspaceCustomFlatApplication: application } =
+ await this.applications.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspaceId: context.workspaceId },
+ );
+ const built = await this.compiler.build({
+ workspaceId: context.workspaceId,
+ input: {
+ componentId: id,
+ name: input.name,
+ source: input.source,
+ pageLayoutType: input.pageLayoutType,
+ },
+ });
+
+ const saveRevision = async () => {
+ if (isDefined(previous)) {
+ previous = await this.getDraftOrThrow({
+ workspaceId: context.workspaceId,
+ userWorkspaceId,
+ draftId: previous.id,
+ });
+
+ if (previous.isSuperseded || previous.threadId !== threadId) {
+ throw new ApplicationException(
+ doNotTranslate(
+ 'This draft was superseded or belongs to another chat. Start a new draft.',
+ ),
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`This draft was superseded or belongs to another chat. Start a new draft.`,
+ },
+ );
+ }
+ }
+ const draft: FrontComponentDraft = {
+ ...input,
+ compiledSource: built.compiledSource,
+ checksum: built.checksum,
+ dependencyRevision: built.dependencyRevision,
+ entrySource: built.source,
+ componentName: built.componentName,
+ hasSdkClientImport: built.hasSdkClientImport,
+ objectNamePlural,
+ id,
+ applicationId: application.id,
+ expiresAt: Date.now() + DRAFT_TIME_TO_LIVE_IN_MILLISECONDS,
+ userWorkspaceId,
+ threadId,
+ };
+
+ await this.saveDraft({ workspaceId: context.workspaceId, draft });
+ if (isDefined(previous)) {
+ await this.saveDraft({
+ workspaceId: context.workspaceId,
+ draft: { ...previous, isSuperseded: true },
+ });
+ }
+
+ return {
+ draftId: id,
+ checksum: built.checksum,
+ name: input.name,
+ sampleRecordCount: input.sampleRecords.length,
+ };
+ };
+
+ return isDefined(previous)
+ ? this.withDraftLock({
+ workspaceId: context.workspaceId,
+ draftId: previous.id,
+ callback: saveRevision,
+ })
+ : saveRevision();
+ }
+
+ async getPreview({
+ userWorkspaceId,
+ draftId,
+ authContext,
+ }: {
+ userWorkspaceId: string;
+ draftId: string;
+ authContext: WorkspaceAuthContext;
+ }) {
+ const workspaceId = authContext.workspace.id;
+ const draft = await this.getDraftOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ draftId,
+ });
+
+ const application =
+ await this.applications.findOneApplicationWithRelationsOrThrow({
+ id: draft.applicationId,
+ workspaceId,
+ });
+
+ return {
+ draftId: draft.id,
+ name: draft.name,
+ isCurrent: !draft.isSuperseded,
+ componentSource: draft.compiledSource,
+ applicationId: draft.applicationId,
+ sharedDependenciesChecksum:
+ application.frontComponentSharedDependenciesChecksum,
+ mockQueryResult: {
+ [draft.objectNamePlural]: {
+ edges: draft.sampleRecords.map((node) => ({ node })),
+ totalCount: draft.sampleRecords.length,
+ pageInfo: { hasNextPage: false },
+ },
+ },
+ };
+ }
+
+ async reportPreviewError({
+ workspaceId,
+ userWorkspaceId,
+ draftId,
+ previewError,
+ }: {
+ workspaceId: string;
+ userWorkspaceId: string;
+ draftId: string;
+ previewError: string;
+ }) {
+ await this.withDraftLock({
+ workspaceId,
+ draftId,
+ callback: async () => {
+ const draft = await this.getDraftOrThrow({
+ workspaceId,
+ userWorkspaceId,
+ draftId,
+ });
+
+ await this.saveDraft({
+ workspaceId,
+ draft: { ...draft, previewError },
+ });
+ },
+ });
+ }
+
+ private async getQueryObjectNamePluralOrThrow({
+ query,
+ authContext,
+ rolePermissionConfig,
+ }: {
+ query: FrontComponentQuery;
+ authContext: WorkspaceAuthContext;
+ rolePermissionConfig?: ToolProviderContext['rolePermissionConfig'];
+ }) {
+ const { selectedFields, flatObjectMetadata } =
+ await this.queryContext.build({
+ authContext,
+ objectName: query.objectName,
+ rolePermissionConfig,
+ });
+
+ for (const fieldName of query.select) {
+ if (!isDefined(selectedFields[fieldName])) {
+ throw new ApplicationException(
+ doNotTranslate(
+ `Field ${query.objectName}.${fieldName} is unavailable. Select accessible top-level fields.`,
+ ),
+ ApplicationExceptionCode.FORBIDDEN,
+ {
+ userFriendlyMessage: msg`Field ${query.objectName}.${fieldName} is unavailable. Select accessible top-level fields.`,
+ },
+ );
+ }
+ }
+
+ return flatObjectMetadata.namePlural;
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts
index 5b2d93634b0..abac787f5e1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-allowed-imports.constant.ts
@@ -1,6 +1,8 @@
import { FRONT_COMPONENT_UI_IMPORTS } from 'twenty-shared/front-component-build';
+import { FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant';
export const FRONT_COMPONENT_ALLOWED_IMPORTS = [
+ FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER,
'react',
'react-dom',
'react/jsx-runtime',
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant.ts
new file mode 100644
index 00000000000..1606c671766
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant.ts
@@ -0,0 +1,2 @@
+export const FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER =
+ 'twenty-client-sdk/core';
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service.ts
index 7d4a3f46a96..a1d9565f95b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/front-component-compiler.service.ts
@@ -75,6 +75,7 @@ export class FrontComponentCompilerService {
dependencyRevision: builtDependencies.dependencyRevision,
componentName: FRONT_COMPONENT_WRAPPER_NAME,
compiledSource: built.builtCode,
+ hasSdkClientImport: built.hasSdkClientImport,
checksum: built.checksum,
};
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-build-result.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-build-result.schema.ts
index 979cb7a6ac4..500f99946ee 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-build-result.schema.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-build-result.schema.ts
@@ -6,6 +6,7 @@ export const frontComponentBuildResultSchema = z.discriminatedUnion('success', [
z.object({
success: z.literal(true),
builtCode: z.string(),
+ hasSdkClientImport: z.boolean(),
checksum: z.string().regex(/^[a-f0-9]{64}$/),
sharedDependenciesChecksum: z.string().regex(/^[a-f0-9]{64}$/),
}),
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.spec.ts
new file mode 100644
index 00000000000..c0fce797eb7
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.spec.ts
@@ -0,0 +1,30 @@
+import { PageLayoutType } from 'twenty-shared/types';
+
+import { frontComponentDraftSchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema';
+
+const INPUT = {
+ name: 'Companies',
+ source: 'export const Component = () => <div />;',
+ query: { objectName: 'company', select: ['name'], limit: 20 },
+ sampleRecords: [],
+};
+
+describe('frontComponentDraftSchema', () => {
+ it.each([PageLayoutType.DASHBOARD, PageLayoutType.RECORD_PAGE])(
+ 'accepts one %s surface',
+ (pageLayoutType) => {
+ expect(
+ frontComponentDraftSchema.safeParse({ ...INPUT, pageLayoutType })
+ .success,
+ ).toBe(true);
+ },
+ );
+ it('rejects a component targeting multiple surfaces', () => {
+ expect(
+ frontComponentDraftSchema.safeParse({
+ ...INPUT,
+ pageLayoutType: [PageLayoutType.DASHBOARD, PageLayoutType.RECORD_PAGE],
+ }).success,
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.ts
new file mode 100644
index 00000000000..c3ec3b92d3e
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema.ts
@@ -0,0 +1,24 @@
+import { z } from 'zod';
+import { PageLayoutType } from 'twenty-shared/types';
+
+import { frontComponentQuerySchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema';
+
+export const frontComponentDraftSchema = z.object({
+ previousDraftId: z.string().uuid().optional(),
+ pageLayoutType: z.enum([
+ PageLayoutType.DASHBOARD,
+ PageLayoutType.RECORD_PAGE,
+ ]),
+ name: z.string().trim().min(1).max(100),
+ source: z
+ .string()
+ .min(1)
+ .max(50000)
+ .describe(
+ 'TSX exporting a named Component that takes no props, with no default export. Load records with CoreApiClient from twenty-client-sdk/core, using the workspace object plural name and selecting edges.node, totalCount and pageInfo.hasNextPage. The query must match the preview query. Twenty adds the theme and defineFrontComponent registration. Use React and supported twenty-ui imports.',
+ ),
+ query: frontComponentQuerySchema.describe(
+ 'Object and fields mocked during preview. Saved components load their own data through the app SDK; this query is not persisted in their source.',
+ ),
+ sampleRecords: z.array(z.record(z.string(), z.unknown())).max(100),
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts
index af3d4bee0c1..5ff301769c6 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type.ts
@@ -1,11 +1,8 @@
import { type PageLayoutType } from 'twenty-shared/types';
-import { type FrontComponentQuery } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-query.type';
-
export type FrontComponentBuildInput = {
componentId: string;
name: string;
source: string;
- query: FrontComponentQuery;
pageLayoutType: PageLayoutType.DASHBOARD | PageLayoutType.RECORD_PAGE;
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft-input.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft-input.type.ts
new file mode 100644
index 00000000000..dd383fac76a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft-input.type.ts
@@ -0,0 +1,7 @@
+import { type z } from 'zod';
+
+import { frontComponentDraftSchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-draft.schema';
+
+export type FrontComponentDraftInput = z.infer<
+ typeof frontComponentDraftSchema
+>;
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft.type.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft.type.ts
new file mode 100644
index 00000000000..5e60dca370f
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft.type.ts
@@ -0,0 +1,18 @@
+import { type FrontComponentDraftInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-draft-input.type';
+
+export type FrontComponentDraft = FrontComponentDraftInput & {
+ id: string;
+ applicationId: string;
+ expiresAt: number;
+ threadId: string;
+ userWorkspaceId: string;
+ entrySource: string;
+ componentName: string;
+ hasSdkClientImport: boolean;
+ objectNamePlural: string;
+ compiledSource: string;
+ checksum: string;
+ dependencyRevision?: string;
+ previewError?: string;
+ isSuperseded?: boolean;
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts
index f4bf184108a..3864d5732f5 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component-shared-dependencies.util.spec.ts
@@ -40,7 +40,6 @@ const INPUT = {
componentId: 'component-id',
name: 'Sales "this week"',
source: SOURCE,
- query: { objectName: 'company', select: ['name'], limit: 20 },
pageLayoutType: PageLayoutType.DASHBOARD as const,
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts
index fd0960d313f..b8433542389 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/build-front-component.util.spec.ts
@@ -40,19 +40,22 @@ const buildFrontComponent = (
input: Parameters<typeof compileFrontComponent>[0]['input'],
) => compileFrontComponent({ input, sharedDependencies });
-const SOURCE = `import { useState } from 'react';
-type Company = { id: string; name: string };
-type ComponentProps = { records: Company[] };
-// Keep this filter local to the widget.
-export const Component = ({ records }: ComponentProps) => {
- const [filter, setFilter] = useState('');
- return <div><input value={filter} onChange={event => setFilter(event.target.value)} />{records.filter(record => record.name.includes(filter)).map(record => <p key={record.id}>{record.name}</p>)}</div>;
+const SOURCE = `import { useEffect, useState } from 'react';
+import { CoreApiClient } from 'twenty-client-sdk/core';
+export const Component = () => {
+ const [records, setRecords] = useState<{ id: string; name: string }[]>([]);
+ useEffect(() => {
+ new CoreApiClient().query({ companies: {
+ __args: { first: 20 }, edges: { node: { id: true, name: true } },
+ totalCount: true, pageInfo: { hasNextPage: true },
+ } }).then(result => setRecords(result.companies.edges.map(edge => edge.node)));
+ }, []);
+ return <div>{records.map(record => <p key={record.id}>{record.name}</p>)}</div>;
};`;
const INPUT = {
componentId: 'component-id',
name: 'Sales "this week"',
source: SOURCE,
- query: { objectName: 'company', select: ['name'], limit: 20 },
pageLayoutType: PageLayoutType.DASHBOARD as const,
};
@@ -60,18 +63,19 @@ describe('buildFrontComponent', () => {
it.each([PageLayoutType.DASHBOARD, PageLayoutType.RECORD_PAGE] as const)(
'builds one editable SDK file for the selected %s surface',
async (pageLayoutType) => {
- const { source, compiledSource, checksum } = await buildFrontComponent({
- ...INPUT,
- pageLayoutType,
- });
+ const { source, compiledSource, checksum, hasSdkClientImport } =
+ await buildFrontComponent({
+ ...INPUT,
+ pageLayoutType,
+ });
expect(source).toContain(SOURCE);
expect(source).toContain(
`widgetAvailability: { pageLayoutType: TwentyPageLayoutType.${pageLayoutType} }`,
);
- expect(source).toContain(
- 'export const componentQuery = ' + JSON.stringify(INPUT.query),
- );
+ expect(source).not.toContain('componentQuery');
+ expect(hasSdkClientImport).toBe(true);
+ expect(compiledSource).toContain('twenty-client-sdk/core');
expect(checksum).toMatch(/^[a-f0-9]{64}$/);
expect(compiledSource).not.toContain('TWENTY_APP_ACCESS_TOKEN');
await expect(
@@ -84,6 +88,7 @@ describe('buildFrontComponent', () => {
write: false,
format: 'esm',
external: [
+ 'twenty-client-sdk/core',
'react',
'react/jsx-runtime',
'twenty-sdk/define',
@@ -113,7 +118,12 @@ describe('buildFrontComponent', () => {
).rejects.toThrow('Unsupported import');
});
- it.each(['node:fs', 'react-dom/client', 'twenty-shared/types'])(
+ it.each([
+ 'node:fs',
+ 'react-dom/client',
+ 'twenty-shared/types',
+ 'twenty-client-sdk/core',
+ ])(
'rejects unsupported dynamic import %s during the build',
async (importPath) => {
await expect(
@@ -181,18 +191,6 @@ describe('buildFrontComponent', () => {
},
);
- it.each([
- { ...INPUT.query, objectName: 'company.name' },
- { ...INPUT.query, select: [] },
- { ...INPUT.query, limit: 101 },
- ])('returns a structured error for invalid query %j', async (query) => {
- await expect(
- buildFrontComponent({ ...INPUT, query }),
- ).rejects.toMatchObject({
- code: 'INVALID_SETTINGS',
- });
- });
-
it.each([
'export default () => <div />;',
'export default function Component() { return <div />; }',
@@ -224,8 +222,8 @@ describe('buildFrontComponent', () => {
buildFrontComponent({
...INPUT,
source:
- 'export const Component = () => <div />; const componentQuery = "other";',
+ 'export const Component = () => <div />; const TwentyComponent = "other";',
}),
- ).rejects.toThrow('componentQuery');
+ ).rejects.toThrow('TwentyComponent');
});
});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/execute-front-component-builder-request.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/execute-front-component-builder-request.util.spec.ts
index 17ae0825b7d..8cdcbe0afc1 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/execute-front-component-builder-request.util.spec.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/execute-front-component-builder-request.util.spec.ts
@@ -21,7 +21,6 @@ const REQUEST: FrontComponentBuilderRequest = {
componentId: 'component-id',
name: 'Preview',
source: 'export const Component = () => <div />;',
- query: { objectName: 'company', select: ['name'], limit: 20 },
pageLayoutType: PageLayoutType.DASHBOARD,
},
manifest: { checksum: 'a'.repeat(64), exports: {} },
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/validate-front-component-sample-records-or-throw.util.spec.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/validate-front-component-sample-records-or-throw.util.spec.ts
new file mode 100644
index 00000000000..965378f75eb
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/__tests__/validate-front-component-sample-records-or-throw.util.spec.ts
@@ -0,0 +1,59 @@
+import { validateFrontComponentSampleRecordsOrThrow } from 'src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-sample-records-or-throw.util';
+
+it('allows selected fields and record IDs', () => {
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [{ id: 'record', name: 'Example' }],
+ selectedFields: ['name'],
+ }),
+ ).not.toThrow();
+});
+
+it('allows an empty mock dataset', () => {
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [],
+ selectedFields: ['name'],
+ }),
+ ).not.toThrow();
+});
+
+it('rejects a field outside the query selection', () => {
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [{ name: 'Example' }, { secret: 'not selected' }],
+ selectedFields: ['name'],
+ }),
+ ).toThrow('Sample records must only contain selected fields and id.');
+});
+
+it('accepts exactly 100 KB of serialized mock records', () => {
+ const overhead = JSON.stringify([{ name: '' }]).length;
+
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [{ name: 'a'.repeat(100000 - overhead) }],
+ selectedFields: ['name'],
+ }),
+ ).not.toThrow();
+});
+
+it('rejects mock records exceeding 100 KB', () => {
+ const overhead = JSON.stringify([{ name: '' }]).length;
+
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [{ name: 'a'.repeat(100001 - overhead) }],
+ selectedFields: ['name'],
+ }),
+ ).toThrow('Sample records exceed 100 KB.');
+});
+
+it('counts UTF-8 bytes for non-ASCII mock records', () => {
+ expect(() =>
+ validateFrontComponentSampleRecordsOrThrow({
+ sampleRecords: [{ name: 'é'.repeat(50000) }],
+ selectedFields: ['name'],
+ }),
+ ).toThrow('Sample records exceed 100 KB.');
+});
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts
index ba0c4430abe..ed3cd155fe2 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component-entry-source.util.ts
@@ -3,11 +3,9 @@ import { z } from 'zod';
import { FRONT_COMPONENT_WRAPPER_NAME } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-wrapper-name.constant';
import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
-import { frontComponentQuerySchema } from 'src/engine/metadata-modules/ai/ai-front-component/schemas/front-component-query.schema';
import { type FrontComponentBuildInput } from 'src/engine/metadata-modules/ai/ai-front-component/types/front-component-build-input.type';
const frontComponentEntryOptionsSchema = z.object({
- query: frontComponentQuerySchema,
pageLayoutType: z.enum([
PageLayoutType.DASHBOARD,
PageLayoutType.RECORD_PAGE,
@@ -18,11 +16,9 @@ export const buildFrontComponentEntrySource = ({
componentId,
name,
source,
- query,
pageLayoutType,
}: FrontComponentBuildInput): string => {
const parsedOptions = frontComponentEntryOptionsSchema.safeParse({
- query,
pageLayoutType,
});
@@ -34,15 +30,13 @@ export const buildFrontComponentEntrySource = ({
}
return `import { defineFrontComponent } from 'twenty-sdk/define';
-import type { ComponentProps as TwentyComponentProps } from 'react';
import { ThemeProvider as TwentyThemeProvider } from 'twenty-ui/theme';
import { PageLayoutType as TwentyPageLayoutType } from 'twenty-shared/types';
import 'twenty-ui/style.css';
import 'twenty-ui/theme-light.css';
${source}
-export const componentQuery = ${JSON.stringify(parsedOptions.data.query)};
-function ${FRONT_COMPONENT_WRAPPER_NAME}(props: TwentyComponentProps<typeof Component>) {
- return <TwentyThemeProvider colorScheme="light"><Component {...props} /></TwentyThemeProvider>;
+function ${FRONT_COMPONENT_WRAPPER_NAME}() {
+ return <TwentyThemeProvider colorScheme="light"><Component /></TwentyThemeProvider>;
}
export default defineFrontComponent({
universalIdentifier: ${JSON.stringify(componentId)},
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts
index 3116d40eafd..4531c89056e 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/build-front-component.util.ts
@@ -1,3 +1,6 @@
+import { FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant';
+import { isDefined } from 'twenty-shared/utils';
+import { FrontComponentBuildException } from 'src/engine/metadata-modules/ai/ai-front-component/exceptions/front-component-build.exception';
import { PageLayoutType } from 'twenty-shared/types';
import { createHash } from 'crypto';
import { dirname, join } from 'path';
@@ -31,6 +34,7 @@ export const buildFrontComponent = async ({
componentName: string;
compiledSource: string;
checksum: string;
+ hasSdkClientImport: boolean;
sharedDependenciesChecksum: string;
}> => {
validateFrontComponentSourceOrThrow(input.source);
@@ -45,8 +49,12 @@ export const buildFrontComponent = async ({
loader: 'tsx',
},
write: false,
+ metafile: true,
platform: 'browser',
- external: [FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER],
+ external: [
+ FRONT_COMPONENT_SHARED_DEPENDENCIES_IMPORT_SPECIFIER,
+ FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER,
+ ],
plugins: [
{
name: 'front-component-imports',
@@ -66,7 +74,7 @@ export const buildFrontComponent = async ({
return {
errors: [
{
- text: `Unsupported import: ${path}. Use React and the supported twenty-ui imports.`,
+ text: `Unsupported import: ${path}. Use React, ${FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER} and the supported twenty-ui imports.`,
},
],
};
@@ -92,10 +100,24 @@ export const buildFrontComponent = async ({
}),
],
});
+ if (!isDefined(result.metafile)) {
+ throw new FrontComponentBuildException({
+ message: 'Component build did not return import metadata.',
+ code: 'BUILD_FAILED',
+ });
+ }
+
const compiledSource = result.outputFiles[0].text;
return {
source,
+ hasSdkClientImport: Object.values(result.metafile.outputs).some((output) =>
+ output.imports.some(
+ (entry) =>
+ entry.external &&
+ entry.path === FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER,
+ ),
+ ),
sharedDependenciesChecksum: sharedDependencies.checksum,
componentName: FRONT_COMPONENT_WRAPPER_NAME,
compiledSource,
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/execute-front-component-builder-request.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/execute-front-component-builder-request.util.ts
index 178c1b5f94b..4d2c8447137 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/execute-front-component-builder-request.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/execute-front-component-builder-request.util.ts
@@ -36,12 +36,18 @@ export const executeFrontComponentBuilderRequest = async ({
exportNamesBySpecifier: new Map(Object.entries(manifest.exports)),
},
});
- const { compiledSource, checksum, sharedDependenciesChecksum } = built;
+ const {
+ compiledSource,
+ checksum,
+ sharedDependenciesChecksum,
+ hasSdkClientImport,
+ } = built;
const result = {
success: true as const,
builtCode: compiledSource,
checksum,
sharedDependenciesChecksum,
+ hasSdkClientImport,
};
return checkResponseSizeOrThrow(result);
} catch (error) {
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-sample-records-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-sample-records-or-throw.util.ts
new file mode 100644
index 00000000000..28f9137210a
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-sample-records-or-throw.util.ts
@@ -0,0 +1,40 @@
+import { msg } from '@lingui/core/macro';
+import { doNotTranslate } from 'twenty-shared/i18n';
+
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+
+export const validateFrontComponentSampleRecordsOrThrow = ({
+ sampleRecords,
+ selectedFields,
+}: {
+ sampleRecords: Record<string, unknown>[];
+ selectedFields: string[];
+}): void => {
+ if (Buffer.byteLength(JSON.stringify(sampleRecords), 'utf8') > 100000) {
+ throw new ApplicationException(
+ doNotTranslate('Sample records exceed 100 KB.'),
+ ApplicationExceptionCode.INVALID_INPUT,
+ { userFriendlyMessage: msg`Sample records exceed 100 KB.` },
+ );
+ }
+ if (
+ sampleRecords.some((record) =>
+ Object.keys(record).some(
+ (key) => key !== 'id' && !selectedFields.includes(key),
+ ),
+ )
+ ) {
+ throw new ApplicationException(
+ doNotTranslate(
+ 'Sample records must only contain selected fields and id.',
+ ),
+ ApplicationExceptionCode.INVALID_INPUT,
+ {
+ userFriendlyMessage: msg`Sample records must only contain selected fields and id.`,
+ },
+ );
+ }
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts
index 20fffd9a0c2..8cf934ca872 100644
--- a/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/ai/ai-front-component/utils/validate-front-component-source-or-throw.util.ts
@@ -1,3 +1,4 @@
+import { FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER } from 'src/engine/metadata-modules/ai/ai-front-component/constants/front-component-core-api-client-import-specifier.constant';
import * as typescript from 'typescript';
import { isDefined } from 'twenty-shared/utils';
@@ -63,7 +64,7 @@ export const validateFrontComponentSourceOrThrow = (source: string): void => {
!FRONT_COMPONENT_ALLOWED_IMPORTS.includes(statement.moduleSpecifier.text)
) {
throw new FrontComponentBuildException({
- message: `Unsupported import: ${statement.moduleSpecifier.text}. Use React and the supported twenty-ui imports.`,
+ message: `Unsupported import: ${statement.moduleSpecifier.text}. Use React, ${FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER} and the supported twenty-ui imports.`,
code: 'INVALID_INPUT',
});
}
@@ -84,9 +85,12 @@ export const validateFrontComponentSourceOrThrow = (source: string): void => {
code: 'INVALID_INPUT',
});
}
- if (!FRONT_COMPONENT_ALLOWED_IMPORTS.includes(specifier.text)) {
+ if (
+ specifier.text === FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER ||
+ !FRONT_COMPONENT_ALLOWED_IMPORTS.includes(specifier.text)
+ ) {
throw new FrontComponentBuildException({
- message: `Unsupported import: ${specifier.text}. Use React and the supported twenty-ui imports.`,
+ message: `Unsupported import: ${specifier.text}. Use a static import for ${FRONT_COMPONENT_CORE_API_CLIENT_IMPORT_SPECIFIER}, or supported React and twenty-ui imports.`,
code: 'INVALID_INPUT',
});
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/metadata-engine.module.ts b/packages/twenty-server/src/engine/metadata-modules/metadata-engine.module.ts
index 6fcee6f2e89..7d7b8edb901 100644
--- a/packages/twenty-server/src/engine/metadata-modules/metadata-engine.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/metadata-engine.module.ts
@@ -5,6 +5,7 @@ import { APP_FILTER } from '@nestjs/core';
import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { AiAgentRunsModule } from 'src/engine/metadata-modules/ai/ai-agent-runs/ai-agent-runs.module';
import { AiChatModule } from 'src/engine/metadata-modules/ai/ai-chat/ai-chat.module';
+import { AiFrontComponentModule } from 'src/engine/metadata-modules/ai/ai-front-component/ai-front-component.module';
import { AiGenerateTextModule } from 'src/engine/metadata-modules/ai/ai-generate-text/ai-generate-text.module';
import { AiWorkspaceStatsModule } from 'src/engine/metadata-modules/ai/ai-workspace-stats/ai-workspace-stats.module';
import { ApplicationConnectionsModule } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.module';
@@ -62,6 +63,7 @@ import { WorkspaceMetadataVersionModule } from 'src/engine/metadata-modules/work
AiAgentModule,
AiAgentRunsModule,
AiChatModule,
+ AiFrontComponentModule,
AiGenerateTextModule,
AiWorkspaceStatsModule,
ApplicationConnectionsModule,
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index 5a87d58cc4c..804587d9d8d 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -102,6 +102,8 @@ exports[`endpoint permission declarations should match the auth principals, perm
"AgentRunsResolver.agentRuns {"applicationTarget":{"argName":"agentId","kind":"applicationOwnedEntity","metadataName":"agent","requireApplicationRegistrationOwnership":false,"source":"graphqlArg"},"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI_SETTINGS"]}",
"AiChatUsageResolver.aiChatUsage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AiChatUsageResolver.aiChatUserCreditsUsage {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
+ "AiFrontComponentController.getPreview {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
+ "AiFrontComponentController.reportPreviewError {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":[]}",
"AiGenerateTextController.handleGenerateText {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI"]}",
"AiWorkspaceStatsResolver.findWorkspaceAiStats {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["AI_SETTINGS"]}",
"ApiKeyController.create {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":{"withAgent":false,"withUser":true,"withoutUser":true},"oauthClient":{"withUser":true,"withoutUser":true},"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":{"withAgent":false,"withUser":false,"withoutUser":false},"oauthClient":{"withUser":false,"withoutUser":false},"userSession":{"impersonated":true,"playground":false,"standard":true,"workspaceAgnostic":false}}],"requiredFeatureFlags":[],"requiredPermissionFlags":["API_KEYS_AND_WEBHOOKS","ROLES"]}",
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index e20d4539119..895f451b791 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -1,4 +1,5 @@
export enum FeatureFlagKey {
+ IS_AI_CHAT_COMPONENT_BUILDER_ENABLED = 'IS_AI_CHAT_COMPONENT_BUILDER_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_REST_METADATA_API_NEW_FORMAT_DIRECT = 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT',
IS_RECORD_CREATION_FORM_ENABLED = 'IS_RECORD_CREATION_FORM_ENABLED',