The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Add app install to the CLI (#28041)
Weiko46e0d0e035d3
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.mdindex 1af1d5e74f0..17ec7cad468 100644--- a/packages/twenty-cli/docs/commands.md+++ b/packages/twenty-cli/docs/commands.md@@ -434,6 +434,22 @@ Failures in reconciliation report `error.details.outcome`: `unchanged` after anThe current export contains metadata and translations, not application source assets or dependency files. Logic-function/front-component code and unsupported metadata are not regenerated. An export with nonempty `files` is refused before writing. Package files, dependency pins and the installed generated client are left alone; pull never installs dependencies. Each export response is limited to 16 MiB. See the [pull implementation](../src/app/pull/README.md) for reconciliation and compatibility details.+## Install a registered app++```bash+twenty app install --remote dev+twenty app install --path ./apps/billing --json+twenty app install --universal-identifier <id> --remote staging --json+```++`app install` installs a package already registered on the target server. It reads the local app definition to find its universal identifier, without building or typechecking the app; `--universal-identifier` works without a local project. Identifiers are sent in lowercase. It requires `APPLICATIONS` permission.++The server selects the registered package and version. Local source changes are not uploaded. For a private package, run `app publish --private` first; publishing to npm alone does not create a server registration. Installation can run app hooks and update an existing installation. Use `app apply` to sync local source instead.++The command waits up to ten minutes for its server installation job to complete, then verifies that the app is installed. JSON returns `application`, `installed: true` and `jobId`. Failed jobs return `INSTALL_FAILED`; missing or mismatched job status is an error, not a successful installation.++Identifier resolution and installation errors include `details.phase`, `details.completedPhases` and `details.outcome`, plus the universal identifier and job identifier when available. Identifier resolution failures report `phase: "identity"` and `outcome: "not-started"`. Ctrl+C or a timeout stops waiting but does not cancel the server job. Run the same command again to retry or resume waiting for an installation that is still running. The command requires the server's `triggerInstallApplication` and `findInstallApplicationJobStatus` APIs, including lookup by `jobId`.+## Uninstall an app```bash@@ -442,7 +458,7 @@ twenty app uninstall --yes --jsontwenty app uninstall --universal-identifier <id> --yes```-`app uninstall` builds the app to find its universal identifier, checks that the app is installed on the target and that the workspace allows uninstalling it, then uninstalls it. `--universal-identifier` skips the build, so an app whose source no longer builds can still be uninstalled. It needs the server's `APPLICATIONS` permission.+`app uninstall` reads the local app definition to find its universal identifier, without building or typechecking the app. It checks that the app is installed on the target and that the workspace allows uninstalling it, then uninstalls it. `--universal-identifier` works without a local project. It needs the server's `APPLICATIONS` permission.Uninstalling runs the app's uninstall hook and deletes everything the app owns, including its objects, fields and their data. It always needs `--yes`, or a yes at the prompt in an interactive terminal; otherwise it stops with `CONFIRMATION_REQUIRED` (exit 2) before changing anything. An app that is not installed returns `APP_NOT_INSTALLED` (exit 4), and one the workspace does not allow to uninstall returns `APP_NOT_UNINSTALLABLE` (exit 6).diff --git a/packages/twenty-cli/src/app/deployment/constants/app-install.constant.ts b/packages/twenty-cli/src/app/deployment/constants/app-install.constant.tsnew file mode 100644index 00000000000..e8f1ef401d4--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/constants/app-install.constant.ts@@ -0,0 +1,4 @@+export const APP_INSTALL = {+ POLL_INTERVAL_MILLISECONDS: 1_000,+ TIMEOUT_MILLISECONDS: 600_000,+} as const;diff --git a/packages/twenty-cli/src/app/deployment/create-install-failure.ts b/packages/twenty-cli/src/app/deployment/create-install-failure.tsnew file mode 100644index 00000000000..9ca5d068a9b--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/create-install-failure.ts@@ -0,0 +1,93 @@+import { isDefined } from 'twenty-shared/utils';++import {+ type AppInstallOutcome,+ type AppInstallPhase,+} from '@/app/deployment/types/app-install-phase.type';+import { withPhaseDetails } from '@/app/deployment/with-phase-details';+import { CliError } from '@/output/cli-error';+import { toCliError } from '@/output/to-cli-error';+import { type CliErrorCode } from '@/output/types/cli-error-code.type';++const REJECTED_BEFORE_INSTALL_CODES = new Set<CliErrorCode>([+ 'AUTH_REQUIRED',+ 'PERMISSION_DENIED',+ 'NOT_FOUND',+]);++const getOutcome = ({+ phase,+ code,+}: {+ phase: AppInstallPhase;+ code: CliErrorCode;+}): AppInstallOutcome => {+ if (+ phase === 'identity' ||+ (phase === 'start' && REJECTED_BEFORE_INSTALL_CODES.has(code))+ ) {+ return 'not-started';+ }++ if (code === 'INSTALL_FAILED') {+ return 'failed';+ }++ return 'unknown';+};++const getRecoveryHint = ({+ outcome,+ phase,+}: {+ outcome: AppInstallOutcome;+ phase: AppInstallPhase;+}) => {+ if (phase === 'identity') {+ return 'Fix the app source or identifier, then retry. No installation was started.';+ }++ if (outcome === 'not-started') {+ return 'Check the target workspace, registration and APPLICATIONS permission before retrying.';+ }++ return 'Run twenty app install again to retry or resume waiting for the current installation. Stopping the CLI does not cancel the server job.';+};++export const createInstallFailure = ({+ error,+ phase,+ completedPhases,+ universalIdentifier,+ jobId,+ signal,+}: {+ error: unknown;+ phase: AppInstallPhase;+ completedPhases: AppInstallPhase[];+ universalIdentifier?: string;+ jobId?: string;+ signal: AbortSignal;+}) => {+ const cliError = toCliError(error, signal);+ const outcome = getOutcome({ phase, code: cliError.code });++ return withPhaseDetails({+ error: new CliError({+ cause: cliError,+ code: cliError.code,+ exitCode: cliError.exitCode,+ message: cliError.message,+ hint: cliError.hint,+ details: {+ ...cliError.details,+ ...(isDefined(universalIdentifier) ? { universalIdentifier } : {}),+ ...(isDefined(jobId) ? { jobId } : {}),+ },+ }),+ phase,+ outcome,+ completedPhases,+ hint: getRecoveryHint({ outcome, phase }),+ });+};diff --git a/packages/twenty-cli/src/app/deployment/install-registered-app.ts b/packages/twenty-cli/src/app/deployment/install-registered-app.tsnew file mode 100644index 00000000000..99af8de3f3c--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/install-registered-app.ts@@ -0,0 +1,99 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isPlainObject } from 'twenty-shared/utils';++import { APP_INSTALL } from '@/app/deployment/constants/app-install.constant';+import { createInstallFailure } from '@/app/deployment/create-install-failure';+import { type AppInstallPhase } from '@/app/deployment/types/app-install-phase.type';+import { waitForAppInstall } from '@/app/deployment/wait-for-app-install';+import { fetchInstalledApp } from '@/app/fetch-installed-app';+import { CliError } from '@/output/cli-error';+import { type ResolvedTarget } from '@/target/types/resolved-target.type';+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';++export const installRegisteredApp = async ({+ universalIdentifier,+ completedPhases,+ target,+ signal,+ onQueued,+}: {+ universalIdentifier: string;+ completedPhases: AppInstallPhase[];+ target: ResolvedTarget;+ signal: AbortSignal;+ onQueued: (jobId: string) => void;+}) => {+ const timeout = AbortSignal.timeout(APP_INSTALL.TIMEOUT_MILLISECONDS);+ const installSignal = AbortSignal.any([signal, timeout]);+ const client = createMetadataClient({ target, signal: installSignal });++ const fail = (error: unknown, phase: AppInstallPhase, jobId?: string) =>+ createInstallFailure({+ error:+ timeout.aborted && !signal.aborted+ ? new CliError({+ code: 'TIMEOUT',+ message: `Timed out waiting for the app installation after ${APP_INSTALL.TIMEOUT_MILLISECONDS / 1_000}s.`,+ })+ : error,+ phase,+ completedPhases,+ universalIdentifier,+ jobId,+ signal,+ });++ const jobId = await client+ .mutation({+ __name: 'TriggerInstallApplication',+ triggerInstallApplication: {+ __args: { input: { universalIdentifier } },+ jobId: true,+ },+ })+ .then((result) => {+ const installation = result?.triggerInstallApplication;++ if (+ !isPlainObject(installation) ||+ !isNonEmptyString(installation.jobId)+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message: 'The server did not return an installation job identifier.',+ });+ }++ return installation.jobId;+ })+ .catch((error: unknown) => {+ throw fail(error, 'start');+ });++ completedPhases.push('start');+ onQueued(jobId);++ await waitForAppInstall({+ universalIdentifier,+ jobId,+ target,+ signal: installSignal,+ }).catch((error: unknown) => {+ throw fail(error, 'wait', jobId);+ });+ completedPhases.push('wait');++ const application = await fetchInstalledApp({+ universalIdentifier,+ target,+ signal: installSignal,+ }).catch((error: unknown) => {+ throw fail(error, 'check', jobId);+ });++ return {+ application: { universalIdentifier, name: application.name },+ installed: true,+ jobId,+ };+};diff --git a/packages/twenty-cli/src/app/deployment/types/app-install-phase.type.ts b/packages/twenty-cli/src/app/deployment/types/app-install-phase.type.tsnew file mode 100644index 00000000000..9f508d32c8c--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/types/app-install-phase.type.ts@@ -0,0 +1,3 @@+export type AppInstallPhase = 'identity' | 'start' | 'wait' | 'check';++export type AppInstallOutcome = 'not-started' | 'failed' | 'unknown';diff --git a/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts b/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.tsindex 49e61984213..bd5caf8ddde 100644--- a/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts+++ b/packages/twenty-cli/src/app/deployment/types/app-uninstall-phase.type.ts@@ -1,5 +1,5 @@export type AppUninstallPhase =- | 'build'+ | 'identity'| 'check'| 'confirmation'| 'uninstall';diff --git a/packages/twenty-cli/src/app/deployment/wait-for-app-install.ts b/packages/twenty-cli/src/app/deployment/wait-for-app-install.tsnew file mode 100644index 00000000000..1e4f2543c53--- /dev/null+++ b/packages/twenty-cli/src/app/deployment/wait-for-app-install.ts@@ -0,0 +1,66 @@+import { isNonEmptyString } from '@sniptt/guards';+import { setTimeout as delay } from 'node:timers/promises';+import { MetadataSchema } from 'twenty-client-sdk/metadata';+import { isPlainObject } from 'twenty-shared/utils';++import { APP_INSTALL } from '@/app/deployment/constants/app-install.constant';+import { CliError } from '@/output/cli-error';+import { type ResolvedTarget } from '@/target/types/resolved-target.type';+import { createMetadataClient } from '@/transport/metadata/create-metadata-client';++export const waitForAppInstall = async ({+ universalIdentifier,+ jobId,+ target,+ signal,+}: {+ universalIdentifier: string;+ jobId: string;+ target: ResolvedTarget;+ signal: AbortSignal;+}) => {+ const client = createMetadataClient({ target, signal });++ while (true) {+ signal.throwIfAborted();+ const data = await client.query({+ __name: 'FindInstallApplicationJobStatus',+ findInstallApplicationJobStatus: {+ __args: { universalIdentifier, jobId },+ jobId: true,+ state: true,+ failedReason: true,+ },+ });+ const status = data?.findInstallApplicationJobStatus;++ if (+ !isPlainObject(status) ||+ status.jobId !== jobId ||+ !Object.values(MetadataSchema.enumJobState).includes(status.state)+ ) {+ throw new CliError({+ code: 'INVALID_RESPONSE',+ message:+ 'The server did not return the status of the requested installation job.',+ });+ }++ if (status.state === 'FAILED') {+ throw new CliError({+ code: 'INSTALL_FAILED',+ message: isNonEmptyString(status.failedReason)+ ? status.failedReason+ : 'The app installation job failed.',+ });+ }++ if (status.state === 'COMPLETED') {+ break;+ }++ await delay(APP_INSTALL.POLL_INTERVAL_MILLISECONDS, undefined, {+ signal,+ });+ }+};diff --git a/packages/twenty-cli/src/app/read-application-identifier.ts b/packages/twenty-cli/src/app/read-application-identifier.tsnew file mode 100644index 00000000000..516fe60dbb5--- /dev/null+++ b/packages/twenty-cli/src/app/read-application-identifier.ts@@ -0,0 +1,64 @@+import { isValidUniversalIdentifier } from 'twenty-shared/application';+import { isDefined } from 'twenty-shared/utils';++import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';+import { resolveAppProject } from '@/app/project/resolve-app-project';+import { readAppIdentity } from '@/app/read-app-identity';+import { readStringOption } from '@/catalog/read-command-values';+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';+import { CliError } from '@/output/cli-error';+import { EXIT_CODE } from '@/output/constants/exit-code.constant';++export const readApplicationIdentifier = async ({+ context,+ onIdentityRead,+}: {+ context: TargetCommandContext;+ onIdentityRead: () => void;+}) => {+ const universalIdentifier = readStringOption(+ context.options,+ 'universalIdentifier',+ );++ if (isDefined(universalIdentifier)) {+ if (!isValidUniversalIdentifier(universalIdentifier)) {+ throw new CliError({+ code: 'INVALID_INPUT',+ exitCode: EXIT_CODE.USAGE,+ message: `--universal-identifier must be a UUID of version 4 or later, not ${universalIdentifier}.`,+ });+ }++ return universalIdentifier.toLowerCase();+ }++ const { options, output, outputMode, signal } = context;+ const project = await resolveAppProject({+ explicitPath: readStringOption(options, 'path'),+ workingDirectory: process.cwd(),+ });+ const identity = await readAppIdentity({+ appPath: project.path,+ signal,+ warn: output.warn,+ });++ if (!isDefined(identity.application)) {+ throw new CliError({+ code: 'INVALID_INPUT',+ exitCode: EXIT_CODE.USAGE,+ message: 'This project has no application definition.',+ });+ }++ if (outputMode === 'human') {+ for (const diagnostic of identity.diagnostics) {+ output.progress(formatToolingDiagnostic(diagnostic));+ }+ }++ onIdentityRead();++ return identity.application.universalIdentifier.toLowerCase();+};diff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.tsindex 8b062f5011b..41f17970e24 100644--- a/packages/twenty-cli/src/catalog/command-catalog.ts+++ b/packages/twenty-cli/src/catalog/command-catalog.ts@@ -1,3 +1,4 @@+import { APP_INSTALL_COMMAND_DEFINITION } from '@/commands/app/install/app-install.command-definition';import { APP_PUBLISH_COMMAND_DEFINITION } from '@/commands/app/publish/app-publish.command-definition';import { APP_DEV_COMMAND_DEFINITION } from '@/commands/app/dev/app-dev.command-definition';import { APP_ADD_COMMAND_DEFINITION } from '@/commands/app/add/app-add.command-definition';@@ -48,6 +49,7 @@ export const COMMAND_CATALOG: CommandDefinition[] = [APP_PUBLISH_COMMAND_DEFINITION,APP_TRANSLATIONS_EXTRACT_COMMAND_DEFINITION,APP_TYPECHECK_COMMAND_DEFINITION,+ APP_INSTALL_COMMAND_DEFINITION,APP_UNINSTALL_COMMAND_DEFINITION,AUTH_LOGIN_COMMAND_DEFINITION,AUTH_LOGOUT_COMMAND_DEFINITION,diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-install.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-install.spec.tsnew file mode 100644index 00000000000..f04002524b8--- /dev/null+++ b/packages/twenty-cli/src/commands/app/__tests__/app-install.spec.ts@@ -0,0 +1,500 @@+import { type ServerResponse } from 'node:http';+import {+ afterAll,+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from 'vitest';++import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';+import {+ parseSingleJsonLine,+ runCliForTest,+} from '@/__tests__/utils/run-cli-for-test';+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';++const readIdentity = vi.hoisted(() => vi.fn());+const timing = vi.hoisted(() => ({+ POLL_INTERVAL_MILLISECONDS: 1,+ TIMEOUT_MILLISECONDS: 5_000,+}));+vi.mock('@/app/read-app-identity', () => ({ readAppIdentity: readIdentity }));+vi.mock('@/app/project/resolve-app-project', () => ({+ resolveAppProject: async ({ explicitPath }: { explicitPath?: string }) => ({+ path: explicitPath ?? '/app/source',+ name: 'Billing App',+ }),+}));+vi.mock('@/app/deployment/constants/app-install.constant', () => ({+ APP_INSTALL: timing,+}));++const UNIVERSAL_IDENTIFIER = '0f3a1c52-7d6e-4b8a-9c21-5e4d3b2a1f00';+const JOB_ID = 'installation-job-1';+const application = {+ name: 'Billing App',+ universalIdentifier: UNIVERSAL_IDENTIFIER,+ canBeUninstalled: true,+};+const state = {+ startResult: { jobId: JOB_ID } as unknown,+ startError: undefined as string | undefined,+ statuses: [] as unknown[],+ statusError: undefined as string | undefined,+ installedApplication: application as unknown,+ holdStart: false,+ heldResponse: undefined as ServerResponse | undefined,+};+const server = await startTestServer((request, response) => {+ const { query } = readGraphqlRequest(request);++ if (query.includes('triggerInstallApplication')) {+ if (state.holdStart) {+ state.heldResponse = response;+ return;+ }+ if (state.startError) {+ return sendJson(response, 200, {+ data: null,+ errors: [+ {+ message: 'Install refused',+ path: ['triggerInstallApplication'],+ extensions: { code: state.startError },+ },+ ],+ });+ }+ return sendJson(response, 200, {+ data: { triggerInstallApplication: state.startResult },+ });+ }+ if (query.includes('findInstallApplicationJobStatus')) {+ if (state.statusError) {+ return sendJson(response, 200, {+ data: null,+ errors: [+ {+ message: 'Status refused',+ path: ['findInstallApplicationJobStatus'],+ extensions: { code: state.statusError },+ },+ ],+ });+ }+ const status =+ state.statuses.length > 1 ? state.statuses.shift() : state.statuses[0];+ return sendJson(response, 200, {+ data: { findInstallApplicationJobStatus: status },+ });+ }+ if (query.includes('findOneApplication')) {+ return sendJson(response, 200, {+ data: { findOneApplication: state.installedApplication },+ });+ }+ return sendJson(response, 400, {+ errors: [{ message: 'Unexpected request' }],+ });+});++const jobStatus = (status: string) => ({+ jobId: JOB_ID,+ state: status,+ failedReason: null,+});+const operationNames = () =>+ server.requests.map((request) => readGraphqlRequest(request).query);+const run = (...args: string[]) => runCliForTest(['app', 'install', ...args]);+const runJson = async (...args: string[]) => {+ const result = await run(...args, '--json');+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };+};+const installByIdentifier = (...args: string[]) =>+ runJson('--universal-identifier', UNIVERSAL_IDENTIFIER, ...args);++describe('app install', () => {+ beforeEach(() => {+ readIdentity.mockReset().mockResolvedValue({+ application: { universalIdentifier: UNIVERSAL_IDENTIFIER },+ diagnostics: [],+ });+ timing.TIMEOUT_MILLISECONDS = 5_000;+ Object.assign(state, {+ startResult: { jobId: JOB_ID },+ startError: undefined,+ statuses: [jobStatus('COMPLETED')],+ statusError: undefined,+ installedApplication: application,+ holdStart: false,+ heldResponse: undefined,+ });+ server.requests.length = 0;+ vi.stubEnv('TWENTY_API_URL', server.url);+ vi.stubEnv('TWENTY_API_KEY', 'install-test-key');+ vi.stubEnv('TWENTY_REMOTE', '');+ });++ afterEach(() => {+ state.heldResponse?.end();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ });+ afterAll(() => server.close());++ it('waits for its queued job and verifies the installation without reading local source', async () => {+ state.statuses = [+ jobStatus('WAITING'),+ jobStatus('ACTIVE'),+ jobStatus('COMPLETED'),+ ];+ const { envelope, exitCode } = await installByIdentifier();++ expect(exitCode).toBe(0);+ expect(envelope.data).toEqual({+ application: {+ name: 'Billing App',+ universalIdentifier: UNIVERSAL_IDENTIFIER,+ },+ installed: true,+ jobId: JOB_ID,+ });+ expect(readIdentity).not.toHaveBeenCalled();+ expect(server.requests).toHaveLength(5);+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({+ input: { universalIdentifier: UNIVERSAL_IDENTIFIER },+ });+ for (const request of server.requests.slice(1, 4)) {+ expect(readGraphqlRequest(request).arguments).toEqual({+ universalIdentifier: UNIVERSAL_IDENTIFIER,+ jobId: JOB_ID,+ });+ }+ expect(operationNames().at(-1)).toContain('findOneApplication');+ expect(+ server.requests.every(+ (request) =>+ request.headers.authorization === 'Bearer install-test-key',+ ),+ ).toBe(true);+ });++ it('reads the local app identifier without uploading or syncing source', async () => {+ const { exitCode } = await runJson('--path', '/app/source');+ expect(exitCode).toBe(0);+ expect(readIdentity).toHaveBeenCalledTimes(1);+ expect(readIdentity).toHaveBeenCalledWith(+ expect.objectContaining({ appPath: '/app/source' }),+ );+ expect(server.requests).toHaveLength(3);+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({+ input: { universalIdentifier: UNIVERSAL_IDENTIFIER },+ });+ });++ it('includes the completed identity read in installation failure details', async () => {+ state.statuses = [jobStatus('FAILED')];+ const { envelope, exitCode } = await runJson();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INSTALL_FAILED',+ details: {+ phase: 'wait',+ outcome: 'failed',+ jobId: JOB_ID,+ completedPhases: ['identity', 'start'],+ },+ });+ expect(readIdentity).toHaveBeenCalledTimes(1);+ });++ it('does not start an install if reading the identity fails', async () => {+ readIdentity.mockRejectedValue(new Error('Broken app source'));+ const { envelope, exitCode } = await runJson();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INTERNAL_ERROR',+ message: 'Broken app source',+ details: {+ phase: 'identity',+ outcome: 'not-started',+ completedPhases: [],+ },+ });+ expect(envelope.error.details).not.toHaveProperty('universalIdentifier');+ expect(envelope.error.details).not.toHaveProperty('jobId');+ expect(envelope.error.hint).toContain('No installation was started');+ expect(readIdentity).toHaveBeenCalledTimes(1);+ expect(server.requests).toHaveLength(0);+ });++ it('does not start an install if the project has no application definition', async () => {+ readIdentity.mockResolvedValue({ application: null, diagnostics: [] });++ const { envelope, exitCode } = await runJson();++ expect(exitCode).toBe(2);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_INPUT',+ message: 'This project has no application definition.',+ details: {+ phase: 'identity',+ outcome: 'not-started',+ completedPhases: [],+ },+ });+ expect(server.requests).toHaveLength(0);+ });++ it('canonicalizes uppercase universal identifiers', async () => {+ const { exitCode } = await runJson(+ '--universal-identifier',+ UNIVERSAL_IDENTIFIER.toUpperCase(),+ );+ expect(exitCode).toBe(0);+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({+ input: { universalIdentifier: UNIVERSAL_IDENTIFIER },+ });+ });++ it('rejects invalid identifiers before reading local source or requesting an install', async () => {+ const { envelope, exitCode } = await runJson(+ '--universal-identifier',+ 'wrong',+ );+ expect(exitCode).toBe(2);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_INPUT',+ details: {+ phase: 'identity',+ outcome: 'not-started',+ completedPhases: [],+ },+ });+ expect(readIdentity).not.toHaveBeenCalled();+ expect(server.requests).toHaveLength(0);+ });++ it.each([null, {}, { jobId: '' }])(+ 'rejects a missing job identifier (%j)',+ async (startResult) => {+ state.startResult = startResult;+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_RESPONSE',+ details: { phase: 'start', outcome: 'unknown', completedPhases: [] },+ });+ expect(server.requests).toHaveLength(1);+ },+ );++ it.each([+ null,+ { jobId: 'another-job', state: 'COMPLETED' },+ { jobId: JOB_ID, state: 'UNKNOWN' },+ ])(+ 'never treats missing or unrelated job status as success (%j)',+ async (status) => {+ state.statuses = [status];+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_RESPONSE',+ details: {+ phase: 'wait',+ outcome: 'unknown',+ jobId: JOB_ID,+ completedPhases: ['start'],+ },+ });+ expect(+ operationNames().some((query) => query.includes('findOneApplication')),+ ).toBe(false);+ },+ );++ it('reports job failures even if an earlier installation still exists', async () => {+ state.statuses = [+ { ...jobStatus('FAILED'), failedReason: 'Post-install hook failed' },+ ];+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INSTALL_FAILED',+ message: 'Post-install hook failed',+ details: {+ phase: 'wait',+ outcome: 'failed',+ jobId: JOB_ID,+ completedPhases: ['start'],+ },+ });+ expect(envelope.error.hint).toContain('Run twenty app install again');+ expect(+ operationNames().some((query) => query.includes('findOneApplication')),+ ).toBe(false);+ });++ it('verifies the installed app identity after completion', async () => {+ state.installedApplication = {+ ...application,+ universalIdentifier: '1f3a1c52-7d6e-4b8a-9c21-5e4d3b2a1f00',+ };+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_RESPONSE',+ details: {+ phase: 'check',+ outcome: 'unknown',+ jobId: JOB_ID,+ completedPhases: ['start', 'wait'],+ },+ });+ });++ it('preserves permission failures without polling', async () => {+ state.startError = 'FORBIDDEN';+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(3);+ expect(envelope.error).toMatchObject({+ code: 'PERMISSION_DENIED',+ details: { phase: 'start', outcome: 'not-started', completedPhases: [] },+ });+ expect(server.requests).toHaveLength(1);+ });++ it('preserves the authentication recovery hint without polling', async () => {+ state.startError = 'UNAUTHENTICATED';+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(3);+ expect(envelope.error).toMatchObject({+ code: 'AUTH_REQUIRED',+ details: { phase: 'start', outcome: 'not-started', completedPhases: [] },+ });+ expect(envelope.error.hint).toContain('TWENTY_API_KEY');+ expect(server.requests).toHaveLength(1);+ });++ it('preserves authentication recovery hints when polling fails after queuing', async () => {+ state.statusError = 'UNAUTHENTICATED';+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(3);+ expect(envelope.error).toMatchObject({+ code: 'AUTH_REQUIRED',+ details: {+ phase: 'wait',+ outcome: 'unknown',+ jobId: JOB_ID,+ completedPhases: ['start'],+ },+ });+ expect(envelope.error.hint).toContain('TWENTY_API_KEY');+ expect(server.requests).toHaveLength(2);+ });++ it('bounds waiting without claiming the server job was cancelled', async () => {+ timing.TIMEOUT_MILLISECONDS = 1_000;+ state.statuses = [jobStatus('ACTIVE')];+ const { envelope, exitCode } = await installByIdentifier();+ expect(exitCode).toBe(1);+ expect(envelope.error).toMatchObject({+ code: 'TIMEOUT',+ message: 'Timed out waiting for the app installation after 1s.',+ details: {+ phase: 'wait',+ outcome: 'unknown',+ jobId: JOB_ID,+ completedPhases: ['start'],+ },+ });+ expect(envelope.error.hint).toContain('does not cancel');+ expect(envelope.error.hint).toContain('Run twenty app install again');+ });++ it('reports cancellation during polling with the queued job identifier', async () => {+ state.statuses = [jobStatus('ACTIVE')];+ const pending = installByIdentifier();+ await vi.waitFor(() => expect(server.requests.length).toBeGreaterThan(1));+ process.emit('SIGINT');+ const { envelope, exitCode } = await pending;+ expect(exitCode).toBe(130);+ expect(envelope.error).toMatchObject({+ code: 'CANCELLED',+ details: {+ phase: 'wait',+ outcome: 'unknown',+ jobId: JOB_ID,+ completedPhases: ['start'],+ },+ });+ });++ it('resumes waiting for the same job when rerun after cancellation', async () => {+ state.statuses = [jobStatus('ACTIVE')];+ const pending = installByIdentifier();+ await vi.waitFor(() => expect(server.requests.length).toBeGreaterThan(1));+ process.emit('SIGINT');+ const cancelled = await pending;+ expect(cancelled.exitCode).toBe(130);+ expect(cancelled.envelope.error.hint).toContain(+ 'Run twenty app install again',+ );++ server.requests.length = 0;+ state.statuses = [jobStatus('COMPLETED')];+ const resumed = await installByIdentifier();++ expect(resumed.exitCode).toBe(0);+ expect(resumed.envelope.data).toMatchObject({+ installed: true,+ jobId: JOB_ID,+ });+ const statusArguments = server.requests+ .map(readGraphqlRequest)+ .filter(({ query }) => query.includes('findInstallApplicationJobStatus'))+ .map((request) => request.arguments);++ expect(statusArguments).toContainEqual({+ universalIdentifier: UNIVERSAL_IDENTIFIER,+ jobId: JOB_ID,+ });+ });++ it('reports uncertainty when interrupted before receiving the job identifier', async () => {+ state.holdStart = true;+ const pending = installByIdentifier();+ await vi.waitFor(() => expect(state.heldResponse).toBeDefined());+ process.emit('SIGINT');+ const { envelope, exitCode } = await pending;+ expect(exitCode).toBe(130);+ expect(envelope.error).toMatchObject({+ code: 'CANCELLED',+ details: { phase: 'start', outcome: 'unknown', completedPhases: [] },+ });+ });++ it('prints success only after installation and appears as a target write command', async () => {+ const { exitCode, stdout } = await run(+ '--universal-identifier',+ UNIVERSAL_IDENTIFIER,+ );+ expect(exitCode).toBe(0);+ expect(stdout).toContain(`Installed Billing App on ${server.url}`);+ const catalog = await runCliForTest(['commands', '--json']);+ expect(parseSingleJsonLine(catalog.stdout).data.commands).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: 'app install',+ writes: true,+ needsTarget: true,+ requiredPermissions: ['APPLICATIONS'],+ }),+ ]),+ );+ });+});diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.tsindex e7a7055f9da..54676c26f2f 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-real-sdk.spec.ts@@ -369,7 +369,7 @@ describe('app commands with CLI snapshots', () => {0,);expect(uninstalled.envelope.data.completedPhases).toEqual([- 'build',+ 'identity','check','uninstall',]);diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.tsindex 87d0b788d08..10bb17f88b5 100644--- a/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts+++ b/packages/twenty-cli/src/commands/app/__tests__/app-uninstall.spec.ts@@ -1,7 +1,6 @@import { buildTestAppWorker } from '@/app/__tests__/utils/build-test-app-worker';-import { writeTestSourceSdk } from '@/app/__tests__/utils/write-test-source-sdk';-import { existsSync } from 'node:fs';-import { rm, mkdtemp, readFile, writeFile } from 'node:fs/promises';+import { createSourceTestApp } from '@/app/source/__tests__/utils/create-source-test-app';+import { rm, mkdtemp, writeFile } from 'node:fs/promises';import { type ServerResponse } from 'node:http';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -41,7 +40,7 @@ let workerDirectory: string;beforeAll(async () => {workerDirectory = await mkdtemp(join(tmpdir(), 'twenty-command-worker-'));- await buildTestAppWorker(workerDirectory, { useToolingFixture: true });+ await buildTestAppWorker(workerDirectory);worker.modulePath = join(workerDirectory, 'app-worker.cjs');}, 60_000);@@ -165,39 +164,17 @@ describe('app uninstall', () => {beforeEach(async () => {appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-uninstall-'));+ await createSourceTestApp(appPath);await writeFile(- join(appPath, 'package.json'),- JSON.stringify({- name: 'uninstall-app',- devDependencies: { 'twenty-sdk': '9.9.9' },- }),+ join(appPath, 'app.ts'),+ `import { defineApplication } from 'twenty-sdk/define';+ export default defineApplication(${JSON.stringify(APPLICATION)});`,);- await writeTestSourceSdk({ appPath });await writeFile(- join(appPath, 'test-tooling.cjs'),- `- const fs = require('node:fs');- const path = require('node:path');- exports.buildSourceSnapshot = async () => {- fs.writeFileSync(path.join(__dirname, 'built.txt'), 'built');- return {- success: true,- data: {- buildId: 'build-id',- contentHash: 'a'.repeat(64),- application: ${JSON.stringify(APPLICATION)},- manifestFormat: 'twenty-application',- manifest: { application: ${JSON.stringify(APPLICATION)} },- files: [],- },- diagnostics: [],- };- };- exports.releaseSourceSnapshot = async ({ buildId }) => {- fs.writeFileSync(path.join(__dirname, 'released.txt'), buildId);- return { success: true, data: null, diagnostics: [] };- };- `,+ join(appPath, 'broken-function.ts'),+ `import { defineLogicFunction } from 'twenty-sdk/define';+ import { handler } from './missing-handler';+ export default defineLogicFunction({ handler });`,);vi.stubEnv('TWENTY_API_URL', server.url);vi.stubEnv('TWENTY_API_KEY', 'uninstall-test-key');@@ -214,15 +191,16 @@ describe('app uninstall', () => {server.requests.length = 0;});- afterEach(() => {+ afterEach(async () => {state.heldUninstallResponse?.end();vi.unstubAllEnvs();vi.restoreAllMocks();+ await rm(appPath, { recursive: true, force: true });});afterAll(() => server.close());- it('finds the app from its build, checks it, then uninstalls it', async () => {+ it('reads the app identity and uninstalls it even with broken function source', async () => {const { envelope, exitCode } = await runJson('--yes');expect(exitCode).toBe(0);@@ -232,18 +210,17 @@ describe('app uninstall', () => {name: APPLICATION.displayName,},uninstalled: true,- completedPhases: ['build', 'check', 'uninstall'],+ completedPhases: ['identity', 'check', 'uninstall'],});expect(operations()).toEqual(['check', 'uninstall']);expect(readGraphqlRequest(server.requests[1]).arguments).toEqual({universalIdentifier: APPLICATION.universalIdentifier,});- expect(await readFile(join(appPath, 'released.txt'), 'utf8')).toBe(- 'build-id',- );});- it('uninstalls by universal identifier without building the project', async () => {+ it('uninstalls by universal identifier without reading the project', async () => {+ await rm(appPath, { recursive: true, force: true });+const { envelope, exitCode } = await runJson('--universal-identifier',APPLICATION.universalIdentifier,@@ -252,7 +229,24 @@ describe('app uninstall', () => {expect(exitCode).toBe(0);expect(envelope.data.completedPhases).toEqual(['check', 'uninstall']);- expect(existsSync(join(appPath, 'built.txt'))).toBe(false);+ });++ it('does not uninstall if the project has no application definition', async () => {+ await rm(join(appPath, 'app.ts'));++ const { envelope, exitCode } = await runJson('--yes');++ expect(exitCode).toBe(2);+ expect(envelope.error).toMatchObject({+ code: 'INVALID_INPUT',+ message: 'This project has no application definition.',+ details: {+ phase: 'identity',+ outcome: 'not-started',+ completedPhases: [],+ },+ });+ expect(server.requests).toHaveLength(0);});it('sends the canonical form of an uppercase universal identifier', async () => {@@ -300,7 +294,7 @@ describe('app uninstall', () => {details: {phase: 'check',outcome: 'not-started',- completedPhases: ['build'],+ completedPhases: ['identity'],},});expect(operations()).toEqual(['check']);@@ -329,7 +323,7 @@ describe('app uninstall', () => {details: {phase: 'confirmation',outcome: 'not-started',- completedPhases: ['build', 'check'],+ completedPhases: ['identity', 'check'],},});expect(operations()).toEqual(['check']);@@ -382,7 +376,7 @@ describe('app uninstall', () => {details: {phase: 'uninstall',outcome,- completedPhases: ['build', 'check'],+ completedPhases: ['identity', 'check'],},});},diff --git a/packages/twenty-cli/src/commands/app/install/app-install.command-definition.ts b/packages/twenty-cli/src/commands/app/install/app-install.command-definition.tsnew file mode 100644index 00000000000..a0b585e851a--- /dev/null+++ b/packages/twenty-cli/src/commands/app/install/app-install.command-definition.ts@@ -0,0 +1,31 @@+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';++export const APP_INSTALL_COMMAND_DEFINITION: TargetCommandDefinition = {+ path: ['app', 'install'],+ description: 'Install a registered app package in the target workspace',+ options: [+ {+ flags: '--path <directory>',+ description:+ 'App directory (default: the app containing the current folder)',+ },+ {+ flags: '--universal-identifier <id>',+ description:+ 'Registered app universal identifier, works without a local project',+ },+ ],+ examples: [+ 'twenty app install --remote dev',+ 'twenty app install --path ./apps/billing --json',+ 'twenty app install --universal-identifier <id> --remote staging --json',+ ],+ outputModes: ['human', 'json'],+ writes: true,+ needsProject: true,+ needsTarget: true,+ requiredPermissions: ['APPLICATIONS'],+ load: async () =>+ (await import('@/commands/app/install/run-app-install-command'))+ .runAppInstallCommand,+};diff --git a/packages/twenty-cli/src/commands/app/install/run-app-install-command.ts b/packages/twenty-cli/src/commands/app/install/run-app-install-command.tsnew file mode 100644index 00000000000..f44749f7c92--- /dev/null+++ b/packages/twenty-cli/src/commands/app/install/run-app-install-command.ts@@ -0,0 +1,44 @@+import { createInstallFailure } from '@/app/deployment/create-install-failure';+import { installRegisteredApp } from '@/app/deployment/install-registered-app';+import { type AppInstallPhase } from '@/app/deployment/types/app-install-phase.type';+import { readApplicationIdentifier } from '@/app/read-application-identifier';+import { type CommandRun } from '@/catalog/types/command-run.type';+import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';+import { formatDataValue } from '@/data/format-data-value';+import { formatSuccessLine } from '@/output/style';++export const runAppInstallCommand: CommandRun<TargetCommandContext> = async (+ context,+) => {+ const { target, signal, output } = context;+ const completedPhases: AppInstallPhase[] = [];+ const universalIdentifier = await readApplicationIdentifier({+ context,+ onIdentityRead: () => completedPhases.push('identity'),+ }).catch((error: unknown) => {+ throw createInstallFailure({+ error,+ phase: 'identity',+ completedPhases,+ signal,+ });+ });++ output.progress(`Installing the registered app on ${target.apiUrl}…`);++ const result = await installRegisteredApp({+ universalIdentifier,+ completedPhases,+ target,+ signal,+ onQueued: (jobId) =>+ output.progress(`Waiting for installation ${formatDataValue(jobId)}…`),+ });++ return {+ data: result,+ human: formatSuccessLine(+ `Installed ${formatDataValue(result.application.name)} on ${target.apiUrl}`,+ ),+ };+};diff --git a/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts b/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.tsindex 5cfd7b8bfbe..a4b2d8cabaa 100644--- a/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts+++ b/packages/twenty-cli/src/commands/app/uninstall/app-uninstall.command-definition.ts@@ -13,7 +13,7 @@ export const APP_UNINSTALL_COMMAND_DEFINITION: TargetCommandDefinition = {{flags: '--universal-identifier <id>',description:- 'Uninstall the app with this universal identifier without building the project, for example when the build is broken',+ 'Uninstall the app with this universal identifier, works without a local project',},{flags: '--yes',diff --git a/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.tsindex 2f42445d838..4dacca490d3 100644--- a/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts+++ b/packages/twenty-cli/src/commands/app/uninstall/run-app-uninstall-command.ts@@ -1,16 +1,10 @@-import { isValidUniversalIdentifier } from 'twenty-shared/application';-import { isDefined } from 'twenty-shared/utils';-import { createUninstallFailure } from '@/app/deployment/create-uninstall-failure';import { fetchInstalledApp } from '@/app/fetch-installed-app';import { requireApproval } from '@/app/deployment/require-approval';-import { runAppBuild } from '@/app/run-app-operation';+import { readApplicationIdentifier } from '@/app/read-application-identifier';import { type AppUninstallPhase } from '@/app/deployment/types/app-uninstall-phase.type';import { uninstallApp } from '@/app/deployment/uninstall-app';-import {- readBooleanOption,- readStringOption,-} from '@/catalog/read-command-values';+import { readBooleanOption } from '@/catalog/read-command-values';import { type CommandRun } from '@/catalog/types/command-run.type';import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';import { formatDataValue } from '@/data/format-data-value';@@ -19,23 +13,6 @@ import { EXIT_CODE } from '@/output/constants/exit-code.constant';import { dimText, formatSuccessLine } from '@/output/style';import { isInteractionAllowed } from '@/program/is-interaction-allowed';-const readUniversalIdentifierOption = (options: Record<string, unknown>) => {- const universalIdentifier = readStringOption(options, 'universalIdentifier');-- if (- isDefined(universalIdentifier) &&- !isValidUniversalIdentifier(universalIdentifier)- ) {- throw new CliError({- code: 'INVALID_INPUT',- exitCode: EXIT_CODE.USAGE,- message: `--universal-identifier must be a UUID of version 4 or later, not ${universalIdentifier}.`,- });- }-- return universalIdentifier;-};-export const runAppUninstallCommand: CommandRun<TargetCommandContext> = async (context,) => {@@ -44,21 +21,12 @@ export const runAppUninstallCommand: CommandRun<TargetCommandContext> = async (const fail = (error: unknown, phase: AppUninstallPhase) =>createUninstallFailure({ error, phase, completedPhases, signal });- const readApplicationIdentifier = async () => {- const explicitIdentifier = readUniversalIdentifierOption(options);-- if (isDefined(explicitIdentifier)) {- return explicitIdentifier;- }-- const { data: build } = await runAppBuild({ context });-- completedPhases.push('build');-- return build.application.universalIdentifier;- };-- const universalIdentifier = (await readApplicationIdentifier()).toLowerCase();+ const universalIdentifier = await readApplicationIdentifier({+ context,+ onIdentityRead: () => completedPhases.push('identity'),+ }).catch((error: unknown) => {+ throw fail(error, 'identity');+ });output.progress(`Checking the app on ${target.apiUrl}…`);diff --git a/packages/twenty-cli/src/output/types/cli-error-code.type.ts b/packages/twenty-cli/src/output/types/cli-error-code.type.tsindex 7ac7b4b8b1e..a8bf2d44bf2 100644--- a/packages/twenty-cli/src/output/types/cli-error-code.type.ts+++ b/packages/twenty-cli/src/output/types/cli-error-code.type.ts@@ -25,6 +25,7 @@ export type CliErrorCode =| 'HTTP_ERROR'| 'IDENTITY_READ_FAILED'| 'INCOMPLETE_TARGET'+ | 'INSTALL_FAILED'| 'INTERNAL_ERROR'| 'INVALID_API_URL'| 'INVALID_APP_NAME'