Skip to content

The open alternative to Salesforce, designed for AI.

feat(cli): add twenty app generate-client (#28015)

Weiko20e3954257d2
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.md
index 0c05e47e3f0..be4c3ae18ac 100644
--- a/packages/twenty-cli/docs/commands.md
+++ b/packages/twenty-cli/docs/commands.md
@@ -334,7 +334,7 @@ twenty app apply --no-delete
- **Uploads.** File bytes go straight to the upload URLs the server returns, without the CLI's credentials. Each file is checked against the build's size and SHA-256 before anything is uploaded.
- **Pull baseline.** After an acknowledged sync, the CLI fetches the workspace ID and fresh application export, then atomically records `.twenty/cli/pull-base.json`. This baseline lets `app pull` distinguish workspace changes from local edits. It is bound to the normalized API URL, workspace UUID and app UUID. JSON reports `pullBase: "recorded"`, `"failed"` or `"unsupported"`; only a recorded base adds `pullBase` to `completedPhases`. Invalid exports or file-write errors preserve the prior base, warn with `PULL_BASE_NOT_RECORDED`, and allow client generation to continue. A server without the export API reports `"unsupported"` without a warning on every apply. The export is recorded as the server sent it; collections it lacks are read as empty by pull. Cancellation before the base is committed exits 130 with `outcome: "applied"` and `phase: "pullBase"`.
- **Typed client.** After the sync, the CLI fetches the app's GraphQL schema from the workspace and calls the app's own `twenty-client-sdk/generate` to regenerate the client in the app's own `node_modules/twenty-client-sdk` (`clientGeneration: "generated"`). It is skipped with a `CLIENT_NOT_GENERATED` warning when the app has no `node_modules/twenty-client-sdk` of its own, as in a hoisted workspace. A symlinked client package is followed and its target rewritten, so don't apply two apps that share one client package at the same time.
-- **Failures.** A failed apply reports `details.phase`, `details.completedPhases` and `details.outcome`: `not-started` when the failing step changed nothing, `partial` when some files were uploaded, `unknown` when a request was sent but its effect is not known, such as a failed or interrupted sync, and `applied` when the sync succeeded but baseline recording was cancelled or client generation failed. Earlier steps, like a new registration, stay done. There is no rollback and no automatic retry: run `twenty app plan` to see where the workspace stands, then apply again. After `applied`, the workspace has the new version but the client files may be incomplete: fix the problem, then run `twenty app apply` again, which repeats the plan, upload and sync before regenerating the client. Ctrl+C exits with 130 and reports the step it interrupted.
+- **Failures.** A failed apply reports `details.phase`, `details.completedPhases` and `details.outcome`: `not-started` when the failing step changed nothing, `partial` when some files were uploaded, `unknown` when a request was sent but its effect is not known, such as a failed or interrupted sync, and `applied` when the sync succeeded but baseline recording was cancelled or client generation failed. Earlier steps, like a new registration, stay done. There is no rollback and no automatic retry: run `twenty app plan` to see where the workspace stands, then apply again. When client generation failed, the workspace has the new version but the client files may be incomplete: fix the problem, then run `twenty app generate-client`, which regenerates the client without syncing again. Ctrl+C exits with 130 and reports the step it interrupted.
Remote changes made between the plan and the sync can change what the sync does. Remote changes between the acknowledged sync and the export can also enter the saved baseline without appearing in local source; this is not an atomic server snapshot of the sync. Planning, a failed sync, or a sync with an unknown outcome never advances the baseline.
@@ -381,7 +381,7 @@ Compilation pauses during generation, then explicitly rebuilds. Unchanged client
inputs and unchanged build output prevent a generation/sync loop. A schema fetch
failure keeps the old client and prints a warning. If generation starts writing
and fails, dev stops because the client files may be incomplete; fix the problem
-and run `twenty app apply` before restarting dev.
+and run `twenty app generate-client` before restarting dev.
Use human output or `--format ndjson`; `--json` is rejected before target lookup.
NDJSON uses ordered `progress` events with `data.kind`: `watch-ready`,
@@ -397,6 +397,17 @@ the cause and restart `twenty app dev`. A killed process can leave temporary
folders in `.twenty/cli/snapshots`. After stopping all dev/apply sessions for that
app, abandoned snapshot folders can be removed.
+## Regenerate the typed client
+
+```bash
+twenty app generate-client --remote dev
+twenty app generate-client --path ./apps/billing --json
+```
+
+`app generate-client` fetches the app's GraphQL schema from the workspace and regenerates the typed client in the app's own `node_modules/twenty-client-sdk`, the same step `app apply` and `app dev` run after a sync, without building, uploading or syncing. Use it after installing dependencies, after a failed client generation, or to pick up schema changes made in the workspace. It needs no server permission flag.
+
+The app must already be installed in the workspace; otherwise the command fails with `APP_NOT_INSTALLED` (exit 4), and `twenty app apply` installs it and generates the client. An app without its own `node_modules/twenty-client-sdk`, as in a hoisted workspace, fails with `CLIENT_SDK_NOT_INSTALLED` instead of the warning `app apply` prints.
+
## Pull an app
```bash
diff --git a/packages/twenty-cli/src/app/create-app-not-installed-error.ts b/packages/twenty-cli/src/app/create-app-not-installed-error.ts
index 05a31395a3c..a511ac4f6f0 100644
--- a/packages/twenty-cli/src/app/create-app-not-installed-error.ts
+++ b/packages/twenty-cli/src/app/create-app-not-installed-error.ts
@@ -4,13 +4,16 @@ import { EXIT_CODE } from '@/output/constants/exit-code.constant';
export const createAppNotInstalledError = ({
universalIdentifier,
apiUrl,
+ hint,
}: {
universalIdentifier: string;
apiUrl: string;
+ hint?: string;
}) =>
new CliError({
code: 'APP_NOT_INSTALLED',
exitCode: EXIT_CODE.NOT_FOUND,
message: `No app with universal identifier ${universalIdentifier} is installed on ${apiUrl}.`,
+ hint,
details: { universalIdentifier },
});
diff --git a/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts b/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts
index 7f22897b851..239096c90f5 100644
--- a/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts
+++ b/packages/twenty-cli/src/app/deployment/create-post-sync-failure.ts
@@ -19,7 +19,7 @@ const POST_SYNC_STEPS: Record<
clientGeneration: {
cancelledMessage: 'generating its typed API client was cancelled',
failedMessage: 'its typed API client was not regenerated',
- hint: 'The workspace already has this version of the app, but the client files in node_modules/twenty-client-sdk may be incomplete. Fix the problem, then run twenty app apply again: it requests a fresh plan, uploads and syncs before regenerating the client. twenty app plan shows what that sync would change.',
+ hint: 'The workspace already has this version of the app, but the client files in node_modules/twenty-client-sdk may be incomplete. Fix the problem, then run twenty app generate-client to regenerate the client without syncing again.',
},
};
diff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.ts
index b696d344bca..57fe5965658 100644
--- a/packages/twenty-cli/src/catalog/command-catalog.ts
+++ b/packages/twenty-cli/src/catalog/command-catalog.ts
@@ -1,6 +1,7 @@
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';
import { APP_EXEC_COMMAND_DEFINITION } from '@/commands/app/exec/app-exec.command-definition';
+import { APP_GENERATE_CLIENT_COMMAND_DEFINITION } from '@/commands/app/generate-client/app-generate-client.command-definition';
import { APP_LOGS_COMMAND_DEFINITION } from '@/commands/app/function-logs/app-logs.command-definition';
import { type CommandDefinition } from '@/catalog/types/command-definition.type';
import { APP_APPLY_COMMAND_DEFINITION } from '@/commands/app/apply/app-apply.command-definition';
@@ -38,6 +39,7 @@ export const COMMAND_CATALOG: CommandDefinition[] = [
APP_EXEC_COMMAND_DEFINITION,
APP_LOGS_COMMAND_DEFINITION,
APP_BUILD_COMMAND_DEFINITION,
+ APP_GENERATE_CLIENT_COMMAND_DEFINITION,
APP_INIT_COMMAND_DEFINITION,
APP_PLAN_COMMAND_DEFINITION,
APP_PULL_COMMAND_DEFINITION,
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-generate-client.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-generate-client.spec.ts
new file mode 100644
index 00000000000..f865ff82675
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-generate-client.spec.ts
@@ -0,0 +1,204 @@
+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 { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { readGraphqlRequest } from '@/__tests__/utils/read-graphql-request';
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { sendJson, startTestServer } from '@/__tests__/utils/start-test-server';
+import { readAppIdentity } from '@/app/read-app-identity';
+
+const worker = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
+
+vi.mock('@/app/get-app-worker-launch', () => ({
+ getAppWorkerLaunch: () => worker,
+}));
+vi.mock('@/app/read-app-identity');
+
+const UNIVERSAL_IDENTIFIER = '6a0c9d8e-8f5f-4c43-9b8e-0e1f2a3b4c5d';
+const SCHEMA =
+ 'type Query { companies: [Company!]! } type Company { id: ID! name: String! }';
+
+let workerDirectory: string;
+let appPath: string;
+let schemaResponse: unknown;
+
+const server = await startTestServer((_request, response) =>
+ sendJson(response, 200, schemaResponse),
+);
+
+const run = (...options: string[]) =>
+ runCliForTest(['app', 'generate-client', '--path', appPath, ...options]);
+
+const expectIdentityReadOnce = () => {
+ expect(readAppIdentity).toHaveBeenCalledTimes(1);
+ expect(readAppIdentity).toHaveBeenCalledWith({
+ appPath,
+ signal: expect.any(AbortSignal),
+ });
+};
+
+beforeAll(async () => {
+ workerDirectory = await mkdtemp(
+ join(tmpdir(), 'twenty-generate-client-worker-'),
+ );
+ await buildTestAppWorker(workerDirectory, { useToolingFixture: true });
+ worker.modulePath = join(workerDirectory, 'app-worker.cjs');
+}, 60_000);
+
+afterAll(async () => {
+ await server.close();
+ await rm(workerDirectory, { recursive: true, force: true });
+});
+
+beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-generate-client-'));
+ await writeFile(
+ join(appPath, 'package.json'),
+ JSON.stringify({
+ name: 'generate-app',
+ devDependencies: { 'twenty-sdk': '9.9.9' },
+ }),
+ );
+ await writeTestSourceSdk({ appPath });
+ await mkdir(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ });
+ await writeFile(
+ join(appPath, 'test-tooling.cjs'),
+ `
+ const fs = require('node:fs');
+ const path = require('node:path');
+ exports.generateApplicationClient = async ({ appPath, schema }) => {
+ fs.writeFileSync(path.join(appPath, 'generated.json'), JSON.stringify({ appPath, schema }));
+ return { success: true, data: null, diagnostics: [] };
+ };
+ `,
+ );
+ schemaResponse = { data: { applicationCoreGraphqlSchema: SCHEMA } };
+ vi.mocked(readAppIdentity)
+ .mockReset()
+ .mockResolvedValue({
+ application: {
+ universalIdentifier: UNIVERSAL_IDENTIFIER.toUpperCase(),
+ displayName: 'Generate App',
+ },
+ diagnostics: [],
+ });
+ vi.stubEnv('TWENTY_API_URL', server.url);
+ vi.stubEnv('TWENTY_API_KEY', 'generate-test-key');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('CI', '');
+ server.requests.length = 0;
+});
+
+afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(appPath, { recursive: true, force: true });
+});
+
+describe('app generate-client', () => {
+ it('regenerates the client from the workspace schema without building or syncing', async () => {
+ const { stdout, exitCode } = await run('--json');
+
+ expect(exitCode).toBe(0);
+ expect(parseSingleJsonLine(stdout).data).toMatchObject({
+ app: { path: appPath, name: 'generate-app' },
+ sdk: { version: '9.9.9' },
+ application: { displayName: 'Generate App' },
+ });
+ expect(server.requests).toHaveLength(1);
+ expect(server.requests[0]).toMatchObject({
+ path: '/metadata',
+ headers: { authorization: 'Bearer generate-test-key' },
+ });
+ expect(readGraphqlRequest(server.requests[0]).arguments).toEqual({
+ applicationUniversalIdentifier: UNIVERSAL_IDENTIFIER,
+ });
+ expect(
+ JSON.parse(await readFile(join(appPath, 'generated.json'), 'utf8')),
+ ).toEqual({ appPath, schema: SCHEMA });
+ expectIdentityReadOnce();
+ });
+
+ it('confirms the generated client in human output', async () => {
+ const { stdout, exitCode } = await run();
+
+ expect(exitCode).toBe(0);
+ expect(stdout).toContain(
+ `Generated the typed API client for Generate App from ${server.url}`,
+ );
+ expectIdentityReadOnce();
+ });
+
+ it('refuses an app without its own twenty-client-sdk before contacting the workspace', async () => {
+ await rm(join(appPath, 'node_modules', 'twenty-client-sdk'), {
+ recursive: true,
+ force: true,
+ });
+
+ const { stdout, exitCode } = await run('--json');
+
+ expect(exitCode).toBe(1);
+ expect(parseSingleJsonLine(stdout).error).toMatchObject({
+ code: 'CLIENT_SDK_NOT_INSTALLED',
+ hint: expect.stringContaining('yarn add twenty-client-sdk'),
+ });
+ expect(server.requests).toEqual([]);
+ expect(readAppIdentity).not.toHaveBeenCalled();
+ });
+
+ it('asks to apply an app that is not installed in the workspace', async () => {
+ schemaResponse = {
+ data: null,
+ errors: [
+ {
+ message: 'Application not found',
+ extensions: { code: 'NOT_FOUND', subCode: 'APPLICATION_NOT_FOUND' },
+ },
+ ],
+ };
+
+ const { stdout, exitCode } = await run('--json');
+
+ expect(exitCode).toBe(4);
+ expect(parseSingleJsonLine(stdout).error).toMatchObject({
+ code: 'APP_NOT_INSTALLED',
+ hint: expect.stringContaining('twenty app apply'),
+ });
+ expect(existsSync(join(appPath, 'generated.json'))).toBe(false);
+ expectIdentityReadOnce();
+ });
+
+ it('rejects a project without an application definition', async () => {
+ vi.mocked(readAppIdentity).mockResolvedValue({
+ application: null,
+ diagnostics: [],
+ });
+
+ const { stdout, exitCode } = await run('--json');
+
+ expect(exitCode).toBe(2);
+ expect(parseSingleJsonLine(stdout).error).toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ expect(server.requests).toEqual([]);
+ expectIdentityReadOnce();
+ });
+});
diff --git a/packages/twenty-cli/src/commands/app/generate-client/app-generate-client.command-definition.ts b/packages/twenty-cli/src/commands/app/generate-client/app-generate-client.command-definition.ts
new file mode 100644
index 00000000000..819f98fcfe7
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/generate-client/app-generate-client.command-definition.ts
@@ -0,0 +1,26 @@
+import { type TargetCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const APP_GENERATE_CLIENT_COMMAND_DEFINITION: TargetCommandDefinition = {
+ path: ['app', 'generate-client'],
+ description:
+ "Regenerate the app's typed API client from the workspace schema, without building or syncing",
+ options: [
+ {
+ flags: '--path <directory>',
+ description:
+ 'App directory (default: the app containing the current folder)',
+ },
+ ],
+ examples: [
+ 'twenty app generate-client --remote dev',
+ 'twenty app generate-client --path ./apps/billing --json',
+ ],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: true,
+ needsTarget: true,
+ load: async () =>
+ (
+ await import('@/commands/app/generate-client/run-app-generate-client-command')
+ ).runAppGenerateClientCommand,
+};
diff --git a/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts b/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts
new file mode 100644
index 00000000000..cead682817d
--- /dev/null
+++ b/packages/twenty-cli/src/commands/app/generate-client/run-app-generate-client-command.ts
@@ -0,0 +1,94 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { createAppNotInstalledError } from '@/app/create-app-not-installed-error';
+import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
+import { generateAppClient } from '@/app/generate-app-client';
+import { getClientGenerationSkipReason } from '@/app/get-client-generation-skip-reason';
+import { isApplicationNotFoundError } from '@/app/is-application-not-found-error';
+import { resolveAppProject } from '@/app/project/resolve-app-project';
+import { resolveSourceSdk } from '@/app/project/resolve-source-sdk';
+import { readAppIdentity } from '@/app/read-app-identity';
+import { readStringOption } 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 { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+import { formatSuccessLine } from '@/output/style';
+
+export const runAppGenerateClientCommand: CommandRun<
+ TargetCommandContext
+> = async (context) => {
+ const { options, output, outputMode, signal, target } = context;
+ const startedAt = performance.now();
+ const project = await resolveAppProject({
+ explicitPath: readStringOption(options, 'path'),
+ workingDirectory: process.cwd(),
+ });
+ const skipReason = await getClientGenerationSkipReason({
+ appPath: project.path,
+ });
+
+ if (isDefined(skipReason)) {
+ throw new CliError({
+ code: 'CLIENT_SDK_NOT_INSTALLED',
+ message: `The typed API client cannot be generated: ${skipReason}`,
+ hint: 'Install twenty-client-sdk in the app, for example with yarn add twenty-client-sdk, then try again.',
+ details: { appPath: project.path },
+ });
+ }
+
+ const identity = await readAppIdentity({ appPath: project.path, signal });
+
+ if (!isDefined(identity.application)) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'This project has no application definition.',
+ });
+ }
+
+ const universalIdentifier =
+ identity.application.universalIdentifier.toLowerCase();
+
+ if (outputMode === 'human') {
+ for (const diagnostic of identity.diagnostics) {
+ output.progress(formatToolingDiagnostic(diagnostic));
+ }
+ }
+
+ const sdk = await resolveSourceSdk({ appPath: project.path });
+ const generationDiagnostics = await generateAppClient({
+ appPath: project.path,
+ applicationUniversalIdentifier: universalIdentifier,
+ sdk,
+ context,
+ }).catch((error: unknown) => {
+ if (
+ isApplicationNotFoundError({
+ error,
+ field: 'applicationCoreGraphqlSchema',
+ })
+ ) {
+ throw createAppNotInstalledError({
+ universalIdentifier,
+ apiUrl: target.apiUrl,
+ hint: 'Install it with twenty app apply, which also generates the client.',
+ });
+ }
+
+ throw error;
+ });
+
+ return {
+ data: {
+ app: { path: project.path, name: project.name },
+ sdk: { version: sdk.version },
+ application: identity.application,
+ diagnostics: [...identity.diagnostics, ...generationDiagnostics],
+ durationMilliseconds: Math.round(performance.now() - startedAt),
+ },
+ human: formatSuccessLine(
+ `Generated the typed API client for ${identity.application.displayName ?? project.name} from ${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.ts
index c0f62fc8194..e2d0912e148 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
@@ -12,6 +12,7 @@ export type CliErrorCode =
| 'BUILD_FAILED'
| 'CANCELLED'
| 'CLIENT_GENERATION_FAILED'
+ | 'CLIENT_SDK_NOT_INSTALLED'
| 'CONFIG_LOCKED'
| 'CONFIRMATION_DECLINED'
| 'CONFIRMATION_REQUIRED'