The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(cli): add explicit object UI creation flags (#27602)
Weiko7978788164b8
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex 09bb6f54b76..36221db4f0d 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -210,16 +210,28 @@ which the template's Vitest config sets.```bashtwenty app addtwenty app add object --name invoice --name-plural invoices --no-input+twenty app add object --name invoice --name-plural invoices --create-view --create-navigation-menu-item --create-page-layout --no-inputtwenty app add field --name amount --type NUMBER --object <object-universal-identifier> --jsontwenty app add logic-function --name send-invoice --no-inputtwenty app add front-component --name invoice-panel --no-input```-`app add` creates one standalone definition from the CLI's templates.+`app add` creates definitions from the CLI's templates.It discovers the containing app, or accepts `--path <app-directory>`. No sign-inor workspace connection is needed. Use `object`, `field`, `logic-function` or-`front-component`; other generators and optional object views, layouts and menu-companions are not supported.+`front-component`.++Objects can also create optional UI definitions:++- `--create-view`: a table view containing the object's name field.+- `--create-navigation-menu-item`: a navigation item pointing to the object.+- `--create-page-layout`: a record page layout with Fields and Timeline tabs,+ plus the fields view required by its Fields widget.++Combine these flags to select what to generate. Without them, only the object+is created. These flags are valid only for objects and also work with `--no-input`+and `--json`. View, navigation and layout files go under `src/views`,+`src/navigation-menu-items` and `src/page-layouts`.Files are created under `src/objects`, `src/fields`, `src/logic-functions` and`src/front-components`, with kebab-case filenames and fresh universal UUIDs.diff --git a/packages/twenty-cli/src/app/add/README.md b/packages/twenty-cli/src/app/add/README.mdindex aca159241cd..5b35ce9797a 100644--- a/packages/twenty-cli/src/app/add/README.md+++ b/packages/twenty-cli/src/app/add/README.md@@ -18,16 +18,25 @@ the same helper as app init.- Parent and relation endpoint identifiers must be valid universal UUIDs. Noworkspace lookup verifies ownership or existence. Relations require reviewingboth endpoints; this generator creates only the requested standalone field.+- Objects accept `--create-view`, `--create-navigation-menu-item` and+ `--create-page-layout`. Each flag opts into that definition; page layouts also+ create the fields view used by their Fields widget. The list view and fields+ view reuse the object's name field. Fields views also include the SDK's+ generated audit fields, resolved using the application's universal identifier.- Node's `randomUUID` creates version 4 identifiers. The CLI TypeScript printerescapes authored strings, including quotes, backslashes and line breaks.- App discovery, SDK compatibility and application identity reuse the CLI'sworker boundary. Identity loading evaluates trusted app code in a disposableworker; it is not a security sandbox. The command makes no workspace requestsand does not require authentication.-- Destination paths reuse pull's containment and symlink checks. A fully staged- file is linked exclusively into place, so an existing or concurrently created- destination is never replaced. Cancellation before that link removes the- staged file; a successful link wins over late cancellation. Cleanup failure+- Destination paths reuse pull's containment and symlink checks. All destinations+ are checked before writing and all files are staged beside their destinations+ before exclusive linking, including when source directories are mounted on+ different filesystems.+ Existing or concurrently created files are never replaced. Failure or+ cancellation before all links complete rolls back the links already created;+ files replaced by another process are preserved. Incomplete rollback reports+ remaining app-relative paths. Completion wins over late cancellation. Cleanup failureafter success warns and reports the remaining temporary directory. Emptyparent directories can remain after failure or cancellation. Exclusive atomiccreation requires a filesystem supporting hard links; unsupported filesystems@@ -35,8 +44,8 @@ the same helper as app init.- Path validation rejects existing symbolic links. It cannot prevent anotherlocal process from replacing a parent directory between validation and writing.- JSON reports app-relative `createdPaths`. There is no overwrite mode and no- editing or registration of existing definitions. Object view, layout and menu- companions and other entity generators are not supported.+ editing or registration of existing definitions. Standalone view, layout and+ navigation item generators are not supported.These are starter definitions, not a deployment validator. Review type-specificsettings, relation endpoints, handlers and components, then build and plan the@@ -48,3 +57,9 @@ app. Successful generation does not imply the server will accept the metadata.normalizing random UUIDs while preserving their reuse. It covers every field typeand both runtime templates. Additional tests cover escaped strings, invalididentifiers, destination conflicts and cancellation.++View and navigation templates are deliberately limited to object companions:+fully populated fields and an object-target navigation item, without the SDK+CLI's placeholder and unrelated view/link/folder variants. Generated identifiers+and references are checked by the app-add command tests; record page layouts+also retain SDK source parity.diff --git a/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts b/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.tsindex 650dd49ef77..af53168e276 100644--- a/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts+++ b/packages/twenty-cli/src/app/add/__tests__/add-template-parity.spec.ts@@ -15,6 +15,7 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest';import { getFieldBaseFile } from '@/app/add/entity-field-template';import { getFrontComponentBaseFile } from '@/app/add/entity-front-component-template';import { getLogicFunctionBaseFile } from '@/app/add/entity-logic-function-template';+import { getRecordPageLayoutBaseFile } from '@/app/add/entity-record-page-layout-template';import { getObjectBaseFile } from '@/app/add/entity-object-template';import { kebabCase } from '@/app/pull/kebab-case';@@ -39,6 +40,7 @@ type SdkReference = {getFrontComponentBaseFile: typeof getFrontComponentBaseFile;getLogicFunctionBaseFile: typeof getLogicFunctionBaseFile;getObjectBaseFile: typeof getObjectBaseFile;+ getRecordPageLayoutBaseFile: typeof getRecordPageLayoutBaseFile;kebabCase: typeof kebabCase;};@@ -58,7 +60,13 @@ describe('app add template parity with the repository SDK', () => {await build({stdin: {contents: [- ...['object', 'field', 'logic-function', 'front-component'].map(+ ...[+ 'object',+ 'field',+ 'logic-function',+ 'front-component',+ 'record-page-layout',+ ].map((entity) =>`export * from './cli/utilities/entity/entity-${entity}-template';`,),@@ -97,6 +105,18 @@ describe('app add template parity with the repository SDK', () => {);});+ it('preserves the SDK record page layout and its fields view reference', () => {+ const input = {+ objectLabelSingular: 'Invoice',+ objectUniversalIdentifier: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',+ fieldsWidgetViewUniversalIdentifier:+ 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',+ };+ expect(normalizeIdentifiers(getRecordPageLayoutBaseFile(input))).toBe(+ normalizeIdentifiers(sdk.getRecordPageLayoutBaseFile(input)),+ );+ });+it.each(Object.values(FieldMetadataType))('preserves the %s field template',(type) => {@@ -158,7 +178,14 @@ describe('app add template parity with the repository SDK', () => {},});- for (const source of [object, field]) {+ const layout = getRecordPageLayoutBaseFile({+ objectLabelSingular: label,+ objectUniversalIdentifier: 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa',+ fieldsWidgetViewUniversalIdentifier:+ 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb',+ });++ for (const source of [object, field, layout]) {expect(source).toContain("Customer\\'s \\\\ invoice\\nnext line");const result = await build({stdin: { contents: source, loader: 'ts' },diff --git a/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.ts b/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.tsdeleted file mode 100644index 04ecc22a6e2..00000000000--- a/packages/twenty-cli/src/app/add/__tests__/write-app-add-file.spec.ts+++ /dev/null@@ -1,139 +0,0 @@-import {- link,- lstat,- mkdtemp,- readFile,- readdir,- rm,- writeFile,-} from 'node:fs/promises';-import type * as fileSystemPromises from 'node:fs/promises';-import { tmpdir } from 'node:os';-import { join } from 'node:path';--import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';--import { writeAppAddFile } from '@/app/add/write-app-add-file';--vi.mock('node:fs/promises', async (importOriginal) => {- const actual = await importOriginal<typeof fileSystemPromises>();-- return {- ...actual,- link: vi.fn(actual.link),- lstat: vi.fn(actual.lstat),- rm: vi.fn(actual.rm),- writeFile: vi.fn(actual.writeFile),- };-});--describe('app add exclusive file creation', () => {- let root: string;- const file = {- path: 'src/objects/invoice.ts',- content: 'complete definition',- };- const actual = vi.importActual<typeof fileSystemPromises>('node:fs/promises');-- beforeEach(async () => {- root = await mkdtemp(join(tmpdir(), 'twenty-add-write-'));- });- afterEach(async () => {- vi.restoreAllMocks();- await rm(root, { recursive: true, force: true });- });-- it.each(['EACCES', 'EIO'])(- 'preserves %s from path validation',- async (code) => {- const error = Object.assign(new Error('filesystem failure'), { code });- vi.mocked(lstat).mockRejectedValueOnce(error);- await expect(- writeAppAddFile({- appPath: root,- file,- signal: new AbortController().signal,- }),- ).rejects.toBe(error);- expect(link).not.toHaveBeenCalled();- },- );-- it('preserves a destination created while the new definition was staged', async () => {- vi.mocked(link).mockImplementationOnce(async (source, destination) => {- await (await actual).writeFile(destination, 'concurrent user definition');-- return (await actual).link(source, destination);- });-- await expect(- writeAppAddFile({- appPath: root,- file,- signal: new AbortController().signal,- }),- ).rejects.toMatchObject({ code: 'APP_PATH_UNAVAILABLE', exitCode: 6 });- expect(await readFile(join(root, file.path), 'utf8')).toBe(- 'concurrent user definition',- );- expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);- });-- it('removes a partial staged write without exposing an incomplete definition', async () => {- vi.mocked(writeFile).mockImplementationOnce(async (path) => {- await (await actual).writeFile(path, 'partial');- throw new Error('disk full');- });-- await expect(- writeAppAddFile({- appPath: root,- file,- signal: new AbortController().signal,- }),- ).rejects.toThrow('disk full');- expect(await readdir(join(root, 'src/objects'))).toEqual([]);- });-- it('cancels after staging without creating the destination', async () => {- const cancellation = new AbortController();-- vi.mocked(writeFile).mockImplementationOnce(async (...args) => {- await (await actual).writeFile(...args);- cancellation.abort();- });-- await expect(- writeAppAddFile({ appPath: root, file, signal: cancellation.signal }),- ).rejects.toThrow();- expect(await readdir(join(root, 'src/objects'))).toEqual([]);- });-- it('reports completion when cancellation arrives after the file was committed', async () => {- const cancellation = new AbortController();-- vi.mocked(link).mockImplementationOnce(async (...args) => {- await (await actual).link(...args);- cancellation.abort();- });-- await expect(- writeAppAddFile({ appPath: root, file, signal: cancellation.signal }),- ).resolves.toBeUndefined();- expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);- expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);- });-- it('returns a cleanup warning path after a successful commit instead of reporting failure', async () => {- vi.mocked(rm).mockRejectedValueOnce(new Error('cleanup denied'));-- const cleanupPath = await writeAppAddFile({- appPath: root,- file,- signal: new AbortController().signal,- });-- expect(cleanupPath).toContain(join(root, 'src/objects/.twenty-add-'));- expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);- });-});diff --git a/packages/twenty-cli/src/app/add/__tests__/write-app-add-files.spec.ts b/packages/twenty-cli/src/app/add/__tests__/write-app-add-files.spec.tsnew file mode 100644index 00000000000..5db9cc9a5f7--- /dev/null+++ b/packages/twenty-cli/src/app/add/__tests__/write-app-add-files.spec.ts@@ -0,0 +1,249 @@+import {+ link,+ lstat,+ mkdtemp,+ readFile,+ readdir,+ rm,+ unlink,+ writeFile,+} from 'node:fs/promises';+import type * as fileSystemPromises from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { writeAppAddFiles } from '@/app/add/write-app-add-files';++vi.mock('node:fs/promises', async (importOriginal) => {+ const actual = await importOriginal<typeof fileSystemPromises>();++ return {+ ...actual,+ link: vi.fn(actual.link),+ lstat: vi.fn(actual.lstat),+ rm: vi.fn(actual.rm),+ unlink: vi.fn(actual.unlink),+ writeFile: vi.fn(actual.writeFile),+ };+});++describe('app add exclusive file creation', () => {+ let root: string;+ const file = {+ path: 'src/objects/invoice.ts',+ content: 'complete definition',+ };+ const actual = vi.importActual<typeof fileSystemPromises>('node:fs/promises');++ beforeEach(async () => {+ root = await mkdtemp(join(tmpdir(), 'twenty-add-write-'));+ });+ afterEach(async () => {+ vi.restoreAllMocks();+ await rm(root, { recursive: true, force: true });+ });++ it.each(['EACCES', 'EIO'])(+ 'preserves %s from path validation',+ async (code) => {+ const error = Object.assign(new Error('filesystem failure'), { code });+ vi.mocked(lstat).mockRejectedValueOnce(error);+ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: new AbortController().signal,+ }),+ ).rejects.toBe(error);+ expect(link).not.toHaveBeenCalled();+ },+ );++ it('stages beside each destination when directories are on different filesystems', async () => {+ const companion = { path: 'src/views/all-invoice.ts', content: 'view' };+ vi.mocked(link).mockImplementation(async (source, destination) => {+ if (dirname(dirname(String(source))) !== dirname(String(destination))) {+ throw Object.assign(new Error('cross-device link'), { code: 'EXDEV' });+ }+ return (await actual).link(source, destination);+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file, companion],+ signal: new AbortController().signal,+ }),+ ).resolves.toEqual([]);+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);+ expect(await readFile(join(root, companion.path), 'utf8')).toBe(+ companion.content,+ );+ });++ it('preserves a destination created while the new definition was staged', async () => {+ vi.mocked(link).mockImplementationOnce(async (source, destination) => {+ await (await actual).writeFile(destination, 'concurrent user definition');++ return (await actual).link(source, destination);+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: new AbortController().signal,+ }),+ ).rejects.toMatchObject({ code: 'APP_PATH_UNAVAILABLE', exitCode: 6 });+ expect(await readFile(join(root, file.path), 'utf8')).toBe(+ 'concurrent user definition',+ );+ expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);+ });++ it('removes a partial staged write without exposing an incomplete definition', async () => {+ vi.mocked(writeFile).mockImplementationOnce(async (path) => {+ await (await actual).writeFile(path, 'partial');+ throw new Error('disk full');+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: new AbortController().signal,+ }),+ ).rejects.toThrow('disk full');+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);+ });++ it('cancels after staging without creating the destination', async () => {+ const cancellation = new AbortController();++ vi.mocked(writeFile).mockImplementationOnce(async (...args) => {+ await (await actual).writeFile(...args);+ cancellation.abort();+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: cancellation.signal,+ }),+ ).rejects.toThrow();+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);+ });++ it('reports completion when cancellation arrives after the file was committed', async () => {+ const cancellation = new AbortController();++ vi.mocked(link).mockImplementationOnce(async (...args) => {+ await (await actual).link(...args);+ cancellation.abort();+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: cancellation.signal,+ }),+ ).resolves.toEqual([]);+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);+ expect(await readdir(join(root, 'src/objects'))).toEqual(['invoice.ts']);+ });++ it('rolls back earlier files if a companion destination appears during creation', async () => {+ const companion = { path: 'src/views/all-invoice.ts', content: 'view' };+ vi.mocked(link)+ .mockImplementationOnce(async (...args) => (await actual).link(...args))+ .mockImplementationOnce(async (source, destination) => {+ await (await actual).writeFile(destination, 'concurrent view');+ return (await actual).link(source, destination);+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file, companion],+ signal: new AbortController().signal,+ }),+ ).rejects.toMatchObject({ code: 'APP_PATH_UNAVAILABLE', exitCode: 6 });+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);+ expect(await readFile(join(root, companion.path), 'utf8')).toBe(+ 'concurrent view',+ );+ });++ it('rolls back earlier files when cancelled before all definitions are created', async () => {+ const cancellation = new AbortController();+ vi.mocked(link).mockImplementationOnce(async (...args) => {+ await (await actual).link(...args);+ cancellation.abort();+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file, { path: 'src/views/all-invoice.ts', content: 'view' }],+ signal: cancellation.signal,+ }),+ ).rejects.toThrow();+ expect(await readdir(join(root, 'src/objects'))).toEqual([]);+ });++ it('preserves a replacement of an earlier file when a later write fails', async () => {+ vi.mocked(link)+ .mockImplementationOnce(async (...args) => (await actual).link(...args))+ .mockImplementationOnce(async () => {+ const destination = join(root, file.path);+ await (await actual).unlink(destination);+ await (await actual).writeFile(destination, 'replacement object');+ throw new Error('disk full');+ });++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file, { path: 'src/views/all-invoice.ts', content: 'view' }],+ signal: new AbortController().signal,+ }),+ ).rejects.toThrow('disk full');+ expect(await readFile(join(root, file.path), 'utf8')).toBe(+ 'replacement object',+ );+ });++ it('reports files left behind when rollback fails', async () => {+ vi.mocked(link)+ .mockImplementationOnce(async (...args) => (await actual).link(...args))+ .mockRejectedValueOnce(new Error('disk full'));+ vi.mocked(unlink).mockRejectedValueOnce(new Error('permission denied'));++ await expect(+ writeAppAddFiles({+ appPath: root,+ files: [file, { path: 'src/views/all-invoice.ts', content: 'view' }],+ signal: new AbortController().signal,+ }),+ ).rejects.toMatchObject({ details: { createdPaths: [file.path] } });+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);+ });++ it('returns a cleanup warning path after a successful commit instead of reporting failure', async () => {+ vi.mocked(rm).mockRejectedValueOnce(new Error('cleanup denied'));++ const cleanupPaths = await writeAppAddFiles({+ appPath: root,+ files: [file],+ signal: new AbortController().signal,+ });++ expect(cleanupPaths).toHaveLength(1);+ expect(cleanupPaths[0]).toContain(join(root, 'src/objects/.twenty-add-'));+ expect(await readFile(join(root, file.path), 'utf8')).toBe(file.content);+ });+});diff --git a/packages/twenty-cli/src/app/add/create-object-companion-files.ts b/packages/twenty-cli/src/app/add/create-object-companion-files.tsnew file mode 100644index 00000000000..7df28a6373e--- /dev/null+++ b/packages/twenty-cli/src/app/add/create-object-companion-files.ts@@ -0,0 +1,89 @@+import { randomUUID } from 'node:crypto';++import { getFieldUniversalIdentifier } from 'twenty-shared/application';+import { ViewType } from 'twenty-shared/types';++import { getNavigationMenuItemBaseFile } from '@/app/add/entity-navigation-menu-item-template';+import { getRecordPageLayoutBaseFile } from '@/app/add/entity-record-page-layout-template';+import { getViewBaseFile } from '@/app/add/entity-view-template';+import { type AppAddFile } from '@/app/add/types/app-add-file.type';++export const createObjectCompanionFiles = ({+ name,+ labelSingular,+ objectUniversalIdentifier,+ nameFieldUniversalIdentifier,+ applicationUniversalIdentifier,+ createView,+ createNavigationMenuItem,+ createPageLayout,+}: {+ name: string;+ labelSingular: string;+ objectUniversalIdentifier: string;+ nameFieldUniversalIdentifier: string;+ applicationUniversalIdentifier: string;+ createView: boolean;+ createNavigationMenuItem: boolean;+ createPageLayout: boolean;+}): AppAddFile[] => {+ const files: AppAddFile[] = [];++ if (createView) {+ files.push({+ path: `src/views/all-${name}.ts`,+ content: getViewBaseFile({+ name: `all-${name}`,+ objectUniversalIdentifier,+ fieldUniversalIdentifiers: [nameFieldUniversalIdentifier],+ }),+ });+ }++ if (createNavigationMenuItem) {+ files.push({+ path: `src/navigation-menu-items/${name}.ts`,+ content: getNavigationMenuItemBaseFile({+ name,+ objectUniversalIdentifier,+ }),+ });+ }++ if (createPageLayout) {+ const fieldsWidgetViewUniversalIdentifier = randomUUID();+ const fieldUniversalIdentifiers = [+ nameFieldUniversalIdentifier,+ ...['createdAt', 'updatedAt', 'createdBy', 'updatedBy'].map((fieldName) =>+ getFieldUniversalIdentifier({+ applicationUniversalIdentifier,+ objectUniversalIdentifier,+ name: fieldName,+ }),+ ),+ ];++ files.push(+ {+ path: `src/views/${name}-record-page-fields.ts`,+ content: getViewBaseFile({+ name: `${name}-record-page-fields`,+ universalIdentifier: fieldsWidgetViewUniversalIdentifier,+ objectUniversalIdentifier,+ type: ViewType.FIELDS_WIDGET,+ fieldUniversalIdentifiers,+ }),+ },+ {+ path: `src/page-layouts/${name}-record-page-layout.ts`,+ content: getRecordPageLayoutBaseFile({+ objectLabelSingular: labelSingular,+ objectUniversalIdentifier,+ fieldsWidgetViewUniversalIdentifier,+ }),+ },+ );+ }++ return files;+};diff --git a/packages/twenty-cli/src/app/add/entity-navigation-menu-item-template.ts b/packages/twenty-cli/src/app/add/entity-navigation-menu-item-template.tsnew file mode 100644index 00000000000..2620a41ab93--- /dev/null+++ b/packages/twenty-cli/src/app/add/entity-navigation-menu-item-template.ts@@ -0,0 +1,21 @@+import { randomUUID } from 'node:crypto';++import { printTypescriptValue } from '@/app/pull/print-typescript-value';++export const getNavigationMenuItemBaseFile = ({+ name,+ objectUniversalIdentifier,+}: {+ name: string;+ objectUniversalIdentifier: string;+}) => `import { defineNavigationMenuItem, NavigationMenuItemType } from 'twenty-sdk/define';++export default defineNavigationMenuItem({+ universalIdentifier: '${randomUUID()}',+ name: ${printTypescriptValue({ value: name })},+ icon: 'IconCompass',+ position: 0,+ type: NavigationMenuItemType.OBJECT,+ targetObjectUniversalIdentifier: '${objectUniversalIdentifier}',+});+`;diff --git a/packages/twenty-cli/src/app/add/entity-record-page-layout-template.ts b/packages/twenty-cli/src/app/add/entity-record-page-layout-template.tsnew file mode 100644index 00000000000..256fdcf563b--- /dev/null+++ b/packages/twenty-cli/src/app/add/entity-record-page-layout-template.ts@@ -0,0 +1,60 @@+import { randomUUID } from 'node:crypto';++import { printTypescriptValue } from '@/app/pull/print-typescript-value';++export const getRecordPageLayoutBaseFile = ({+ objectLabelSingular,+ objectUniversalIdentifier,+ fieldsWidgetViewUniversalIdentifier,+}: {+ objectLabelSingular: string;+ objectUniversalIdentifier: string;+ fieldsWidgetViewUniversalIdentifier: string;+}) => {+ return `import { definePageLayout, PageLayoutTabLayoutMode, PageLayoutType } from 'twenty-sdk/define';++export default definePageLayout({+ universalIdentifier: '${randomUUID()}',+ name: ${printTypescriptValue({ value: `Default ${objectLabelSingular} Layout` })},+ type: PageLayoutType.RECORD_PAGE,+ objectUniversalIdentifier: '${objectUniversalIdentifier}',+ tabs: [+ {+ universalIdentifier: '${randomUUID()}',+ title: 'Home',+ position: 10,+ icon: 'IconHome',+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,+ widgets: [+ {+ universalIdentifier: '${randomUUID()}',+ title: 'Fields',+ type: 'FIELDS',+ configuration: {+ configurationType: 'FIELDS',+ viewUniversalIdentifier: '${fieldsWidgetViewUniversalIdentifier}',+ },+ },+ ],+ },+ {+ universalIdentifier: '${randomUUID()}',+ title: 'Timeline',+ position: 20,+ icon: 'IconTimelineEvent',+ layoutMode: PageLayoutTabLayoutMode.VERTICAL_LIST,+ widgets: [+ {+ universalIdentifier: '${randomUUID()}',+ title: 'Timeline',+ type: 'TIMELINE',+ configuration: {+ configurationType: 'TIMELINE',+ },+ },+ ],+ },+ ],+});+`;+};diff --git a/packages/twenty-cli/src/app/add/entity-view-template.ts b/packages/twenty-cli/src/app/add/entity-view-template.tsnew file mode 100644index 00000000000..c5f96d6dd1a--- /dev/null+++ b/packages/twenty-cli/src/app/add/entity-view-template.ts@@ -0,0 +1,41 @@+import { randomUUID } from 'node:crypto';++import { VIEW_TYPE_DEFAULT_ICONS } from 'twenty-shared/constants';+import { ViewType } from 'twenty-shared/types';++import { printTypescriptValue } from '@/app/pull/print-typescript-value';++export const getViewBaseFile = ({+ name,+ universalIdentifier = randomUUID(),+ objectUniversalIdentifier,+ fieldUniversalIdentifiers,+ type = ViewType.TABLE,+}: {+ name: string;+ universalIdentifier?: string;+ objectUniversalIdentifier: string;+ fieldUniversalIdentifiers: string[];+ type?: ViewType;+}) => `import { defineView } from 'twenty-sdk/define';++export default defineView(${printTypescriptValue({+ value: {+ universalIdentifier,+ name,+ objectUniversalIdentifier,+ type,+ icon: VIEW_TYPE_DEFAULT_ICONS[type],+ position: 0,+ fields: fieldUniversalIdentifiers.map(+ (fieldMetadataUniversalIdentifier, position) => ({+ universalIdentifier: randomUUID(),+ fieldMetadataUniversalIdentifier,+ position,+ isVisible: true,+ size: 200,+ }),+ ),+ },+})});+`;diff --git a/packages/twenty-cli/src/app/add/prepare-app-add-file.ts b/packages/twenty-cli/src/app/add/prepare-app-add-files.tssimilarity index 83%rename from packages/twenty-cli/src/app/add/prepare-app-add-file.tsrename to packages/twenty-cli/src/app/add/prepare-app-add-files.tsindex df1c8abf8e0..d6aa5c6216d 100644--- a/packages/twenty-cli/src/app/add/prepare-app-add-file.ts+++ b/packages/twenty-cli/src/app/add/prepare-app-add-files.ts@@ -1,3 +1,5 @@+import { randomUUID } from 'node:crypto';+import { isValidUniversalIdentifier } from 'twenty-shared/application';import {FieldMetadataType,@@ -8,6 +10,8 @@ import { isDefined } from 'twenty-shared/utils';import { convertToLabel } from '@/app/convert-to-label';import { APP_ADD_ENTITIES } from '@/app/add/constants/app-add-entities.constant';+import { createObjectCompanionFiles } from '@/app/add/create-object-companion-files';+import { type AppAddFile } from '@/app/add/types/app-add-file.type';import { getFieldBaseFile } from '@/app/add/entity-field-template';import { getFrontComponentBaseFile } from '@/app/add/entity-front-component-template';import { getLogicFunctionBaseFile } from '@/app/add/entity-logic-function-template';@@ -15,6 +19,7 @@ import { getObjectBaseFile } from '@/app/add/entity-object-template';import { promptForAppAddValue } from '@/app/add/prompt-for-app-add-value';import { kebabCase } from '@/app/pull/kebab-case';import {+ readBooleanOption,readStringArgument,readStringOption,} from '@/catalog/read-command-values';@@ -31,7 +36,13 @@ const invalidInput = (message: string) =>hint: 'Run twenty app add --help for options and examples.',});-export const prepareAppAddFile = async (context: CommandContext) => {+export const prepareAppAddFiles = async ({+ context,+ applicationUniversalIdentifier,+}: {+ context: CommandContext;+ applicationUniversalIdentifier: string;+}) => {const { options, signal } = context;const interactive = isInteractionAllowed(context);const readValue = async ({@@ -91,7 +102,13 @@ export const prepareAppAddFile = async (context: CommandContext) => {value: readStringArgument(context.arguments, 0),choices: APP_ADD_ENTITIES,});- const objectOptions = ['namePlural', 'labelPlural'];+ const objectOptions = [+ 'namePlural',+ 'labelPlural',+ 'createView',+ 'createNavigationMenuItem',+ 'createPageLayout',+ ];const fieldOptions = ['type', 'object', 'description'];const relationOptions = ['targetObject',@@ -100,9 +117,7 @@ export const prepareAppAddFile = async (context: CommandContext) => {'onDelete',];const rejectOptions = (names: string[]) => {- const supplied = names.filter((option) =>- isDefined(readStringOption(options, option)),- );+ const supplied = names.filter((option) => isDefined(options[option]));if (supplied.length > 0) {throw invalidInput(@@ -123,6 +138,7 @@ export const prepareAppAddFile = async (context: CommandContext) => {}let content: string;+ let companionFiles: AppAddFile[] = [];switch (entity) {case 'object': {@@ -146,10 +162,28 @@ export const prepareAppAddFile = async (context: CommandContext) => {defaultValue: convertToLabel(namePlural),});+ const objectUniversalIdentifier = randomUUID();+ const nameFieldUniversalIdentifier = randomUUID();+content = getObjectBaseFile({name,+ universalIdentifier: objectUniversalIdentifier,+ nameFieldUniversalIdentifier,data: { nameSingular: name, namePlural, labelSingular, labelPlural },});+ companionFiles = createObjectCompanionFiles({+ name: fileName,+ labelSingular,+ objectUniversalIdentifier,+ nameFieldUniversalIdentifier,+ applicationUniversalIdentifier,+ createView: readBooleanOption(options, 'createView'),+ createNavigationMenuItem: readBooleanOption(+ options,+ 'createNavigationMenuItem',+ ),+ createPageLayout: readBooleanOption(options, 'createPageLayout'),+ });break;}case 'field': {@@ -245,7 +279,12 @@ export const prepareAppAddFile = async (context: CommandContext) => {return {entity,name,- path: `src/${entity}s/${fileName}.${entity === 'front-component' ? 'tsx' : 'ts'}`,- content,+ files: [+ {+ path: `src/${entity}s/${fileName}.${entity === 'front-component' ? 'tsx' : 'ts'}`,+ content,+ },+ ...companionFiles,+ ],};};diff --git a/packages/twenty-cli/src/app/add/types/app-add-file.type.ts b/packages/twenty-cli/src/app/add/types/app-add-file.type.tsnew file mode 100644index 00000000000..a8253403d9d--- /dev/null+++ b/packages/twenty-cli/src/app/add/types/app-add-file.type.ts@@ -0,0 +1,4 @@+export type AppAddFile = {+ path: string;+ content: string;+};diff --git a/packages/twenty-cli/src/app/add/write-app-add-file.ts b/packages/twenty-cli/src/app/add/write-app-add-file.tsdeleted file mode 100644index 0d73f45f481..00000000000--- a/packages/twenty-cli/src/app/add/write-app-add-file.ts+++ /dev/null@@ -1,66 +0,0 @@-import { link, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';-import { dirname, join } from 'node:path';--import { AppPathError } from '@/app/pull/app-path-error';-import { assertPullPaths } from '@/app/pull/assert-pull-paths';-import { CliError } from '@/output/cli-error';-import { EXIT_CODE } from '@/output/constants/exit-code.constant';-import { hasErrorCode } from '@/utils/has-error-code';--export const writeAppAddFile = async ({- appPath,- file,- signal,-}: {- appPath: string;- file: { path: string; content: string };- signal: AbortSignal;-}) => {- signal.throwIfAborted();-- try {- await assertPullPaths({ appPath, relativePaths: [file.path] });- } catch (error) {- if (!(error instanceof AppPathError)) throw error;-- throw new CliError({- code: 'APP_PATH_UNAVAILABLE',- exitCode: EXIT_CODE.CONFLICT,- message: `Cannot create ${file.path}: the destination must stay inside the app and cannot contain symbolic links.`,- });- }-- const destination = join(appPath, file.path);-- await mkdir(dirname(destination), { recursive: true });- signal.throwIfAborted();-- const temporaryDirectory = await mkdtemp(- join(dirname(destination), '.twenty-add-'),- );- const temporaryPath = join(temporaryDirectory, 'definition');- let cleanupFailed = false;-- try {- await writeFile(temporaryPath, file.content, { flag: 'wx' });- signal.throwIfAborted();- await link(temporaryPath, destination);- } catch (error) {- if (hasErrorCode(error, 'EEXIST')) {- throw new CliError({- code: 'APP_PATH_UNAVAILABLE',- exitCode: EXIT_CODE.CONFLICT,- message: `${file.path} already exists. No files were changed.`,- hint: 'Choose a different name, or edit the existing definition.',- });- }-- throw error;- } finally {- await rm(temporaryDirectory, { recursive: true, force: true }).catch(() => {- cleanupFailed = true;- });- }-- return cleanupFailed ? temporaryDirectory : undefined;-};diff --git a/packages/twenty-cli/src/app/add/write-app-add-files.ts b/packages/twenty-cli/src/app/add/write-app-add-files.tsnew file mode 100644index 00000000000..44570a85848--- /dev/null+++ b/packages/twenty-cli/src/app/add/write-app-add-files.ts@@ -0,0 +1,135 @@+import {+ link,+ lstat,+ mkdir,+ mkdtemp,+ rm,+ unlink,+ writeFile,+} from 'node:fs/promises';+import { dirname, join } from 'node:path';++import { type AppAddFile } from '@/app/add/types/app-add-file.type';+import { AppPathError } from '@/app/pull/app-path-error';+import { assertPullPaths } from '@/app/pull/assert-pull-paths';+import { CliError } from '@/output/cli-error';+import { EXIT_CODE } from '@/output/constants/exit-code.constant';+import { hasErrorCode } from '@/utils/has-error-code';++export const writeAppAddFiles = async ({+ appPath,+ files,+ signal,+}: {+ appPath: string;+ files: AppAddFile[];+ signal: AbortSignal;+}) => {+ signal.throwIfAborted();++ for (const file of files) {+ try {+ await assertPullPaths({ appPath, relativePaths: [file.path] });+ await lstat(join(appPath, file.path));+ throw new CliError({+ code: 'APP_PATH_UNAVAILABLE',+ exitCode: EXIT_CODE.CONFLICT,+ message: `${file.path} already exists. No files were changed.`,+ hint: 'Choose a different name, or edit the existing definition.',+ });+ } catch (error) {+ if (error instanceof AppPathError) {+ throw new CliError({+ code: 'APP_PATH_UNAVAILABLE',+ exitCode: EXIT_CODE.CONFLICT,+ message: `Cannot create ${file.path}: the destination must stay inside the app and cannot contain symbolic links.`,+ });+ }+ if (!hasErrorCode(error, 'ENOENT')) throw error;+ }+ }++ const stagedFiles: {+ path: string;+ stagedPath: string;+ temporaryDirectory: string;+ }[] = [];+ const createdFiles: { path: string; stagedPath: string }[] = [];+ const cleanupPaths: string[] = [];++ try {+ for (const file of files) {+ signal.throwIfAborted();+ const destinationDirectory = dirname(join(appPath, file.path));++ await mkdir(destinationDirectory, { recursive: true });+ signal.throwIfAborted();+ const temporaryDirectory = await mkdtemp(+ join(destinationDirectory, '.twenty-add-'),+ );+ const stagedPath = join(temporaryDirectory, 'definition');++ stagedFiles.push({ path: file.path, stagedPath, temporaryDirectory });+ await writeFile(stagedPath, file.content, { flag: 'wx' });+ }++ for (const file of stagedFiles) {+ signal.throwIfAborted();+ const destination = join(appPath, file.path);+ const stagedPath = file.stagedPath;++ try {+ await link(stagedPath, destination);+ } catch (error) {+ if (!hasErrorCode(error, 'EEXIST')) throw error;++ throw new CliError({+ code: 'APP_PATH_UNAVAILABLE',+ exitCode: EXIT_CODE.CONFLICT,+ message: `${file.path} already exists.`,+ hint: 'Choose a different name, or edit the existing definition.',+ });+ }+ createdFiles.push({ path: file.path, stagedPath });+ }+ } catch (error) {+ const remainingPaths: string[] = [];++ for (const file of createdFiles.reverse()) {+ try {+ const destination = join(appPath, file.path);+ const staged = await lstat(file.stagedPath);+ const current = await lstat(destination);++ if (staged.ino !== current.ino || staged.dev !== current.dev) continue;+ await unlink(destination);+ } catch (rollbackError) {+ if (!hasErrorCode(rollbackError, 'ENOENT'))+ remainingPaths.push(file.path);+ }+ }++ if (remainingPaths.length > 0) {+ throw new CliError({+ code: 'APP_PATH_UNAVAILABLE',+ message:+ 'Could not create all definitions or remove all files created by this command.',+ hint: `Review these files before retrying: ${remainingPaths.join(', ')}.`,+ details: { createdPaths: remainingPaths },+ cause: error,+ });+ }++ throw error;+ } finally {+ for (const { temporaryDirectory } of stagedFiles) {+ await rm(temporaryDirectory, { recursive: true, force: true }).catch(+ () => {+ cleanupPaths.push(temporaryDirectory);+ },+ );+ }+ }++ return cleanupPaths;+};diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.tsindex 25e5ee43036..2c7115a353c 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-add.spec.ts@@ -10,6 +10,7 @@ import {import { tmpdir } from 'node:os';import { join } from 'node:path';+import { getFieldUniversalIdentifier } from 'twenty-shared/application';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {@@ -121,6 +122,150 @@ describe('app add', () => {},);+ it.each([+ [true, false, false],+ [false, true, false],+ [false, false, true],+ [true, true, false],+ [true, false, true],+ [false, true, true],+ [true, true, true],+ ])(+ 'creates selected companions, view=%s navigation=%s layout=%s',+ async (createView, createNavigation, createLayout) => {+ const paths = [+ 'src/objects/invoice.ts',+ ...(createView ? ['src/views/all-invoice.ts'] : []),+ ...(createNavigation ? ['src/navigation-menu-items/invoice.ts'] : []),+ ...(createLayout+ ? [+ 'src/views/invoice-record-page-fields.ts',+ 'src/page-layouts/invoice-record-page-layout.ts',+ ]+ : []),+ ];+ const result = await runJson([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ ...(createView ? ['--create-view'] : []),+ ...(createNavigation ? ['--create-navigation-menu-item'] : []),+ ...(createLayout ? ['--create-page-layout'] : []),+ ]);++ expect(result.exitCode, result.stdout).toBe(0);+ expect(result.envelope.data).toMatchObject({ createdPaths: paths });+ const object = await readFile(join(appPath, paths[0]), 'utf8');+ const objectIdentifier = object.match(+ /universalIdentifier: '([^']+)'/,+ )![1];+ const nameFieldIdentifier = object.match(+ /NAME_FIELD_UNIVERSAL_IDENTIFIER =\s*'([^']+)'/,+ )![1];++ for (const path of paths.slice(1)) {+ const content = await readFile(join(appPath, path), 'utf8');+ expect(content).toContain(objectIdentifier);+ if (path.startsWith('src/views/'))+ expect(content).toContain(nameFieldIdentifier);+ }+ if (createLayout) {+ const fieldsView = await readFile(+ join(appPath, 'src/views/invoice-record-page-fields.ts'),+ 'utf8',+ );+ const fieldsViewIdentifier = fieldsView.match(+ /universalIdentifier: '([^']+)'/,+ )![1];+ const layout = await readFile(+ join(appPath, 'src/page-layouts/invoice-record-page-layout.ts'),+ 'utf8',+ );+ expect(layout).toContain(+ `viewUniversalIdentifier: '${fieldsViewIdentifier}'`,+ );+ expect(fieldsView).toContain("type: 'FIELDS_WIDGET'");+ for (const name of [+ 'createdAt',+ 'updatedAt',+ 'createdBy',+ 'updatedBy',+ ]) {+ expect(fieldsView).toContain(+ getFieldUniversalIdentifier({+ applicationUniversalIdentifier: OBJECT_IDENTIFIER,+ objectUniversalIdentifier: objectIdentifier,+ name,+ }),+ );+ }+ }+ expect(promptForAppAddValue).not.toHaveBeenCalled();+ },+ );++ it('refuses a companion collision before creating the object or any other definition', async () => {+ await mkdir(join(appPath, 'src/page-layouts'), { recursive: true });+ const path = join(+ appPath,+ 'src/page-layouts/invoice-record-page-layout.ts',+ );+ await writeFile(path, 'existing layout');+ const result = await runJson([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ '--create-view',+ '--create-page-layout',+ ]);++ expect(result.exitCode).toBe(6);+ expect(await readFile(path, 'utf8')).toBe('existing layout');+ expect(await readdir(join(appPath, 'src'), { recursive: true })).toEqual([+ 'page-layouts',+ 'page-layouts/invoice-record-page-layout.ts',+ ]);+ });++ it('refuses a symlinked companion directory before creating the object', async () => {+ const outside = join(root, 'outside');+ await mkdir(outside);+ await mkdir(join(appPath, 'src'));+ await symlink(outside, join(appPath, 'src/views'));+ const result = await runJson([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ '--create-view',+ ]);++ expect(result.exitCode).toBe(6);+ expect(await readdir(outside)).toEqual([]);+ expect(await readdir(join(appPath, 'src'))).toEqual(['views']);+ });++ it.each([+ '--create-view',+ '--create-navigation-menu-item',+ '--create-page-layout',+ ])('rejects %s for non-object definitions before writing', async (flag) => {+ const result = await runJson([+ 'logic-function',+ '--name',+ 'send-invoice',+ flag,+ ]);+ expect(result.exitCode).toBe(2);+ expect(result.envelope.error.message).toContain(flag);+ expect(await readdir(appPath)).toEqual(['package.json']);+ });+it('uses the containing app from a nested folder and honors --path from outside it', async () => {const nestedPath = join(appPath, 'src', 'nested');diff --git a/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts b/packages/twenty-cli/src/commands/app/add/app-add.command-definition.tsindex 97c07d32dd4..1126a589d04 100644--- a/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts+++ b/packages/twenty-cli/src/commands/app/add/app-add.command-definition.ts@@ -22,6 +22,19 @@ export const APP_ADD_COMMAND_DEFINITION: LocalCommandDefinition = {flags: '--name <name>',description: 'Definition name; also determines the generated filename',},+ {+ flags: '--create-view',+ description: 'Create a table view for the new object',+ },+ {+ flags: '--create-navigation-menu-item',+ description: 'Create a navigation menu item for the new object',+ },+ {+ flags: '--create-page-layout',+ description:+ 'Create a record page layout and its fields view for the new object',+ },{ flags: '--name-plural <name>', description: 'Plural API name (object)' },{flags: '--label <label>',@@ -65,6 +78,7 @@ export const APP_ADD_COMMAND_DEFINITION: LocalCommandDefinition = {examples: ['twenty app add','twenty app add object --name invoice --name-plural invoices --no-input',+ 'twenty app add object --name invoice --name-plural invoices --create-view --create-navigation-menu-item --create-page-layout --no-input','twenty app add field --name amount --type NUMBER --object <object-universal-identifier> --json','twenty app add logic-function --name send-invoice --no-input','twenty app add front-component --name invoice-panel --no-input',diff --git a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts b/packages/twenty-cli/src/commands/app/add/run-app-add-command.tsindex 61d80c74b5c..af3d4967486 100644--- a/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts+++ b/packages/twenty-cli/src/commands/app/add/run-app-add-command.ts@@ -1,7 +1,7 @@import { isDefined } from 'twenty-shared/utils';-import { prepareAppAddFile } from '@/app/add/prepare-app-add-file';-import { writeAppAddFile } from '@/app/add/write-app-add-file';+import { prepareAppAddFiles } from '@/app/add/prepare-app-add-files';+import { writeAppAddFiles } from '@/app/add/write-app-add-files';import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';import { readAppIdentity } from '@/app/read-app-identity';import { resolveAppProject } from '@/app/project/resolve-app-project';@@ -30,31 +30,34 @@ export const runAppAddCommand: CommandRun = async (context) => {output.progress(formatToolingDiagnostic(diagnostic));}- const file = await prepareAppAddFile(context);- const cleanupPath = await writeAppAddFile({+ const { entity, name, files } = await prepareAppAddFiles({+ context,+ applicationUniversalIdentifier: identity.application.universalIdentifier,+ });+ const cleanupPaths = await writeAppAddFiles({appPath: project.path,- file,+ files,signal,});- if (isDefined(cleanupPath)) {+ for (const cleanupPath of cleanupPaths) {output.warn({code: 'APP_ADD_CLEANUP_FAILED',- message: `Created ${file.path}, but could not remove temporary directory ${cleanupPath}.`,+ message: `Created definitions, but could not remove temporary directory ${cleanupPath}.`,});}return {data: {app: project,- entity: file.entity,- name: file.name,- createdPaths: [file.path],+ entity,+ name,+ createdPaths: files.map((file) => file.path),diagnostics: identity.diagnostics,},human: [- formatSuccessLine(`Created ${file.path}`),- ...(file.entity === 'object'+ ...files.map((file) => formatSuccessLine(`Created ${file.path}`)),+ ...(entity === 'object' && files.length === 1? ['Add views, navigation and record-page layouts separately to expose the object in the UI.',]