The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(cli): offer object UI companions interactively (#27603)
Weiko3239ed442881
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex 36221db4f0d..cbe4f1c6890 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -228,9 +228,12 @@ Objects can also create optional UI definitions:- `--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`,+Combine these flags to select what to generate without a companion prompt.+Without any creation flags, a human interactive terminal asks whether to create+all three, defaulting to No. Press Enter or answer No to create only the object.+With `--no-input`, `--json`, redirected stdin or CI, companions are created only+when explicitly requested by flags. These flags are valid only for objects.+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` anddiff --git a/packages/twenty-cli/src/app/add/README.md b/packages/twenty-cli/src/app/add/README.mdindex 5b35ce9797a..f5779d8c41d 100644--- a/packages/twenty-cli/src/app/add/README.md+++ b/packages/twenty-cli/src/app/add/README.md@@ -23,6 +23,10 @@ the same helper as app init.create the fields view used by their Fields widget. The list view and fieldsview reuse the object's name field. Fields views also include the SDK'sgenerated audit fields, resolved using the application's universal identifier.+ With no creation flags, human interactive mode offers all three together,+ defaulting to No. Explicit creation flags bypass that question. Noninteractive+ modes never ask and create only explicitly selected companions. All prompts+ complete before any files are written, including on cancellation.- 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'sdiff --git a/packages/twenty-cli/src/app/add/prepare-app-add-files.ts b/packages/twenty-cli/src/app/add/prepare-app-add-files.tsindex d6aa5c6216d..1aa6b4f75ab 100644--- a/packages/twenty-cli/src/app/add/prepare-app-add-files.ts+++ b/packages/twenty-cli/src/app/add/prepare-app-add-files.ts@@ -16,7 +16,6 @@ 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 { 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,@@ -24,6 +23,8 @@ import {readStringOption,} from '@/catalog/read-command-values';import { type CommandContext } from '@/catalog/types/command-context.type';+import { confirmInTerminal } from '@/input/confirm-in-terminal';+import { promptInTerminal } from '@/input/prompt-in-terminal';import { CliError } from '@/output/cli-error';import { EXIT_CODE } from '@/output/constants/exit-code.constant';import { isInteractionAllowed } from '@/program/is-interaction-allowed';@@ -64,7 +65,7 @@ export const prepareAppAddFiles = async ({const choiceHint = choices ? ` (${choices.join(', ')})` : '';const defaultHint = isDefined(defaultValue) ? ` [${defaultValue}]` : '';- value = await promptForAppAddValue({+ value = await promptInTerminal({question: `${label}${choiceHint}${defaultHint}: `,signal,});@@ -162,6 +163,30 @@ export const prepareAppAddFiles = async ({defaultValue: convertToLabel(namePlural),});+ const companions = {+ createView: readBooleanOption(options, 'createView'),+ createNavigationMenuItem: readBooleanOption(+ options,+ 'createNavigationMenuItem',+ ),+ createPageLayout: readBooleanOption(options, 'createPageLayout'),+ };++ if (+ interactive &&+ !Object.values(companions).some((isSelected) => isSelected)+ ) {+ const shouldCreateCompanions = await confirmInTerminal({+ question:+ 'Also create a view, navigation menu item, and record page layout for this object?',+ signal,+ });++ companions.createView = shouldCreateCompanions;+ companions.createNavigationMenuItem = shouldCreateCompanions;+ companions.createPageLayout = shouldCreateCompanions;+ }+const objectUniversalIdentifier = randomUUID();const nameFieldUniversalIdentifier = randomUUID();@@ -177,12 +202,7 @@ export const prepareAppAddFiles = async ({objectUniversalIdentifier,nameFieldUniversalIdentifier,applicationUniversalIdentifier,- createView: readBooleanOption(options, 'createView'),- createNavigationMenuItem: readBooleanOption(- options,- 'createNavigationMenuItem',- ),- createPageLayout: readBooleanOption(options, 'createPageLayout'),+ ...companions,});break;}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 2c7115a353c..75f582f8305 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@@ -18,15 +18,18 @@ import {runCliForTest,} from '@/__tests__/utils/run-cli-for-test';import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';-import { promptForAppAddValue } from '@/app/add/prompt-for-app-add-value';import { readAppIdentity } from '@/app/read-app-identity';+import { confirmInTerminal } from '@/input/confirm-in-terminal';+import { promptInTerminal } from '@/input/prompt-in-terminal';import { CliError } from '@/output/cli-error';vi.mock('@/app/read-app-identity', () => ({ readAppIdentity: vi.fn() }));-vi.mock('@/app/add/prompt-for-app-add-value', () => ({- promptForAppAddValue: vi.fn(),+vi.mock('@/input/prompt-in-terminal', () => ({+ promptInTerminal: vi.fn(),}));+vi.mock('@/input/confirm-in-terminal', () => ({ confirmInTerminal: vi.fn() }));+const OBJECT_IDENTIFIER = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';describe('app add', () => {@@ -58,7 +61,8 @@ describe('app add', () => {},diagnostics: [],});- vi.mocked(promptForAppAddValue).mockReset();+ vi.mocked(promptInTerminal).mockReset();+ vi.mocked(confirmInTerminal).mockReset().mockResolvedValue(false);});afterEach(async () => {@@ -118,7 +122,7 @@ describe('app add', () => {expect(await readdir(join(appPath, 'src'), { recursive: true })).toEqual(expect.arrayContaining([path.slice(4)]),);- expect(vi.mocked(promptForAppAddValue)).not.toHaveBeenCalled();+ expect(vi.mocked(promptInTerminal)).not.toHaveBeenCalled();},);@@ -202,7 +206,7 @@ describe('app add', () => {);}}- expect(promptForAppAddValue).not.toHaveBeenCalled();+ expect(promptInTerminal).not.toHaveBeenCalled();},);@@ -360,7 +364,7 @@ describe('app add', () => {expect(result.exitCode, result.stdout).toBe(2);expect(result.envelope.error.code).toBe('USAGE');- expect(promptForAppAddValue).not.toHaveBeenCalled();+ expect(promptInTerminal).not.toHaveBeenCalled();expect(await readdir(appPath)).toEqual(['package.json']);},);@@ -427,7 +431,7 @@ describe('app add', () => {vi.spyOn(process, 'stdin', 'get').mockReturnValue(createStandardInputStub({ isTerminal: true }),);- vi.mocked(promptForAppAddValue)+ vi.mocked(promptInTerminal).mockResolvedValueOnce('logic-function').mockResolvedValueOnce('send-invoice');const result = await run([]);@@ -436,14 +440,153 @@ describe('app add', () => {expect(result.stdout).toContain('Created src/logic-functions/send-invoice.ts',);- expect(promptForAppAddValue).toHaveBeenCalledTimes(2);+ expect(promptInTerminal).toHaveBeenCalledTimes(2);+ });++ it.each([false, true])(+ 'offers all companions before writing, accepted=%s',+ async (accepted) => {+ vi.stubEnv('CI', 'false');+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(+ createStandardInputStub({ isTerminal: true }),+ );+ vi.mocked(confirmInTerminal).mockImplementation(async () => {+ expect(await readdir(appPath)).toEqual(['package.json']);+ return accepted;+ });++ const result = await run([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ '--label',+ 'Invoice',+ '--label-plural',+ 'Invoices',+ ]);++ expect(result.exitCode, result.stderr).toBe(0);+ expect(confirmInTerminal).toHaveBeenCalledExactlyOnceWith({+ question:+ 'Also create a view, navigation menu item, and record page layout for this object?',+ signal: expect.any(AbortSignal),+ });+ expect(result.stdout).toContain('Created src/objects/invoice.ts');+ expect(result.stdout.includes('Created src/views/all-invoice.ts')).toBe(+ accepted,+ );+ expect(+ result.stdout.includes('Created src/navigation-menu-items/invoice.ts'),+ ).toBe(accepted);+ expect(+ result.stdout.includes(+ 'Created src/page-layouts/invoice-record-page-layout.ts',+ ),+ ).toBe(accepted);+ expect(await readdir(join(appPath, 'src'))).toEqual(+ accepted+ ? ['navigation-menu-items', 'objects', 'page-layouts', 'views']+ : ['objects'],+ );+ },+ );++ it.each([+ '--create-view',+ '--create-navigation-menu-item',+ '--create-page-layout',+ ])('honors %s without asking about other companions', async (flag) => {+ vi.stubEnv('CI', 'false');+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(+ createStandardInputStub({ isTerminal: true }),+ );+ const result = await run([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ '--label',+ 'Invoice',+ '--label-plural',+ 'Invoices',+ flag,+ ]);++ expect(result.exitCode, result.stderr).toBe(0);+ expect(confirmInTerminal).not.toHaveBeenCalled();+ expect(result.stdout.includes('Created src/views/all-invoice.ts')).toBe(+ flag === '--create-view',+ );+ expect(+ result.stdout.includes('Created src/navigation-menu-items/invoice.ts'),+ ).toBe(flag === '--create-navigation-menu-item');+ expect(+ result.stdout.includes(+ 'Created src/page-layouts/invoice-record-page-layout.ts',+ ),+ ).toBe(flag === '--create-page-layout');+ });++ it.each([+ { flags: ['--no-input'], isTerminal: true, continuousIntegration: 'false' },+ { flags: ['--json'], isTerminal: true, continuousIntegration: 'false' },+ { flags: [], isTerminal: false, continuousIntegration: 'false' },+ { flags: [], isTerminal: true, continuousIntegration: 'true' },+ ])(+ 'creates only the object without prompting in noninteractive mode %j',+ async ({ flags, isTerminal, continuousIntegration }) => {+ vi.stubEnv('CI', continuousIntegration);+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(+ createStandardInputStub({ isTerminal }),+ );+ const result = await run([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ ...flags,+ ]);++ expect(result.exitCode, result.stderr).toBe(0);+ expect(confirmInTerminal).not.toHaveBeenCalled();+ expect(promptInTerminal).not.toHaveBeenCalled();+ expect(await readdir(join(appPath, 'src'))).toEqual(['objects']);+ },+ );++ it('leaves all files untouched when the companion prompt is cancelled', async () => {+ vi.stubEnv('CI', 'false');+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(+ createStandardInputStub({ isTerminal: true }),+ );+ vi.mocked(confirmInTerminal).mockRejectedValue(+ new CliError({ code: 'CANCELLED', message: 'Cancelled.', exitCode: 130 }),+ );+ const result = await run([+ 'object',+ '--name',+ 'invoice',+ '--name-plural',+ 'invoices',+ '--label',+ 'Invoice',+ '--label-plural',+ 'Invoices',+ ]);++ expect(result.exitCode).toBe(130);+ expect(await readdir(appPath)).toEqual(['package.json']);});it('does not prompt with --no-input', async () => {const result = await run(['object', '--no-input']);expect(result.exitCode).toBe(2);- expect(promptForAppAddValue).not.toHaveBeenCalled();+ expect(promptInTerminal).not.toHaveBeenCalled();expect(await readdir(appPath)).toEqual(['package.json']);});@@ -461,7 +604,7 @@ describe('app add', () => {expect(result.exitCode).toBe(1);expect(result.stderr).toContain('No application definition found');- expect(promptForAppAddValue).not.toHaveBeenCalled();+ expect(promptInTerminal).not.toHaveBeenCalled();expect(await readdir(appPath)).toEqual(['package.json']);});@@ -470,7 +613,7 @@ describe('app add', () => {vi.spyOn(process, 'stdin', 'get').mockReturnValue(createStandardInputStub({ isTerminal: true }),);- vi.mocked(promptForAppAddValue).mockRejectedValue(+ vi.mocked(promptInTerminal).mockRejectedValue(new CliError({ code: 'CANCELLED', message: 'Cancelled.', exitCode: 130 }),);diff --git a/packages/twenty-cli/src/input/__tests__/confirm-in-terminal.spec.ts b/packages/twenty-cli/src/input/__tests__/confirm-in-terminal.spec.tsnew file mode 100644index 00000000000..c917a5e6555--- /dev/null+++ b/packages/twenty-cli/src/input/__tests__/confirm-in-terminal.spec.ts@@ -0,0 +1,79 @@+import { EventEmitter } from 'node:events';+import { createInterface } from 'node:readline/promises';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { confirmInTerminal } from '@/input/confirm-in-terminal';++vi.mock('node:readline/promises', () => ({ createInterface: vi.fn() }));++const createTerminal = () => {+ const terminal = Object.assign(new EventEmitter(), {+ question:+ vi.fn<+ (question: string, options: { signal: AbortSignal }) => Promise<string>+ >(),+ close: vi.fn(),+ });+ vi.mocked(createInterface).mockReturnValue(+ terminal as unknown as ReturnType<typeof createInterface>,+ );+ return terminal;+};++describe('terminal confirmation', () => {+ afterEach(() => vi.restoreAllMocks());++ it.each([+ ['', false],+ ['n', false],+ ['no', false],+ ['y', true],+ [' YES ', true],+ ])(+ 'defaults to No and accepts explicit Yes, answer=%j',+ async (answer, expected) => {+ const terminal = createTerminal();+ terminal.question.mockResolvedValue(answer);+ await expect(+ confirmInTerminal({+ question: 'Create companions?',+ signal: new AbortController().signal,+ }),+ ).resolves.toBe(expected);+ expect(terminal.question).toHaveBeenCalledWith(+ 'Create companions? [y/N] ',+ { signal: expect.any(AbortSignal) },+ );+ expect(terminal.close).toHaveBeenCalledOnce();+ },+ );++ it.each(['SIGINT', 'close', 'abort'])(+ 'returns cancellation when interrupted by %s',+ async (event) => {+ const terminal = createTerminal();+ const controller = new AbortController();+ terminal.question.mockImplementation(+ async (_question, { signal }) =>+ new Promise((_resolve, reject) => {+ signal.addEventListener('abort', () => reject(signal.reason), {+ once: true,+ });+ }),+ );+ const result = confirmInTerminal({+ question: 'Create companions?',+ signal: controller.signal,+ });+ const assertion = expect(result).rejects.toMatchObject({+ code: 'CANCELLED',+ exitCode: 130,+ });+ if (event === 'abort') controller.abort();+ else terminal.emit(event);+ await assertion;+ expect(terminal.close).toHaveBeenCalledOnce();+ },+ );+});diff --git a/packages/twenty-cli/src/input/confirm-in-terminal.ts b/packages/twenty-cli/src/input/confirm-in-terminal.tsindex ef668952641..0bf5018e144 100644--- a/packages/twenty-cli/src/input/confirm-in-terminal.ts+++ b/packages/twenty-cli/src/input/confirm-in-terminal.ts@@ -1,4 +1,4 @@-import { createInterface } from 'node:readline/promises';+import { promptInTerminal } from '@/input/prompt-in-terminal';const YES_ANSWER_PATTERN = /^y(es)?$/i;@@ -9,16 +9,10 @@ export const confirmInTerminal = async ({question: string;signal: AbortSignal;}) => {- const terminal = createInterface({- input: process.stdin,- output: process.stderr,+ const answer = await promptInTerminal({+ question: `${question} [y/N] `,+ signal,});- try {- const answer = await terminal.question(`${question} [y/N] `, { signal });-- return YES_ANSWER_PATTERN.test(answer.trim());- } finally {- terminal.close();- }+ return YES_ANSWER_PATTERN.test(answer.trim());};diff --git a/packages/twenty-cli/src/app/add/prompt-for-app-add-value.ts b/packages/twenty-cli/src/input/prompt-in-terminal.tssimilarity index 94%rename from packages/twenty-cli/src/app/add/prompt-for-app-add-value.tsrename to packages/twenty-cli/src/input/prompt-in-terminal.tsindex 4e91d4d8e10..083519646ea 100644--- a/packages/twenty-cli/src/app/add/prompt-for-app-add-value.ts+++ b/packages/twenty-cli/src/input/prompt-in-terminal.ts@@ -2,7 +2,7 @@ import { createInterface } from 'node:readline/promises';import { createCancelledError } from '@/output/create-cancelled-error';-export const promptForAppAddValue = async ({+export const promptInTerminal = async ({question,signal,}: {