Skip to content

The open alternative to Salesforce, designed for AI.

feat(cli): pull existing apps or initialize the workspace custom app (#29207)

Weikof28b5f18d14f
diff --git a/packages/twenty-cli/CONTRIBUTING.md b/packages/twenty-cli/CONTRIBUTING.md
index 8eee1a49d64..c6fa2d4b90c 100644
--- a/packages/twenty-cli/CONTRIBUTING.md
+++ b/packages/twenty-cli/CONTRIBUTING.md
@@ -166,7 +166,11 @@ node packages/twenty-cli/scripts/prepublish.mjs
## App integration tests
-`app-template/src/__tests__` supplies the integration-test setup for CLI-created apps.
+`app-template/` contains the shared project scaffold. `app init` layers
+`app-template/example/files/` and `example/scripts.json` onto it; `app pull`
+uses only the shared scaffold before writing the exported definitions.
+
+`app-template/example/files/src/__tests__` supplies the integration-test setup for CLI-created apps.
It deploys the app before tests and uninstalls it afterward by invoking the
installed CLI with `--json`. Apps invoke the executable rather than import the
CLI as a library or add it as a dependency. See the
diff --git a/packages/twenty-cli/app-template/AGENTS.md b/packages/twenty-cli/app-template/example/files/AGENTS.md
similarity index 100%
rename from packages/twenty-cli/app-template/AGENTS.md
rename to packages/twenty-cli/app-template/example/files/AGENTS.md
diff --git a/packages/twenty-cli/app-template/CHANGELOG.md b/packages/twenty-cli/app-template/example/files/CHANGELOG.md
similarity index 100%
rename from packages/twenty-cli/app-template/CHANGELOG.md
rename to packages/twenty-cli/app-template/example/files/CHANGELOG.md
diff --git a/packages/twenty-cli/app-template/README.md b/packages/twenty-cli/app-template/example/files/README.md
similarity index 100%
rename from packages/twenty-cli/app-template/README.md
rename to packages/twenty-cli/app-template/example/files/README.md
diff --git a/packages/twenty-cli/app-template/SETUP.md b/packages/twenty-cli/app-template/example/files/SETUP.md
similarity index 100%
rename from packages/twenty-cli/app-template/SETUP.md
rename to packages/twenty-cli/app-template/example/files/SETUP.md
diff --git a/packages/twenty-cli/app-template/github/workflows/cd.yml b/packages/twenty-cli/app-template/example/files/github/workflows/cd.yml
similarity index 100%
rename from packages/twenty-cli/app-template/github/workflows/cd.yml
rename to packages/twenty-cli/app-template/example/files/github/workflows/cd.yml
diff --git a/packages/twenty-cli/app-template/github/workflows/ci.yml b/packages/twenty-cli/app-template/example/files/github/workflows/ci.yml
similarity index 100%
rename from packages/twenty-cli/app-template/github/workflows/ci.yml
rename to packages/twenty-cli/app-template/example/files/github/workflows/ci.yml
diff --git a/packages/twenty-cli/app-template/github/workflows/publish.yml b/packages/twenty-cli/app-template/example/files/github/workflows/publish.yml
similarity index 100%
rename from packages/twenty-cli/app-template/github/workflows/publish.yml
rename to packages/twenty-cli/app-template/example/files/github/workflows/publish.yml
diff --git a/packages/twenty-cli/app-template/locales/en.json b/packages/twenty-cli/app-template/example/files/locales/en.json
similarity index 100%
rename from packages/twenty-cli/app-template/locales/en.json
rename to packages/twenty-cli/app-template/example/files/locales/en.json
diff --git a/packages/twenty-cli/app-template/public/logo.svg b/packages/twenty-cli/app-template/example/files/public/logo.svg
similarity index 100%
rename from packages/twenty-cli/app-template/public/logo.svg
rename to packages/twenty-cli/app-template/example/files/public/logo.svg
diff --git a/packages/twenty-cli/app-template/src/__tests__/application-config.test.ts b/packages/twenty-cli/app-template/example/files/src/__tests__/application-config.test.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/__tests__/application-config.test.ts
rename to packages/twenty-cli/app-template/example/files/src/__tests__/application-config.test.ts
diff --git a/packages/twenty-cli/app-template/src/__tests__/global-setup.ts b/packages/twenty-cli/app-template/example/files/src/__tests__/global-setup.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/__tests__/global-setup.ts
rename to packages/twenty-cli/app-template/example/files/src/__tests__/global-setup.ts
diff --git a/packages/twenty-cli/app-template/src/__tests__/run-twenty.ts b/packages/twenty-cli/app-template/example/files/src/__tests__/run-twenty.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/__tests__/run-twenty.ts
rename to packages/twenty-cli/app-template/example/files/src/__tests__/run-twenty.ts
diff --git a/packages/twenty-cli/app-template/src/__tests__/schema.integration-test.ts b/packages/twenty-cli/app-template/example/files/src/__tests__/schema.integration-test.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/__tests__/schema.integration-test.ts
rename to packages/twenty-cli/app-template/example/files/src/__tests__/schema.integration-test.ts
diff --git a/packages/twenty-cli/app-template/src/application-config.ts b/packages/twenty-cli/app-template/example/files/src/application-config.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/application-config.ts
rename to packages/twenty-cli/app-template/example/files/src/application-config.ts
diff --git a/packages/twenty-cli/app-template/src/constants/universal-identifiers.ts b/packages/twenty-cli/app-template/example/files/src/constants/universal-identifiers.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/constants/universal-identifiers.ts
rename to packages/twenty-cli/app-template/example/files/src/constants/universal-identifiers.ts
diff --git a/packages/twenty-cli/app-template/src/default-role.ts b/packages/twenty-cli/app-template/example/files/src/default-role.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/default-role.ts
rename to packages/twenty-cli/app-template/example/files/src/default-role.ts
diff --git a/packages/twenty-cli/app-template/src/front-components/main-page.tsx b/packages/twenty-cli/app-template/example/files/src/front-components/main-page.tsx
similarity index 100%
rename from packages/twenty-cli/app-template/src/front-components/main-page.tsx
rename to packages/twenty-cli/app-template/example/files/src/front-components/main-page.tsx
diff --git a/packages/twenty-cli/app-template/src/logic-functions/health-check.ts b/packages/twenty-cli/app-template/example/files/src/logic-functions/health-check.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/logic-functions/health-check.ts
rename to packages/twenty-cli/app-template/example/files/src/logic-functions/health-check.ts
diff --git a/packages/twenty-cli/app-template/src/navigation-menu-items/main-page.navigation-menu-item.ts b/packages/twenty-cli/app-template/example/files/src/navigation-menu-items/main-page.navigation-menu-item.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/navigation-menu-items/main-page.navigation-menu-item.ts
rename to packages/twenty-cli/app-template/example/files/src/navigation-menu-items/main-page.navigation-menu-item.ts
diff --git a/packages/twenty-cli/app-template/src/page-layouts/main-page.page-layout.ts b/packages/twenty-cli/app-template/example/files/src/page-layouts/main-page.page-layout.ts
similarity index 100%
rename from packages/twenty-cli/app-template/src/page-layouts/main-page.page-layout.ts
rename to packages/twenty-cli/app-template/example/files/src/page-layouts/main-page.page-layout.ts
diff --git a/packages/twenty-cli/app-template/tsconfig.spec.json b/packages/twenty-cli/app-template/example/files/tsconfig.spec.json
similarity index 100%
rename from packages/twenty-cli/app-template/tsconfig.spec.json
rename to packages/twenty-cli/app-template/example/files/tsconfig.spec.json
diff --git a/packages/twenty-cli/app-template/vitest.config.ts b/packages/twenty-cli/app-template/example/files/vitest.config.ts
similarity index 100%
rename from packages/twenty-cli/app-template/vitest.config.ts
rename to packages/twenty-cli/app-template/example/files/vitest.config.ts
diff --git a/packages/twenty-cli/app-template/vitest.unit.config.ts b/packages/twenty-cli/app-template/example/files/vitest.unit.config.ts
similarity index 100%
rename from packages/twenty-cli/app-template/vitest.unit.config.ts
rename to packages/twenty-cli/app-template/example/files/vitest.unit.config.ts
diff --git a/packages/twenty-cli/app-template/example/scripts.json b/packages/twenty-cli/app-template/example/scripts.json
new file mode 100644
index 00000000000..3ec46627c7b
--- /dev/null
+++ b/packages/twenty-cli/app-template/example/scripts.json
@@ -0,0 +1,6 @@
+{
+ "typecheck": "tsgo --noEmit -p tsconfig.spec.json",
+ "test": "vitest run",
+ "test:watch": "vitest",
+ "test:unit": "vitest run --config vitest.unit.config.ts"
+}
diff --git a/packages/twenty-cli/app-template/package.json b/packages/twenty-cli/app-template/package.json
index 1b27aef049a..692b2137075 100644
--- a/packages/twenty-cli/app-template/package.json
+++ b/packages/twenty-cli/app-template/package.json
@@ -13,10 +13,7 @@
"twenty": "twenty",
"lint": "oxlint -c .oxlintrc.json .",
"lint:fix": "oxlint --fix -c .oxlintrc.json .",
- "typecheck": "tsgo --noEmit -p tsconfig.spec.json",
- "test": "vitest run",
- "test:watch": "vitest",
- "test:unit": "vitest run --config vitest.unit.config.ts"
+ "typecheck": "tsgo --noEmit -p tsconfig.json"
},
"dependencies": {},
"devDependencies": {
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.md
index a2aae52ce98..f2523edc634 100644
--- a/packages/twenty-cli/docs/commands.md
+++ b/packages/twenty-cli/docs/commands.md
@@ -416,10 +416,14 @@ The app must already be installed in the workspace; otherwise the command fails
```bash
twenty app pull --remote dev
twenty app pull --path ./apps/billing --json
-twenty app pull --universal-identifier <uuid> --verbose
+twenty app pull --path ./workspace-app --yes --no-input
```
-`app pull` reads the app's definition and exports its workspace metadata into the existing project. It uses the selected connection and the server's `APPLICATIONS` permission; the server decides which apps this workspace can export. It does not register an app or change the workspace. When a project has no application definition, provide `--universal-identifier`. A project declaring a different app is refused before writing.
+Inside an app, `app pull` reads the identifier from the local application definition and pulls that application. Outside an app, it asks where to create a project for the selected workspace's custom application, then asks to create it, install its dependencies with Yarn, and pull. `--path` chooses an existing app or a new or empty destination; noninteractive creation requires both `--path` and `--yes`. It never overwrites an unrelated nonempty directory.
+
+New projects reuse the bundled initializer's package and configuration files without demo entities. Pull writes the custom application's definition. An existing SDK project without an application definition also pulls the custom application. A missing custom application is an error. There is no `--universal-identifier` option.
+
+Pull uses the selected connection and the server's `APPLICATIONS` permission. Creating a project here creates local files only; it does not register an application or change the workspace. Existing projects do not install dependencies automatically. If a new project's installation fails, the scaffold is kept so you can run `yarn install` there and retry pull.
The project must have `twenty-sdk` installed, version `>=1.23.0`, with its public `twenty-sdk/define` and `twenty-sdk/front-component` exports. Pull also checks that the SDK provides the authoring APIs required by the generated files. Missing APIs fail with `SDK_SOURCE_UNSUPPORTED`; install a compatible version (2.50.0 or later). Pull does not require a project TypeScript compiler. Run `twenty app typecheck` afterwards to check the generated definitions against your installed SDK.
diff --git a/packages/twenty-cli/src/app/__tests__/app-template-global-setup.spec.ts b/packages/twenty-cli/src/app/__tests__/app-template-global-setup.spec.ts
index 0abda3c38ce..9732b5404e3 100644
--- a/packages/twenty-cli/src/app/__tests__/app-template-global-setup.spec.ts
+++ b/packages/twenty-cli/src/app/__tests__/app-template-global-setup.spec.ts
@@ -3,10 +3,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
setup,
teardown,
-} from '../../../app-template/src/__tests__/global-setup';
-import { runTwenty } from '../../../app-template/src/__tests__/run-twenty';
+} from '../../../app-template/example/files/src/__tests__/global-setup';
+import { runTwenty } from '../../../app-template/example/files/src/__tests__/run-twenty';
-vi.mock('../../../app-template/src/__tests__/run-twenty', () => ({
+vi.mock('../../../app-template/example/files/src/__tests__/run-twenty', () => ({
runTwenty: vi.fn(),
}));
diff --git a/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts
index a7ae1f0d212..f32e79fe8e6 100644
--- a/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts
+++ b/packages/twenty-cli/src/app/__tests__/app-template-run-twenty.spec.ts
@@ -4,7 +4,7 @@ import { delimiter, dirname, join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { runTwenty } from '../../../app-template/src/__tests__/run-twenty';
+import { runTwenty } from '../../../app-template/example/files/src/__tests__/run-twenty';
describe('runTwenty in the app template', () => {
let root: string;
diff --git a/packages/twenty-cli/src/app/__tests__/install-app-dependencies-or-throw.spec.ts b/packages/twenty-cli/src/app/__tests__/install-app-dependencies-or-throw.spec.ts
new file mode 100644
index 00000000000..4d22f451c32
--- /dev/null
+++ b/packages/twenty-cli/src/app/__tests__/install-app-dependencies-or-throw.spec.ts
@@ -0,0 +1,102 @@
+import { access, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { installAppDependenciesOrThrow } from '@/app/install-app-dependencies-or-throw';
+
+const output = {
+ event: vi.fn(),
+ warn: vi.fn(),
+ progress: vi.fn(),
+ succeed: vi.fn(),
+ fail: vi.fn(),
+};
+
+describe('installing a new pull project', () => {
+ let appPath: string;
+ const writeYarn = (source: string) =>
+ writeFile(join(appPath, 'yarn'), `#!${process.execPath}\n${source}`, {
+ mode: 0o755,
+ });
+
+ beforeEach(async () => {
+ appPath = await mkdtemp(join(tmpdir(), 'twenty-pull-install-'));
+ vi.stubEnv('PATH', appPath);
+ vi.stubEnv('TWENTY_API_KEY', 'workspace-secret');
+ vi.stubEnv('TWENTY_APP_ACCESS_TOKEN', 'app-secret');
+ vi.stubEnv('TWENTY_API_URL', 'https://workspace.invalid');
+ });
+
+ afterEach(async () => {
+ vi.unstubAllEnvs();
+ await rm(appPath, { recursive: true, force: true });
+ });
+
+ it('installs in the new project without exposing workspace credentials or subprocess output', async () => {
+ await writeYarn(`
+ require('node:fs').writeFileSync('installation.json', JSON.stringify({
+ args: process.argv.slice(2),
+ hasCredentials: Boolean(process.env.TWENTY_API_KEY || process.env.TWENTY_APP_ACCESS_TOKEN || process.env.TWENTY_API_URL),
+ immutable: process.env.YARN_ENABLE_IMMUTABLE_INSTALLS,
+ }));
+ console.log('package manager output');
+ `);
+
+ await installAppDependenciesOrThrow({
+ appPath,
+ output,
+ signal: new AbortController().signal,
+ });
+
+ expect(
+ JSON.parse(await readFile(join(appPath, 'installation.json'), 'utf8')),
+ ).toEqual({
+ args: ['install'],
+ hasCredentials: false,
+ immutable: 'false',
+ });
+ });
+
+ it('reports install failure with the retained project and package manager diagnostics', async () => {
+ await writeYarn(
+ `console.error('Registry unavailable'); process.exitCode = 9;`,
+ );
+
+ await expect(
+ installAppDependenciesOrThrow({
+ appPath,
+ output,
+ signal: new AbortController().signal,
+ }),
+ ).rejects.toMatchObject({
+ code: 'APP_INIT_FAILED',
+ hint: expect.stringContaining('Registry unavailable'),
+ details: {
+ path: appPath,
+ exitCode: 9,
+ stderr: expect.stringContaining('Registry unavailable'),
+ },
+ });
+ });
+
+ it('stops the installer when pull is cancelled', async () => {
+ await writeYarn(
+ `require('node:fs').writeFileSync('started', 'yes'); setInterval(() => {}, 1000);`,
+ );
+ const cancellation = new AbortController();
+ const installation = installAppDependenciesOrThrow({
+ appPath,
+ output,
+ signal: cancellation.signal,
+ });
+ const rejected = expect(installation).rejects.toMatchObject({
+ code: 'CANCELLED',
+ });
+
+ await vi.waitFor(() => access(join(appPath, 'started')));
+ cancellation.abort();
+ await rejected;
+ });
+});
diff --git a/packages/twenty-cli/src/app/create-app-project.ts b/packages/twenty-cli/src/app/create-app-project.ts
index fa7be77f1bd..ac6e40aee53 100644
--- a/packages/twenty-cli/src/app/create-app-project.ts
+++ b/packages/twenty-cli/src/app/create-app-project.ts
@@ -139,12 +139,14 @@ export const createAppProject = async ({
appName,
appDisplayName,
appDescription,
+ shouldIncludeExample = true,
signal,
}: {
appDirectory: string;
appName: string;
appDisplayName: string;
appDescription: string;
+ shouldIncludeExample?: boolean;
signal: AbortSignal;
}) => {
await readAvailableAppDirectory(appDirectory);
@@ -162,6 +164,7 @@ export const createAppProject = async ({
appName,
appDisplayName,
appDescription,
+ shouldIncludeExample,
appDirectory: stagingDirectory,
});
signal.throwIfAborted();
diff --git a/packages/twenty-cli/src/app/fetch-workspace-id.ts b/packages/twenty-cli/src/app/fetch-workspace-id.ts
deleted file mode 100644
index 35977933a1b..00000000000
--- a/packages/twenty-cli/src/app/fetch-workspace-id.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { isNonEmptyString } from '@sniptt/guards';
-import { isPlainObject, isValidUuid } from 'twenty-shared/utils';
-
-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 fetchWorkspaceId = async ({
- target,
- signal,
-}: {
- target: ResolvedTarget;
- signal: AbortSignal;
-}) => {
- const client = createMetadataClient({ target, signal });
- const data = await client.query({
- currentWorkspace: { id: true },
- });
- const workspace = data?.currentWorkspace;
-
- if (
- !isPlainObject(workspace) ||
- !isNonEmptyString(workspace.id) ||
- !isValidUuid(workspace.id)
- ) {
- throw new CliError({
- code: 'INVALID_RESPONSE',
- message: `${target.apiUrl} did not say which workspace these credentials belong to.`,
- });
- }
-
- return workspace.id;
-};
diff --git a/packages/twenty-cli/src/app/fetch-workspace-or-throw.ts b/packages/twenty-cli/src/app/fetch-workspace-or-throw.ts
new file mode 100644
index 00000000000..0f95596958d
--- /dev/null
+++ b/packages/twenty-cli/src/app/fetch-workspace-or-throw.ts
@@ -0,0 +1,58 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isValidUniversalIdentifier } from 'twenty-shared/application';
+import { isDefined, isPlainObject, isValidUuid } from 'twenty-shared/utils';
+
+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 fetchWorkspaceOrThrow = async ({
+ target,
+ signal,
+ shouldIncludeCustomApplication = false,
+}: {
+ target: ResolvedTarget;
+ signal: AbortSignal;
+ shouldIncludeCustomApplication?: boolean;
+}) => {
+ const client = createMetadataClient({ target, signal });
+ const data = await client.query({
+ currentWorkspace: {
+ id: true,
+ ...(shouldIncludeCustomApplication
+ ? { workspaceCustomApplication: { universalIdentifier: true } }
+ : {}),
+ },
+ });
+ const workspace = data?.currentWorkspace;
+
+ if (
+ !isPlainObject(workspace) ||
+ !isNonEmptyString(workspace.id) ||
+ !isValidUuid(workspace.id)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `${target.apiUrl} did not say which workspace these credentials belong to.`,
+ });
+ }
+
+ if (
+ shouldIncludeCustomApplication &&
+ isDefined(workspace.workspaceCustomApplication) &&
+ (!isPlainObject(workspace.workspaceCustomApplication) ||
+ !isNonEmptyString(
+ workspace.workspaceCustomApplication.universalIdentifier,
+ ) ||
+ !isValidUniversalIdentifier(
+ workspace.workspaceCustomApplication.universalIdentifier,
+ ))
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: `${target.apiUrl} returned an invalid workspace custom application identifier.`,
+ });
+ }
+
+ return workspace;
+};
diff --git a/packages/twenty-cli/src/app/install-app-dependencies-or-throw.ts b/packages/twenty-cli/src/app/install-app-dependencies-or-throw.ts
new file mode 100644
index 00000000000..59069364a33
--- /dev/null
+++ b/packages/twenty-cli/src/app/install-app-dependencies-or-throw.ts
@@ -0,0 +1,77 @@
+import execa from 'execa';
+
+import { createAppWorkerEnvironment } from '@/app/create-app-worker-environment';
+import { formatDataValue } from '@/data/format-data-value';
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+import { type Output } from '@/output/types/output.type';
+
+export const installAppDependenciesOrThrow = async ({
+ appPath,
+ signal,
+ output,
+}: {
+ appPath: string;
+ signal: AbortSignal;
+ output: Output;
+}) => {
+ signal.throwIfAborted();
+ output.progress({
+ message: 'Installing app dependencies with yarn install…',
+ });
+
+ const subprocess = execa('yarn', ['install'], {
+ cwd: appPath,
+ env: {
+ ...createAppWorkerEnvironment(process.env),
+ YARN_ENABLE_IMMUTABLE_INSTALLS: 'false',
+ COREPACK_ENABLE_DOWNLOAD_PROMPT: '0',
+ },
+ extendEnv: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ reject: false,
+ maxBuffer: 4 * 1024 * 1024,
+ });
+ const cancel = () =>
+ subprocess.kill('SIGTERM', { forceKillAfterTimeout: 1000 });
+
+ signal.addEventListener('abort', cancel, { once: true });
+ if (signal.aborted) {
+ cancel();
+ }
+
+ try {
+ const result = await subprocess;
+
+ if (signal.aborted) {
+ throw createCancelledError();
+ }
+
+ if (result.failed) {
+ const diagnostic = (result.stderr?.trim() || result.stdout?.trim() || '')
+ .slice(-4000)
+ .split('\n')
+ .map(formatDataValue)
+ .join('\n');
+
+ throw new CliError({
+ code: 'APP_INIT_FAILED',
+ message: 'Could not install dependencies for the new app.',
+ hint: [
+ diagnostic,
+ `The project was created at ${formatDataValue(appPath)}. Fix the installation error, run yarn install there, then run twenty app pull again.`,
+ ]
+ .filter(Boolean)
+ .join('\n'),
+ details: {
+ path: appPath,
+ exitCode: result.exitCode,
+ stdout: result.stdout?.slice(-16384) ?? '',
+ stderr: result.stderr?.slice(-16384) ?? '',
+ },
+ });
+ }
+ } finally {
+ signal.removeEventListener('abort', cancel);
+ }
+};
diff --git a/packages/twenty-cli/src/app/pull/README.md b/packages/twenty-cli/src/app/pull/README.md
index f078195d1fc..cd6b029984e 100644
--- a/packages/twenty-cli/src/app/pull/README.md
+++ b/packages/twenty-cli/src/app/pull/README.md
@@ -10,6 +10,9 @@ See the [app tooling overview](../README.md) for package boundaries.
## Contract
+- An existing application's local identifier selects the target. With no local definition, the command fetches `currentWorkspace.workspaceCustomApplication.universalIdentifier`. Apply baseline recording still queries only the workspace ID.
+- Outside an app, pull offers to create a local project and install its dependencies before reconciliation. Noninteractive creation requires `--path` and `--yes`. The initializer omits demo entities, and unrelated nonempty directories are refused.
+- Missing custom applications fail before project creation. The worker still checks that the local identity matches the export before writing.
- Source scanning stays inside the disposable CLI worker so configs containing functions are never serialized through IPC. Only the server export and report cross that boundary. Selected credentials are removed from the worker environment. App source is trusted developer code, not sandboxed code.
- The wire/export and baseline boundary check identity and envelope fields, not every metadata collection. `toPullManifest` is the single explicit assertion into the typed writers, preserving their trust in the server schema. Missing/null object and field collections are consumed with `?? []`, like the other collections. Malformed entity contents can still make reconciliation fail before writing. We do not duplicate the server's schema.
- The baseline file is an envelope whose `manifest` member is an `ExportedManifest`. Reconciliation walks arrays generically without maintaining a second collection list. Unrecognized collections and non-array metadata survive; protected or unreconciled definitions retain their prior baseline entries.
diff --git a/packages/twenty-cli/src/app/pull/create-pull-project.ts b/packages/twenty-cli/src/app/pull/create-pull-project.ts
new file mode 100644
index 00000000000..54f9b278748
--- /dev/null
+++ b/packages/twenty-cli/src/app/pull/create-pull-project.ts
@@ -0,0 +1,94 @@
+import { basename, resolve } from 'node:path';
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { createAppProject } from '@/app/create-app-project';
+import { requireApproval } from '@/app/deployment/require-approval';
+import { installAppDependenciesOrThrow } from '@/app/install-app-dependencies-or-throw';
+import { isValidPackageName } from '@/app/is-valid-package-name';
+import { kebabCase } from '@/app/pull/kebab-case';
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { formatDataValue } from '@/data/format-data-value';
+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';
+
+export const createPullProject = async ({
+ context,
+ displayName,
+}: {
+ context: CommandContext;
+ displayName: string;
+}) => {
+ const { options, signal, output } = context;
+ const canPrompt = isInteractionAllowed(context);
+ const defaultDirectory = kebabCase(displayName) || 'workspace-app';
+ let path = readStringOption(options, 'path');
+
+ if (!isDefined(path) && canPrompt) {
+ path =
+ (
+ await promptInTerminal({
+ question: `No Twenty app found. Directory for the workspace custom app [./${formatDataValue(defaultDirectory)}]: `,
+ signal,
+ })
+ ).trim() || defaultDirectory;
+ }
+
+ if (!isDefined(path)) {
+ throw new CliError({
+ code: 'APP_PATH_REQUIRED',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'Choose a directory for the workspace custom application.',
+ hint: 'Pass --path <new-or-empty-directory> --yes to create the project, install its dependencies and pull.',
+ });
+ }
+
+ const appDirectory = resolve(process.cwd(), path);
+ const appName = kebabCase(basename(appDirectory));
+
+ if (!isValidPackageName(appName)) {
+ throw new CliError({
+ code: 'INVALID_APP_NAME',
+ exitCode: EXIT_CODE.USAGE,
+ message: 'The directory name cannot be used as an app package name.',
+ hint: 'Choose a directory such as workspace-app.',
+ });
+ }
+
+ await requireApproval({
+ isApproved: readBooleanOption(options, 'yes'),
+ canPrompt,
+ question: `Create ${formatDataValue(displayName)} in ${formatDataValue(appDirectory)}, install its dependencies and pull?`,
+ code: 'CONFIRMATION_REQUIRED',
+ message:
+ 'Pull needs to create a local project and install its dependencies.',
+ hint: 'Pass --yes to create the project and install its dependencies.',
+ declinedMessage: 'Pull stopped before creating the project.',
+ signal,
+ });
+
+ output.progress({
+ message: `Creating ${appName} in ${formatDataValue(appDirectory)}…`,
+ });
+ await createAppProject({
+ appDirectory,
+ appName,
+ appDisplayName: displayName,
+ appDescription: '',
+ shouldIncludeExample: false,
+ signal,
+ });
+ await installAppDependenciesOrThrow({
+ appPath: appDirectory,
+ signal,
+ output,
+ });
+
+ return { path: appDirectory, name: appName };
+};
diff --git a/packages/twenty-cli/src/app/record-pull-base.ts b/packages/twenty-cli/src/app/record-pull-base.ts
index 671c0e507e5..9c75d91d0e2 100644
--- a/packages/twenty-cli/src/app/record-pull-base.ts
+++ b/packages/twenty-cli/src/app/record-pull-base.ts
@@ -1,5 +1,5 @@
import { fetchAppExport } from '@/app/fetch-app-export';
-import { fetchWorkspaceId } from '@/app/fetch-workspace-id';
+import { fetchWorkspaceOrThrow } from '@/app/fetch-workspace-or-throw';
import { writePullBase } from '@/app/pull/write-pull-base';
import { type TargetCommandContext } from '@/catalog/types/target-command-context.type';
import { createCancelledError } from '@/output/create-cancelled-error';
@@ -21,7 +21,7 @@ export const recordPullBase = async ({
output.progress({ message: 'Recording the pull base…' });
try {
- const workspaceId = await fetchWorkspaceId({ target, signal });
+ const { id: workspaceId } = await fetchWorkspaceOrThrow({ target, signal });
const applicationExport = await fetchAppExport({
universalIdentifier,
target,
diff --git a/packages/twenty-cli/src/app/render-app-template.ts b/packages/twenty-cli/src/app/render-app-template.ts
index 422e91a7372..e10ecf5a6e6 100644
--- a/packages/twenty-cli/src/app/render-app-template.ts
+++ b/packages/twenty-cli/src/app/render-app-template.ts
@@ -15,60 +15,79 @@ export const renderAppTemplate = async ({
appName,
appDisplayName,
appDescription,
+ shouldIncludeExample = true,
}: {
appDirectory: string;
appName: string;
appDisplayName: string;
appDescription: string;
+ shouldIncludeExample?: boolean;
}) => {
- await cp(getAppTemplateDirectory(), appDirectory, { recursive: true });
+ const templateDirectory = getAppTemplateDirectory();
+ const exampleDirectory = join(templateDirectory, 'example');
+
+ await cp(templateDirectory, appDirectory, {
+ recursive: true,
+ filter: (source) => source !== exampleDirectory,
+ });
+
+ if (shouldIncludeExample) {
+ await cp(join(exampleDirectory, 'files'), appDirectory, {
+ recursive: true,
+ });
+ }
+
await writeFile(join(appDirectory, 'yarn.lock'), '', { flag: 'a' });
// npm excludes these dotfiles when packing the template.
for (const [source, destination] of [
['gitignore', '.gitignore'],
- ['github', '.github'],
['yarnrc.yml', '.yarnrc.yml'],
]) {
await rename(join(appDirectory, source), join(appDirectory, destination));
}
- await cp(join(appDirectory, 'AGENTS.md'), join(appDirectory, 'CLAUDE.md'));
+ if (shouldIncludeExample) {
+ await rename(join(appDirectory, 'github'), join(appDirectory, '.github'));
+
+ await cp(join(appDirectory, 'AGENTS.md'), join(appDirectory, 'CLAUDE.md'));
+
+ for (const workflowName of ['ci.yml', 'cd.yml', 'publish.yml']) {
+ const workflowPath = join(
+ appDirectory,
+ '.github',
+ 'workflows',
+ workflowName,
+ );
+ const workflow = (await readFile(workflowPath, 'utf8')).replaceAll(
+ 'CLI-VERSION-TO-BE-GENERATED',
+ CLI_VERSION,
+ );
+
+ await writeFile(workflowPath, workflow);
+ }
- for (const workflowName of ['ci.yml', 'cd.yml', 'publish.yml']) {
- const workflowPath = join(
+ const identifiersPath = join(
appDirectory,
- '.github',
- 'workflows',
- workflowName,
- );
- const workflow = (await readFile(workflowPath, 'utf8')).replaceAll(
- 'CLI-VERSION-TO-BE-GENERATED',
- CLI_VERSION,
+ 'src/constants/universal-identifiers.ts',
);
+ const identifiers = (await readFile(identifiersPath, 'utf8'))
+ .replace(/'DISPLAY-NAME-TO-BE-GENERATED'/g, () =>
+ printTypescriptValue({ value: appDisplayName }),
+ )
+ .replace(/'DESCRIPTION-TO-BE-GENERATED'/g, () =>
+ printTypescriptValue({ value: appDescription }),
+ )
+ .replace(/UUID-TO-BE-GENERATED/g, () => randomUUID());
- await writeFile(workflowPath, workflow);
+ await writeFile(identifiersPath, identifiers);
}
- const identifiersPath = join(
- appDirectory,
- 'src/constants/universal-identifiers.ts',
- );
- const identifiers = (await readFile(identifiersPath, 'utf8'))
- .replace(/'DISPLAY-NAME-TO-BE-GENERATED'/g, () =>
- printTypescriptValue({ value: appDisplayName }),
- )
- .replace(/'DESCRIPTION-TO-BE-GENERATED'/g, () =>
- printTypescriptValue({ value: appDescription }),
- )
- .replace(/UUID-TO-BE-GENERATED/g, () => randomUUID());
-
- await writeFile(identifiersPath, identifiers);
-
const packageJsonPath = join(appDirectory, 'package.json');
const packageJson: {
name: string;
engines: Record<string, string>;
+ scripts: Record<string, string>;
devDependencies: Record<string, string>;
} = JSON.parse(await readFile(packageJsonPath, 'utf8'));
@@ -80,5 +99,13 @@ export const renderAppTemplate = async ({
packageJson.devDependencies[packageName] = APP_TEMPLATE_PACKAGE_VERSION;
}
+ if (shouldIncludeExample) {
+ const exampleScripts: Record<string, string> = JSON.parse(
+ await readFile(join(exampleDirectory, 'scripts.json'), 'utf8'),
+ );
+
+ packageJson.scripts = { ...packageJson.scripts, ...exampleScripts };
+ }
+
await writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2));
};
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
index 7075f6dee16..ea132ec2a77 100644
--- a/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-init.spec.ts
@@ -23,6 +23,7 @@ import {
parseSingleJsonLine,
runCliForTest,
} from '@/__tests__/utils/run-cli-for-test';
+import { createAppProject } from '@/app/create-app-project';
import { getAppTemplateDirectory } from '@/app/get-app-template-directory';
import { CLI_VERSION } from '@/constants/cli-version.constant';
@@ -82,6 +83,55 @@ describe('app init', () => {
await rm(root, { recursive: true, force: true });
});
+ it.each([false, true])(
+ 'inherits shared template files and scripts with example=%s',
+ async (shouldIncludeExample) => {
+ const templateDirectory = join(root, 'template');
+ const appDirectory = join(workDirectory, 'my-app');
+
+ await cp(TEMPLATE_DIRECTORY, templateDirectory, { recursive: true });
+ await mkdir(join(templateDirectory, 'config'));
+ await writeFile(join(templateDirectory, 'config/shared.json'), '{}');
+ const templatePackageJson = await readPackageJson(templateDirectory);
+
+ templatePackageJson.scripts['check:shared'] = 'echo shared';
+ await writeFile(
+ join(templateDirectory, 'package.json'),
+ JSON.stringify(templatePackageJson),
+ );
+ vi.mocked(getAppTemplateDirectory).mockReturnValue(templateDirectory);
+
+ await createAppProject({
+ appDirectory,
+ appName: 'my-app',
+ appDisplayName: 'My app',
+ appDescription: '',
+ shouldIncludeExample,
+ signal: new AbortController().signal,
+ });
+
+ expect(
+ await readFile(join(appDirectory, 'config/shared.json'), 'utf8'),
+ ).toBe('{}');
+ expect((await readPackageJson(appDirectory)).scripts).toEqual({
+ ...templatePackageJson.scripts,
+ ...(shouldIncludeExample
+ ? JSON.parse(
+ await readFile(
+ join(templateDirectory, 'example/scripts.json'),
+ 'utf8',
+ ),
+ )
+ : {}),
+ });
+ const appFiles = await readdir(appDirectory);
+
+ expect(appFiles.includes('src')).toBe(shouldIncludeExample);
+ expect(appFiles.includes('public')).toBe(shouldIncludeExample);
+ expect(appFiles).not.toContain('example');
+ },
+ );
+
it('creates the app from the bundled template without installing or saving anything', async () => {
const result = await run(['my-app']);
const appDirectory = join(workDirectory, 'my-app');
@@ -157,7 +207,14 @@ describe('app init', () => {
expect(globalSetup).not.toContain('twenty-sdk/cli');
expect(await readFile(join(testsDirectory, 'run-twenty.ts'), 'utf8')).toBe(
await readFile(
- join(TEMPLATE_DIRECTORY, 'src', '__tests__', 'run-twenty.ts'),
+ join(
+ TEMPLATE_DIRECTORY,
+ 'example',
+ 'files',
+ 'src',
+ '__tests__',
+ 'run-twenty.ts',
+ ),
'utf8',
),
);
diff --git a/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts
index ec9b864ae5c..30c77795220 100644
--- a/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts
+++ b/packages/twenty-cli/src/commands/app/__tests__/app-pull.spec.ts
@@ -10,9 +10,15 @@ import {
symlink,
writeFile,
} from 'node:fs/promises';
+import { createStandardInputStub } from '@/__tests__/utils/create-standard-input-stub';
+import { getAppTemplateDirectory } from '@/app/get-app-template-directory';
+import { installAppDependenciesOrThrow } from '@/app/install-app-dependencies-or-throw';
+import { promptInTerminal } from '@/input/prompt-in-terminal';
+import { CliError } from '@/output/cli-error';
import { MetadataWritability } from 'twenty-shared/types';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
import {
afterAll,
afterEach,
@@ -40,6 +46,16 @@ const launch = vi.hoisted(() => ({ modulePath: '', execArgv: [] as string[] }));
vi.mock('@/app/get-app-worker-launch', () => ({
getAppWorkerLaunch: () => launch,
}));
+vi.mock('@/app/get-app-template-directory', () => ({
+ getAppTemplateDirectory: vi.fn(),
+}));
+vi.mock('@/app/install-app-dependencies-or-throw', () => ({
+ installAppDependenciesOrThrow: vi.fn(),
+}));
+vi.mock('@/input/prompt-in-terminal', () => ({ promptInTerminal: vi.fn() }));
+const TEMPLATE_DIRECTORY = fileURLToPath(
+ new URL('../../../../app-template', import.meta.url),
+);
const OBJECT_ID = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
const WORKSPACE_ID = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
const BASE_PATH = '.twenty/cli/pull-base.json';
@@ -76,10 +92,18 @@ const createExport = () => ({
});
let exported = createExport();
let forbidden = false;
+let customApplication: { universalIdentifier: string } | null = {
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+};
const server = await startTestServer((request, response) => {
if (request.body.includes('currentWorkspace')) {
return sendJson(response, 200, {
- data: { currentWorkspace: { id: WORKSPACE_ID } },
+ data: {
+ currentWorkspace: {
+ id: WORKSPACE_ID,
+ workspaceCustomApplication: customApplication,
+ },
+ },
});
}
if (forbidden) {
@@ -108,11 +132,24 @@ describe('app pull command with the packaged worker', () => {
await rm(workerPath, { recursive: true, force: true });
});
beforeEach(async () => {
+ vi.mocked(getAppTemplateDirectory).mockReturnValue(TEMPLATE_DIRECTORY);
+ vi.mocked(promptInTerminal).mockReset();
+ vi.mocked(installAppDependenciesOrThrow)
+ .mockReset()
+ .mockImplementation(async ({ appPath }) => {
+ const packageJson = await readFile(
+ join(appPath, 'package.json'),
+ 'utf8',
+ );
+ await createSourceTestApp(appPath);
+ await writeFile(join(appPath, 'package.json'), packageJson);
+ });
appPath = await mkdtemp(join(tmpdir(), 'twenty-cli-pull-'));
sdkPath = await createSourceTestApp(appPath);
await writeFile(join(appPath, 'app.ts'), sourceApplication());
exported = createExport();
forbidden = false;
+ customApplication = { universalIdentifier: SOURCE_TEST_APPLICATION_ID };
server.requests.length = 0;
vi.stubEnv('TWENTY_API_URL', server.url);
vi.stubEnv('TWENTY_API_KEY', 'must-not-reach-source');
@@ -121,6 +158,7 @@ describe('app pull command with the packaged worker', () => {
});
afterEach(async () => {
vi.unstubAllEnvs();
+ vi.restoreAllMocks();
await rm(appPath, { recursive: true, force: true });
});
@@ -395,25 +433,194 @@ export default defineObject({ nameSingular: 'invalid' });`,
});
});
- it('requires an explicit UUID in a project without an app definition', async () => {
+ it('pulls the workspace custom application without an identifier or local definition', async () => {
await rm(join(appPath, 'app.ts'));
- expect((await runJson()).envelope.error.code).toBe('INVALID_INPUT');
+ const result = await runJson();
+
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ expect(result.envelope.data.application.universalIdentifier).toBe(
+ SOURCE_TEST_APPLICATION_ID,
+ );
+ expect(readGraphqlRequest(server.requests[0]).query).toContain(
+ 'workspaceCustomApplication',
+ );
+ expect(readGraphqlRequest(server.requests[1]).arguments).toEqual({
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ shouldIncludeDependencies: true,
+ });
+ expect(
+ await readFile(join(appPath, 'src/application.config.ts'), 'utf8'),
+ ).toContain(SOURCE_TEST_APPLICATION_ID);
+ });
+
+ it.each([null, { universalIdentifier: OBJECT_ID }])(
+ 'uses the locally declared application when the workspace custom application is %j',
+ async (customApplicationValue) => {
+ customApplication = customApplicationValue;
+ const result = await runJson();
+
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ expect(readGraphqlRequest(server.requests[0]).query).not.toContain(
+ 'workspaceCustomApplication',
+ );
+ expect(readGraphqlRequest(server.requests[1]).arguments).toEqual({
+ universalIdentifier: SOURCE_TEST_APPLICATION_ID,
+ shouldIncludeDependencies: true,
+ });
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ expect(promptInTerminal).not.toHaveBeenCalled();
+ },
+ );
+
+ it('fails without creating a project when the custom application is missing', async () => {
+ await rm(appPath, { recursive: true });
+ customApplication = null;
+ const result = await runJson('--yes');
+
+ expect(result.envelope.error).toMatchObject({
+ code: 'APP_NOT_FOUND',
+ message: 'This workspace has no custom application to pull.',
+ });
+ expect(server.requests).toHaveLength(1);
+ await expect(stat(appPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ });
+
+ it('rejects a malformed workspace custom application identifier before export', async () => {
+ await rm(join(appPath, 'app.ts'));
+ customApplication = { universalIdentifier: 'not-a-uuid' };
+
+ expect((await runJson()).envelope.error.code).toBe('INVALID_RESPONSE');
+ expect(server.requests).toHaveLength(1);
+ expect(await readdir(appPath)).not.toContain('.twenty');
+ });
+
+ it('rejects the removed identifier option before contacting the workspace', async () => {
+ expect((await runJson('--universal-identifier', OBJECT_ID)).exitCode).toBe(
+ 2,
+ );
expect(server.requests).toHaveLength(0);
+ });
+
+ it('creates and pulls a clean project into a new directory with --yes', async () => {
+ await rm(appPath, { recursive: true });
+ const result = await runJson('--yes');
+
+ expect(result.exitCode, JSON.stringify(result.envelope)).toBe(0);
+ expect(result.envelope.data.pulled).toBe(true);
+ expect(installAppDependenciesOrThrow).toHaveBeenCalledOnce();
+ expect(promptInTerminal).not.toHaveBeenCalled();
+ expect(await readdir(join(appPath, 'src'))).toEqual([
+ 'application.config.ts',
+ 'objects',
+ ]);
expect(
- (
- await runJson(
- '--universal-identifier',
- SOURCE_TEST_APPLICATION_ID.toUpperCase(),
- )
- ).exitCode,
- ).toBe(0);
+ await readFile(join(appPath, 'src/application.config.ts'), 'utf8'),
+ ).toContain(SOURCE_TEST_APPLICATION_ID);
+ expect(
+ await readFile(join(appPath, 'src/objects/pet.object.ts'), 'utf8'),
+ ).toContain(OBJECT_ID);
+ expect(
+ JSON.parse(await readFile(join(appPath, 'package.json'), 'utf8')).scripts
+ .typecheck,
+ ).toBe('tsgo --noEmit -p tsconfig.json');
+ expect(await readdir(appPath)).not.toContain('public');
+ const second = await runJson();
+ expect(second.exitCode, JSON.stringify(second.envelope)).toBe(0);
+ expect(second.envelope.data.base.status).toBe('used');
+ expect(installAppDependenciesOrThrow).toHaveBeenCalledOnce();
});
- it('rejects a different app before requesting the export', async () => {
+ it('asks for the directory and confirmation outside an app', async () => {
+ await rm(appPath, { recursive: true });
+ await mkdir(appPath);
+ vi.spyOn(process, 'cwd').mockReturnValue(appPath);
+ vi.stubEnv('CI', 'false');
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ isTerminal: true }),
+ );
+ vi.mocked(promptInTerminal)
+ .mockResolvedValueOnce('workspace-app')
+ .mockResolvedValueOnce('yes');
+
+ const result = await runCliForTest(['app', 'pull']);
+
+ expect(result.exitCode, result.stderr).toBe(0);
+ expect(promptInTerminal).toHaveBeenCalledTimes(2);
+ expect(vi.mocked(promptInTerminal).mock.calls[1][0].question).toContain(
+ 'install its dependencies',
+ );
+ expect(await readdir(appPath)).toEqual(['workspace-app']);
expect(
- (await runJson('--universal-identifier', OBJECT_ID)).envelope.error.code,
- ).toBe('INVALID_INPUT');
- expect(server.requests).toHaveLength(0);
+ await readFile(
+ join(appPath, 'workspace-app/src/application.config.ts'),
+ 'utf8',
+ ),
+ ).toContain(SOURCE_TEST_APPLICATION_ID);
+ });
+
+ it('does not create anything when the user declines', async () => {
+ await rm(appPath, { recursive: true });
+ vi.stubEnv('CI', 'false');
+ vi.spyOn(process, 'stdin', 'get').mockReturnValue(
+ createStandardInputStub({ isTerminal: true }),
+ );
+ vi.mocked(promptInTerminal).mockResolvedValueOnce('no');
+
+ const result = await run();
+
+ expect(result.exitCode).toBe(2);
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ await expect(stat(appPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('requires approval in noninteractive mode before creating files', async () => {
+ await rm(appPath, { recursive: true });
+ const result = await runJson('--no-input');
+
+ expect(result.envelope.error.code).toBe('CONFIRMATION_REQUIRED');
+ expect(promptInTerminal).not.toHaveBeenCalled();
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ await expect(stat(appPath)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('requires a destination when creating without prompts', async () => {
+ await rm(appPath, { recursive: true });
+ await mkdir(appPath);
+ vi.spyOn(process, 'cwd').mockReturnValue(appPath);
+
+ const result = await runCliForTest(['app', 'pull', '--yes', '--json']);
+
+ expect(parseSingleJsonLine(result.stdout).error.code).toBe(
+ 'APP_PATH_REQUIRED',
+ );
+ expect(await readdir(appPath)).toEqual([]);
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ });
+
+ it('preserves files in an unrelated nonempty directory', async () => {
+ await rm(appPath, { recursive: true });
+ await mkdir(appPath);
+ await writeFile(join(appPath, 'notes.txt'), 'keep me');
+ const result = await runJson('--yes');
+
+ expect(result.envelope.error.code).toBe('APP_PATH_UNAVAILABLE');
+ expect(await readdir(appPath)).toEqual(['notes.txt']);
+ expect(await readFile(join(appPath, 'notes.txt'), 'utf8')).toBe('keep me');
+ expect(installAppDependenciesOrThrow).not.toHaveBeenCalled();
+ });
+
+ it('does not write pulled definitions after an installation failure', async () => {
+ await rm(appPath, { recursive: true });
+ vi.mocked(installAppDependenciesOrThrow).mockRejectedValue(
+ new CliError({ code: 'APP_INIT_FAILED', message: 'Yarn failed' }),
+ );
+ const result = await runJson('--yes');
+
+ expect(result.envelope.error.code).toBe('APP_INIT_FAILED');
+ expect(await readdir(appPath)).toContain('package.json');
+ expect(await readdir(appPath)).not.toContain('src');
+ expect(await readdir(appPath)).not.toContain('.twenty');
});
it('leaves local files untouched when server authorization fails', async () => {
diff --git a/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts b/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts
index afe37ec313c..ac17110540b 100644
--- a/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts
+++ b/packages/twenty-cli/src/commands/app/pull/app-pull.command-definition.ts
@@ -2,27 +2,29 @@ import { type TargetCommandDefinition } from '@/catalog/types/command-definition
export const APP_PULL_COMMAND_DEFINITION: TargetCommandDefinition = {
path: ['app', 'pull'],
- description: 'Pull workspace metadata into an existing app project',
+ description:
+ 'Pull an app, or create a local project for the workspace custom app',
options: [
{
flags: '--path <directory>',
description:
- 'App directory (default: the app containing the current folder)',
+ 'App directory, or a new or empty directory for the workspace custom app',
},
{
- flags: '--universal-identifier <uuid>',
+ flags: '--yes',
description:
- 'Application to pull when this project has no application definition',
+ 'Create a missing project and install its dependencies without prompting',
},
{ flags: '--verbose', description: 'List coverage details' },
],
examples: [
'twenty app pull --remote dev',
- 'twenty app pull --path ./apps/billing --json',
+ 'twenty app pull --path ./apps/billing',
+ 'twenty app pull --path ./workspace-app --yes --json',
],
outputModes: ['human', 'json'],
writes: true,
- needsProject: true,
+ needsProject: false,
needsTarget: true,
requiredPermissions: ['APPLICATIONS'],
load: async () =>
diff --git a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts
index e91eb1b8eae..298947b13c4 100644
--- a/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts
+++ b/packages/twenty-cli/src/commands/app/pull/run-app-pull-command.ts
@@ -1,8 +1,8 @@
-import { isValidUniversalIdentifier } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { fetchAppExport } from '@/app/fetch-app-export';
-import { fetchWorkspaceId } from '@/app/fetch-workspace-id';
+import { fetchWorkspaceOrThrow } from '@/app/fetch-workspace-or-throw';
+import { createPullProject } from '@/app/pull/create-pull-project';
import { formatToolingDiagnostic } from '@/app/format-tooling-diagnostic';
import { parseToolingResult } from '@/app/parse-tooling-result';
import { formatPullReport } from '@/app/pull/format-pull-report';
@@ -23,72 +23,61 @@ import { CliError } from '@/output/cli-error';
import { EXIT_CODE } from '@/output/constants/exit-code.constant';
import { commandText, formatSuccessLine } from '@/output/style';
-export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({
- options,
- target,
- signal,
- output,
- outputMode,
-}) => {
- const project = await resolveAppProject({
+export const runAppPullCommand: CommandRun<TargetCommandContext> = async (
+ context,
+) => {
+ const { options, target, signal, output, outputMode } = context;
+ let project = await resolveAppProject({
explicitPath: readStringOption(options, 'path'),
workingDirectory: process.cwd(),
+ }).catch((error: unknown) => {
+ if (
+ error instanceof CliError &&
+ ['APP_NOT_FOUND', 'APP_PATH_REQUIRED'].includes(error.code)
+ ) {
+ return undefined;
+ }
+ throw error;
});
-
- const explicitIdentifier = readStringOption(options, 'universalIdentifier');
-
- if (
- isDefined(explicitIdentifier) &&
- !isValidUniversalIdentifier(explicitIdentifier)
- ) {
- throw new CliError({
- code: 'INVALID_INPUT',
- exitCode: EXIT_CODE.USAGE,
- message: '--universal-identifier must be a UUID of version 4 or later.',
- });
- }
-
- const identity = await readAppIdentity({
- appPath: project.path,
+ const identity = isDefined(project)
+ ? await readAppIdentity({
+ appPath: project.path,
+ signal,
+ warn: output.warn,
+ })
+ : { application: null, diagnostics: [] };
+ const workspace = await fetchWorkspaceOrThrow({
+ target,
signal,
- warn: output.warn,
+ shouldIncludeCustomApplication: !isDefined(identity.application),
});
-
const universalIdentifier = (
- explicitIdentifier ?? identity.application?.universalIdentifier
+ identity.application?.universalIdentifier ??
+ workspace.workspaceCustomApplication?.universalIdentifier
)?.toLowerCase();
if (!isDefined(universalIdentifier)) {
throw new CliError({
- code: 'INVALID_INPUT',
- exitCode: EXIT_CODE.USAGE,
- message: 'This project has no application definition.',
- hint: 'Pass --universal-identifier <uuid> to pull an app into this project.',
+ code: 'APP_NOT_FOUND',
+ message: 'This workspace has no custom application to pull.',
});
}
- if (
- isDefined(identity.application) &&
- identity.application.universalIdentifier.toLowerCase() !==
- universalIdentifier
- ) {
- throw new CliError({
- code: 'INVALID_INPUT',
- exitCode: EXIT_CODE.USAGE,
- message: `This project declares application ${identity.application.universalIdentifier}, not ${universalIdentifier}. Pull it into a different directory.`,
+ output.progress({ message: `Exporting the app from ${target.apiUrl}…` });
+
+ const applicationExport = await fetchAppExport({
+ universalIdentifier,
+ target,
+ signal,
+ shouldIncludeDependencies: true,
+ });
+ if (!isDefined(project)) {
+ project = await createPullProject({
+ context,
+ displayName: applicationExport.application.displayName,
});
}
- output.progress({ message: `Exporting the app from ${target.apiUrl}…` });
- const [workspaceId, applicationExport] = await Promise.all([
- fetchWorkspaceId({ target, signal }),
- fetchAppExport({
- universalIdentifier,
- target,
- signal,
- shouldIncludeDependencies: true,
- }),
- ]);
output.progress({
message:
'Reconciling local definitions. Changed workspace entities replace local edits…',
@@ -98,7 +87,7 @@ export const runAppPullCommand: CommandRun<TargetCommandContext> = async ({
request: {
type: 'pull',
appPath: project.path,
- target: { apiUrl: target.apiUrl, workspaceId },
+ target: { apiUrl: target.apiUrl, workspaceId: workspace.id },
applicationExport,
},
signal,
diff --git a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
index e0106fbe26e..aee1ee58693 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/sync-and-recovery.mdx
@@ -112,10 +112,15 @@ A plan:
`twenty app pull` is the inverse of `apply`: it reads an application out of the workspace and restores its define files, translations and stored dependency files.
```bash
-twenty app pull --universal-identifier <universalIdentifier>
+twenty app pull --remote dev
+twenty app pull --path ./workspace-app --yes --no-input
```
-Pull needs an existing project — scaffold one with `twenty app init` first, then pull into it. Without `--universal-identifier`, pull targets the application your local `defineApplication()` file declares. If `--universal-identifier` names a different application than the one your project declares, pull refuses rather than leaving two applications in one tree: pull that one into its own directory. If the project has an application file whose identifier cannot be read, usually because dependencies are not installed, pull refuses too and asks you to run `yarn install` first. Add `--verbose` to expand the coverage sections of the report, which then name up to 20 identifiers per metadata type instead of only the totals.
+Inside an app, pull reads its local `defineApplication()` identifier and retrieves that application. Outside an app, it asks for a directory and confirmation, creates a local project for the selected workspace's custom application, installs dependencies with Yarn, then pulls the definitions. The new project includes package and configuration files, without the initializer's demo entities.
+
+Use `--path` to select an existing app or a new or empty directory. Noninteractive creation requires `--path` and `--yes`; pull refuses to overwrite an unrelated nonempty directory. Creating a project does not register an application or change the workspace. An existing SDK project without an application definition also pulls the custom application. There is no `--universal-identifier` option.
+
+If dependency installation fails for a new project, the scaffold is kept. Run `yarn install` inside it, then retry pull. Existing projects do not install dependencies automatically. If their application identifier cannot be read, pull reports that error instead of creating another app. Add `--verbose` to expand the coverage sections of the report, which then name up to 20 identifiers per metadata type instead of only the totals.
**What it writes:**