Skip to content

The open alternative to Salesforce, designed for AI.

feat(cli): restore local development environment commands (#29301)

Weiko55b9ab6c70ab
diff --git a/packages/twenty-agent-skills/references/concepts/how-apps-work.md b/packages/twenty-agent-skills/references/concepts/how-apps-work.md
index 0835e2b1d53..67aaffcd630 100644
--- a/packages/twenty-agent-skills/references/concepts/how-apps-work.md
+++ b/packages/twenty-agent-skills/references/concepts/how-apps-work.md
@@ -37,7 +37,7 @@ The API key authenticates the developer against the target workspace. It determi
Connect to an existing Twenty workspace with `twenty auth login --url <twenty-instance-url> --name dev`. This opens browser authentication and saves a remote.
-For local development, provision a separate Twenty server through Docker or the repository's development environment, then authenticate against its URL. The standalone CLI does not start containers.
+For local development, run `twenty local start` to create or start the full Twenty environment, then authenticate against `http://localhost:2020`. Docker must be installed and running. Use `--test` for a separate instance on port `2021`. The repository's development environment remains an alternative.
## App Lifecycle
diff --git a/packages/twenty-agent-skills/references/concepts/operating-rules.md b/packages/twenty-agent-skills/references/concepts/operating-rules.md
index 5fa3ce4bbaa..a1adc76a58d 100644
--- a/packages/twenty-agent-skills/references/concepts/operating-rules.md
+++ b/packages/twenty-agent-skills/references/concepts/operating-rules.md
@@ -6,7 +6,7 @@ This file is the single source of truth for the cross-skill rules. Harness-speci
1. **Bounded sync only.** Use `twenty app apply` to synchronize app changes. Never `twenty app dev` (watch mode). Watch mode leaks file handles and produces ambiguous failure output in agent sandboxes.
-2. **Do not run broad validation unless it is requested.** After scaffolding (`twenty app init`) or after the CLI generates entities, prefer the bounded command that matches the task: `twenty app apply` for app sync, the package's unit-test script for unit tests, and `TWENTY_API_URL=http://localhost:2021 yarn test` for the full integration suite. Integration tests must target the isolated test instance on port `2021`, not the dev instance on port `2020`, unless the user explicitly asks otherwise.
+2. **Do not run broad validation unless it is requested.** After scaffolding (`twenty app init`) or after the CLI generates entities, prefer the bounded command that matches the task: `twenty app apply` for app sync, the package's unit-test script for unit tests, and `TWENTY_API_URL=http://localhost:2021 yarn test` for the full integration suite. Start it with `twenty local start --test`. Integration tests must target the isolated test instance on port `2021`, not the dev instance on port `2020`, unless the user explicitly asks otherwise.
3. **Generate new entities with a CLI.** A CLI produces the file structure, identifiers, SDK imports and boilerplate. Hand-craft an entity file only to modify an existing one, or when no option below can produce it. Take the first option that works:
1. **The standalone `twenty` CLI, when `command -v twenty` finds it.** Run it directly, not through `yarn`. It works with or without a terminal: with `--no-input` it never prompts and exits with code 2 when a required value is missing. It covers objects, fields, logic functions and front components. For an object, pass the three `--create-*` flags so it also generates the table view, navigation menu item and record page layout that make the object visible in the UI:
diff --git a/packages/twenty-agent-skills/references/develop-app/tests.md b/packages/twenty-agent-skills/references/develop-app/tests.md
index e9baa66ec17..c0651df01b2 100644
--- a/packages/twenty-agent-skills/references/develop-app/tests.md
+++ b/packages/twenty-agent-skills/references/develop-app/tests.md
@@ -34,13 +34,13 @@ src/utils/__tests__/map-bar.util.spec.ts
Integration tests build, deploy, install, and uninstall the app on whatever server `TWENTY_API_URL` points to. The scaffold defaults to the dev instance (`http://localhost:2020`), so running them there adds and then removes the app from the workspace you sync to with `twenty app apply`. Always run them against the isolated test instance instead — a separate container, database, and port (`2021`) that does not affect your running dev instance:
```bash
-# Start an already provisioned isolated test container.
-docker start twenty-app-dev-test
+# Create or start the isolated test environment.
+twenty local start --test
# Run integration tests against it.
TWENTY_API_URL=http://localhost:2021 yarn test
```
-Provision the isolated test container before starting it, using the local-server documentation. Set `TWENTY_API_KEY` for that instance; the CLI no longer provisions Docker containers. This mirrors CI, which spawns the same isolated instance via the `spawn-twenty-app-dev-test` action.
+Set `TWENTY_API_KEY` for that isolated instance. `twenty local start --test` creates it when missing and preserves its data when restarting. New test instances use the same rate limits and disabled marketplace sync as CI. CI creates a fresh instance through the `spawn-twenty-app-dev-test` action; local restarts preserve existing settings and data.
When the user asks you to run tests, do run them. First start or verify the isolated test instance, then run the test command with `TWENTY_API_URL=http://localhost:2021`. Do not run integration tests against `http://localhost:2020` unless the user explicitly asks to target the dev instance. If only unit tests are requested, use the package's unit-test script and no `TWENTY_API_URL` override is needed.
diff --git a/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md b/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md
index 2339f077097..fc18fb1b2bf 100644
--- a/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md
+++ b/packages/twenty-agent-skills/references/manage-app/cli-and-sync.md
@@ -158,7 +158,22 @@ twenty app uninstall
twenty app uninstall --yes
```
-Integration tests install and uninstall the app on their target server, so run them against the isolated test instance (`docker start twenty-app-dev-test`, port `2021`) rather than the dev instance — see `../develop-app/tests.md`.
+Integration tests install and uninstall the app on their target server, so run them against the isolated test instance (`twenty local start --test`, port `2021`) rather than the dev instance — see `../develop-app/tests.md`.
+
+## Local development environment
+
+`twenty local start` runs a complete local Twenty instance, including web UI,
+API, worker and databases. Docker must be running with a local socket context.
+No app directory or saved remote is required. Login remains separate:
+`twenty auth login --url http://localhost:2020 --name local`.
+
+Use `local status`, `local logs` and `local stop` to inspect and stop it.
+`start [version]` preserves existing instances. New instances use the explicit
+version, the highest published match for `engines.twenty`, or `latest` when no
+range exists.
+
+Use `--test` consistently for the separate test instance on port `2021`.
+Stopping an instance preserves data. None of these commands changes remotes.
## CI/CD
diff --git a/packages/twenty-agent-skills/scripts/validators/cross-doc-contracts.js b/packages/twenty-agent-skills/scripts/validators/cross-doc-contracts.js
index d6b0b4b393d..0b3f3f7e8f3 100644
--- a/packages/twenty-agent-skills/scripts/validators/cross-doc-contracts.js
+++ b/packages/twenty-agent-skills/scripts/validators/cross-doc-contracts.js
@@ -393,7 +393,7 @@ const assertTestingGuidance = (fail) => {
const requiredManageFragments = [
'run tests for my Twenty app',
'references/develop-app/tests.md',
- 'docker start twenty-app-dev-test',
+ 'twenty local start --test',
'TWENTY_API_URL=http://localhost:2021 yarn test',
'Do not run integration tests against the dev instance on `http://localhost:2020`',
];
@@ -423,7 +423,7 @@ const assertTestingGuidance = (fail) => {
const requiredCliFragments = [
'Integration tests install and uninstall the app on their target server',
- 'docker start twenty-app-dev-test',
+ 'twenty local start --test',
'port `2021`',
'../develop-app/tests.md',
];
diff --git a/packages/twenty-agent-skills/skills/create-app/SKILL.md b/packages/twenty-agent-skills/skills/create-app/SKILL.md
index 8383f41a9e9..15c8f06a4d1 100644
--- a/packages/twenty-agent-skills/skills/create-app/SKILL.md
+++ b/packages/twenty-agent-skills/skills/create-app/SKILL.md
@@ -26,7 +26,7 @@ yarn install
Use `--path <directory>` for a different destination and `--display-name` or `--description` for metadata. The positional name is the package name.
-Twenty Cloud and self-hosted instances are supported. Ask for the existing Twenty workspace URL when connection is needed. If the user wants a local server, use the documented Docker or repository development environment.
+Twenty Cloud and self-hosted instances are supported. Ask for the existing Twenty workspace URL when connection is needed. If the user wants a local environment, run `twenty local start`, then authenticate separately with `twenty auth login`. A repository development environment also works.
```bash
twenty auth login --url <twenty-instance-url> --name dev
diff --git a/packages/twenty-agent-skills/skills/manage-app/SKILL.md b/packages/twenty-agent-skills/skills/manage-app/SKILL.md
index a499ab52fe4..ff110fa4248 100644
--- a/packages/twenty-agent-skills/skills/manage-app/SKILL.md
+++ b/packages/twenty-agent-skills/skills/manage-app/SKILL.md
@@ -55,7 +55,7 @@ For command details, remotes, validation command semantics, sync modes, troubles
If the user asks to run tests, also read `../../references/develop-app/tests.md` before running any test command. Full test suites include integration tests that install and uninstall the app on their target server, so start or verify the isolated test instance and run:
```bash
-docker start twenty-app-dev-test
+twenty local start --test
TWENTY_API_URL=http://localhost:2021 yarn test
```
diff --git a/packages/twenty-cli/CONTRIBUTING.md b/packages/twenty-cli/CONTRIBUTING.md
index c6fa2d4b90c..b2d1bd12aae 100644
--- a/packages/twenty-cli/CONTRIBUTING.md
+++ b/packages/twenty-cli/CONTRIBUTING.md
@@ -49,6 +49,7 @@ changed server workflows against a disposable workspace when appropriate.
| `src/config`, `src/target`, `src/oauth` | Saved connections, target selection and authentication |
| `src/transport` | HTTP/GraphQL requests, proxy routing, limits and cancellation |
| `src/metadata`, `src/data` | Workspace metadata inspection and record reads |
+| `src/local` | Local development instance lifecycle, Docker subprocesses, image selection and readiness |
| `src/doctor` | Read-only setup and connection diagnostics |
| `src/app` | Project tooling and application lifecycle, see its [module map](src/app/README.md) |
| `src/input`, `src/output` | Input parsing, human/JSON/NDJSON output and error contracts |
diff --git a/packages/twenty-cli/docs/commands.md b/packages/twenty-cli/docs/commands.md
index f2523edc634..d287d89eae4 100644
--- a/packages/twenty-cli/docs/commands.md
+++ b/packages/twenty-cli/docs/commands.md
@@ -11,6 +11,7 @@ failure recovery. See the [README](../README.md) to build and start the CLI.
- [Open](#open-the-workspace)
- [Metadata](#inspect-the-data-model)
- [Records](#read-records)
+- [Local development environment](#run-a-local-development-environment)
- [App init](#create-an-app) and [add](#add-definitions-to-an-app)
- [Build and typecheck](#build-and-check-an-app)
- [Plan](#preview-app-changes), [apply](#apply-an-app) and [dev](#develop-an-app)
@@ -19,6 +20,51 @@ failure recovery. See the [README](../README.md) to build and start the CLI.
- [Expired browser sessions](#expired-browser-sessions)
- [Output and exit codes](#output)
+## Run a local development environment
+
+```bash
+twenty local start
+twenty local status
+twenty auth login --url http://localhost:2020 --name local
+twenty local logs --no-follow
+twenty local stop
+```
+
+`local` runs the full Twenty development environment, including the web UI,
+API, worker and databases. Docker must be installed and running with a local
+socket context; remote Docker endpoints are rejected. These commands need
+neither an app directory nor a saved workspace connection. They do not sign in,
+change remotes or apply an app.
+
+`start [version]` creates an instance or starts the existing one, and waits up
+to five minutes for `/healthz`. For a new instance, version selection is:
+explicit version or image tag, the highest published version matching the nearest
+`package.json`'s `engines.twenty`, then `latest` when no range exists. A failed
+lookup or unmatched range is an error, never a fallback to another version.
+New instances pull the selected image before creation, including when the tag
+is cached locally. Existing instances keep their image and port.
+A readiness failure leaves the container and data in place for diagnosis.
+
+New instances bind to loopback on port `2020`. Use `--port <port>` when creating
+one. `--test` selects the separate test instance, default port `2021`; pass it
+to every command intended for that instance. Data and file storage use separate
+named volumes for each instance. Existing SDK development containers and their
+volumes are reused.
+
+```bash
+twenty local start 2.53.1 --test
+twenty local logs --test --lines 100 --no-follow
+```
+
+`status` reports `not-created`, `stopped`, `starting` or `healthy`; unavailable
+Docker is an error. `logs` follows by default; `--no-follow` prints recent logs
+and exits. It supports human or NDJSON output, with a terminal result or error;
+other local commands support human or JSON output. Ctrl+C cancels the CLI
+operation, without stopping the environment or deleting data.
+
+`stop` preserves the container and all data. This development environment is
+not a production deployment tool.
+
## Connections and authentication
```bash
diff --git a/packages/twenty-cli/src/catalog/command-catalog.ts b/packages/twenty-cli/src/catalog/command-catalog.ts
index 41f17970e24..9304aeb4a6d 100644
--- a/packages/twenty-cli/src/catalog/command-catalog.ts
+++ b/packages/twenty-cli/src/catalog/command-catalog.ts
@@ -1,3 +1,7 @@
+import { LOCAL_START_COMMAND_DEFINITION } from '@/commands/local/start/local-start.command-definition';
+import { LOCAL_STOP_COMMAND_DEFINITION } from '@/commands/local/stop/local-stop.command-definition';
+import { LOCAL_STATUS_COMMAND_DEFINITION } from '@/commands/local/status/local-status.command-definition';
+import { LOCAL_LOGS_COMMAND_DEFINITION } from '@/commands/local/environment-logs/local-logs.command-definition';
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';
@@ -36,6 +40,11 @@ import { REMOTE_USE_COMMAND_DEFINITION } from '@/commands/remote/use/remote-use.
import { VERSION_COMMAND_DEFINITION } from '@/commands/version/version.command-definition';
export const COMMAND_CATALOG: CommandDefinition[] = [
+ LOCAL_START_COMMAND_DEFINITION,
+ LOCAL_STOP_COMMAND_DEFINITION,
+ LOCAL_STATUS_COMMAND_DEFINITION,
+ LOCAL_LOGS_COMMAND_DEFINITION,
+
APP_ADD_COMMAND_DEFINITION,
APP_APPLY_COMMAND_DEFINITION,
APP_DEV_COMMAND_DEFINITION,
diff --git a/packages/twenty-cli/src/catalog/command-topics.ts b/packages/twenty-cli/src/catalog/command-topics.ts
index 5ce30fcc423..40a1d16a779 100644
--- a/packages/twenty-cli/src/catalog/command-topics.ts
+++ b/packages/twenty-cli/src/catalog/command-topics.ts
@@ -3,6 +3,13 @@ import { type CommandTopicDefinition } from '@/catalog/types/command-topic-defin
import { AUTH_LOGIN_COMMAND_DEFINITION } from '@/commands/auth/login/auth-login.command-definition';
export const COMMAND_TOPICS: CommandTopicDefinition[] = [
+ {
+ path: ['local'],
+ description: 'Run a local Twenty development environment',
+ helpGroup: HELP_GROUP.APP,
+ helpHint:
+ 'Runs Twenty, including its web UI, worker and databases. Requires a local Docker installation. Sign in afterward with twenty auth login.',
+ },
{
path: ['app'],
description: 'Create, develop and manage applications',
diff --git a/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts b/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts
new file mode 100644
index 00000000000..ddf5c1b9758
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/__tests__/local-commands.spec.ts
@@ -0,0 +1,245 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ parseSingleJsonLine,
+ runCliForTest,
+} from '@/__tests__/utils/run-cli-for-test';
+import { checkLocalHealth } from '@/local/check-local-health';
+import { waitForLocalHealth } from '@/local/wait-for-local-health';
+import { getLocalEnvironment } from '@/local/get-local-environment';
+import { runDocker } from '@/local/run-docker';
+import { CliError } from '@/output/cli-error';
+
+vi.mock('@/local/run-docker', () => ({ runDocker: vi.fn() }));
+vi.mock('@/local/check-local-health', () => ({
+ checkLocalHealth: vi.fn(),
+}));
+vi.mock('@/local/wait-for-local-health', () => ({
+ waitForLocalHealth: vi.fn(),
+}));
+
+const environment = getLocalEnvironment(true);
+const makeContainer = (isRunning = true) => {
+ const portBindings: Record<string, { HostIp: string; HostPort: string }[]> = {
+ '2021/tcp': [{ HostIp: '127.0.0.1', HostPort: '12021' }],
+ };
+ return {
+ Id: 'test-container',
+ Config: {
+ Image: 'twentycrm/twenty-app-dev:v2.53.0',
+ },
+ State: { Running: isRunning },
+ HostConfig: {
+ PortBindings: portBindings,
+ },
+ };
+};
+let container: ReturnType<typeof makeContainer> | undefined;
+let failure: string | undefined;
+
+const runJson = async (args: string[]) => {
+ const result = await runCliForTest(['local', ...args, '--test', '--json']);
+ return { ...result, envelope: parseSingleJsonLine(result.stdout) };
+};
+const dockerArguments = () =>
+ vi.mocked(runDocker).mock.calls.map(([{ args }]) => args);
+const mutations = () =>
+ dockerArguments().filter(([command]) =>
+ ['run', 'start', 'stop', 'pull'].includes(command),
+ );
+
+describe('local commands', () => {
+ beforeEach(() => {
+ container = makeContainer();
+ failure = undefined;
+ vi.stubEnv('DOCKER_HOST', '');
+ vi.stubEnv('DOCKER_CONTEXT', '');
+ vi.stubEnv('TWENTY_REMOTE', '');
+ vi.stubEnv('TWENTY_API_URL', '');
+ vi.stubEnv('TWENTY_API_KEY', '');
+ vi.mocked(checkLocalHealth).mockResolvedValue(true);
+ vi.mocked(waitForLocalHealth).mockResolvedValue(undefined);
+ vi.mocked(runDocker).mockImplementation(async ({ args, onOutput }) => {
+ if (args[0] === failure || args.slice(0, 2).join(' ') === failure) {
+ throw new CliError({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: 'Docker failed',
+ });
+ }
+ if (args[0] === 'context') {
+ return 'unix:///var/run/docker.sock';
+ }
+ if (args[0] === 'info') {
+ return '28.0';
+ }
+ if (args[0] === 'container' && args[1] === 'ls') {
+ return container?.Id ?? '';
+ }
+ if (args[0] === 'container') {
+ return JSON.stringify(container);
+ }
+ if (args[0] === 'start' && isDefined(container)) {
+ container.State.Running = true;
+ }
+ if (args[0] === 'stop' && isDefined(container)) {
+ container.State.Running = false;
+ }
+ if (args[0] === 'run') {
+ container = makeContainer();
+ container.Config.Image = args.at(-1)!;
+ const [, hostPort, internalPort] =
+ args[args.indexOf('--publish') + 1].split(':');
+ container.HostConfig.PortBindings = {
+ [`${internalPort}/tcp`]: [
+ { HostIp: '127.0.0.1', HostPort: hostPort },
+ ],
+ };
+ }
+ if (args[0] === 'logs') {
+ await onOutput?.('server started\nworker ready\n');
+ }
+ return '';
+ });
+ });
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetAllMocks();
+ });
+
+ it('creates an isolated instance without an app or saved connection', async () => {
+ container = undefined;
+ const { exitCode, envelope } = await runJson([
+ 'start',
+ '2.54.0',
+ '--port',
+ '12021',
+ ]);
+ expect(exitCode).toBe(0);
+ expect(envelope.data).toMatchObject({
+ name: environment.name,
+ status: 'healthy',
+ url: 'http://localhost:12021',
+ });
+ const run = mutations().find(([command]) => command === 'run')!;
+ expect(run).toContain('127.0.0.1:12021:12021');
+ expect(run).toContain('twentycrm/twenty-app-dev:v2.54.0');
+ expect(run).toContain('twenty-app-dev-test-data:/data/postgres');
+ expect(run).toContain('API_RATE_LIMITING_SHORT_LIMIT=100000');
+ expect(run).toContain('API_RATE_LIMITING_LONG_LIMIT=100000');
+ expect(run).toContain('MARKETPLACE_CATALOG_SYNC_CRON_ENABLED=false');
+ expect(run).not.toContain('twenty-app-dev-data:/data/postgres');
+ });
+
+ it('refreshes latest before creating an instance, instead of trusting a stale cached image', async () => {
+ container = undefined;
+ expect((await runJson(['start'])).exitCode).toBe(0);
+ expect(mutations()[0]).toEqual(['pull', 'twentycrm/twenty-app-dev:latest']);
+ expect(mutations()[1][0]).toBe('run');
+ });
+
+ it('rejects an invalid image tag before pulling or creating anything', async () => {
+ container = undefined;
+ const { exitCode, envelope } = await runJson(['start', 'other/image:tag']);
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('INVALID_INPUT');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('restarts a stopped instance without replacing it or changing its port', async () => {
+ container = makeContainer(false);
+ const { exitCode, envelope } = await runJson(['start']);
+ expect(exitCode).toBe(0);
+ expect(envelope.data.url).toBe('http://localhost:12021');
+ expect(waitForLocalHealth).toHaveBeenCalledWith({
+ port: 12021,
+ signal: expect.any(AbortSignal),
+ });
+ expect(mutations()).toEqual([['start', 'test-container']]);
+ });
+
+ it.each([['--port', '2021'], ['2.54.0']])(
+ 'refuses to replace existing settings during start: %j',
+ async (...args) => {
+ const { exitCode, envelope } = await runJson(['start', ...args]);
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('CONFLICT');
+ expect(mutations()).toEqual([]);
+ },
+ );
+
+ it('reports unavailable Docker as a failure, not a missing environment', async () => {
+ failure = 'info';
+ const { exitCode, envelope } = await runJson(['status']);
+ expect(exitCode).toBe(1);
+ expect(envelope.error.code).toBe('LOCAL_ENVIRONMENT_FAILED');
+ });
+
+ it('distinguishes absent, stopped and unhealthy environments', async () => {
+ container = undefined;
+ expect((await runJson(['status'])).envelope.data.status).toBe(
+ 'not-created',
+ );
+ container = makeContainer(false);
+ expect((await runJson(['status'])).envelope.data.status).toBe('stopped');
+ container.State.Running = true;
+ vi.mocked(checkLocalHealth).mockResolvedValue(false);
+ expect((await runJson(['status'])).envelope.data.status).toBe('starting');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('does not claim startup success when readiness fails', async () => {
+ vi.mocked(waitForLocalHealth).mockRejectedValue(
+ new CliError({ code: 'TIMEOUT', message: 'Not ready' }),
+ );
+ expect((await runJson(['start'])).envelope.error.code).toBe('TIMEOUT');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('stops without removing the container or its data', async () => {
+ expect((await runJson(['stop'])).exitCode).toBe(0);
+ expect(mutations()).toEqual([['stop', 'test-container']]);
+ });
+
+ it('rejects malformed port bindings before changing the container', async () => {
+ container!.HostConfig.PortBindings = {};
+ expect((await runJson(['start'])).envelope.error.code).toBe('CONFLICT');
+ expect(mutations()).toEqual([]);
+ });
+
+ it('streams logs as NDJSON and emits a terminal result', async () => {
+ const { exitCode, stdout } = await runCliForTest([
+ 'local',
+ 'logs',
+ '--test',
+ '--no-follow',
+ '--format',
+ 'ndjson',
+ ]);
+ expect(exitCode).toBe(0);
+ const events = stdout
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ expect(events.map(({ type }) => type)).toEqual([
+ 'start',
+ 'record',
+ 'result',
+ ]);
+ expect(events[0].data).toEqual({
+ name: environment.name,
+ shouldFollow: false,
+ });
+ expect(events.at(-1).data).toEqual({
+ name: environment.name,
+ shouldFollow: false,
+ });
+ expect(events[1].data.message).toBe('server started\nworker ready\n');
+ expect(dockerArguments().at(-1)).toEqual([
+ 'logs',
+ '--tail',
+ '50',
+ 'test-container',
+ ]);
+ });
+});
diff --git a/packages/twenty-cli/src/commands/local/environment-logs/local-logs.command-definition.ts b/packages/twenty-cli/src/commands/local/environment-logs/local-logs.command-definition.ts
new file mode 100644
index 00000000000..886b1d304d9
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/environment-logs/local-logs.command-definition.ts
@@ -0,0 +1,28 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const LOCAL_LOGS_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['local', 'logs'],
+ description: 'Stream local environment logs',
+ options: [
+ {
+ flags: '-n, --lines <lines>',
+ description: 'Number of recent log lines (default: 50, maximum: 10000)',
+ },
+ {
+ flags: '--no-follow',
+ description: 'Print recent logs and exit',
+ },
+ {
+ flags: '--test',
+ description: 'Use the separate local test instance',
+ },
+ ],
+ examples: ['twenty local logs', 'twenty local logs --test --no-follow'],
+ outputModes: ['human', 'ndjson'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/local/environment-logs/run-local-logs-command'))
+ .runLocalLogsCommand,
+};
diff --git a/packages/twenty-cli/src/commands/local/environment-logs/run-local-logs-command.ts b/packages/twenty-cli/src/commands/local/environment-logs/run-local-logs-command.ts
new file mode 100644
index 00000000000..baae2526a41
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/environment-logs/run-local-logs-command.ts
@@ -0,0 +1,59 @@
+import { isDefined } from 'twenty-shared/utils';
+import { once } from 'node:events';
+
+import { readStringOption } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { checkLocalRuntime } from '@/local/check-local-runtime';
+import { readLocalInteger } from '@/local/read-local-integer';
+import { readLocalOptions } from '@/local/read-local-options';
+import { readLocalContainer } from '@/local/read-local-container';
+import { runDocker } from '@/local/run-docker';
+import { CliError } from '@/output/cli-error';
+
+export const runLocalLogsCommand: CommandRun<CommandContext> = async ({
+ options,
+ signal,
+ output,
+ outputMode,
+}) => {
+ const { environment } = readLocalOptions(options);
+ const lines =
+ readLocalInteger({
+ value: readStringOption(options, 'lines'),
+ name: '--lines',
+ maximum: 10000,
+ }) ?? 50;
+ const shouldFollow = options.follow !== false;
+ await checkLocalRuntime(signal);
+ const container = await readLocalContainer({ environment, signal });
+ if (!isDefined(container)) {
+ throw new CliError({
+ code: 'NOT_FOUND',
+ message: 'No local environment has been created.',
+ hint: 'Run twenty local start first (add --test for the test instance).',
+ });
+ }
+ await output.event('start', { name: environment.name, shouldFollow }, signal);
+ await runDocker({
+ args: [
+ 'logs',
+ '--tail',
+ String(lines),
+ ...(shouldFollow ? ['--follow'] : []),
+ container.id,
+ ],
+ signal,
+ onOutput: async (message) => {
+ if (outputMode === 'ndjson') {
+ await output.event('record', { message }, signal);
+ } else if (!process.stdout.write(message)) {
+ await once(process.stdout, 'drain', { signal });
+ }
+ },
+ });
+ return {
+ data: { name: environment.name, shouldFollow },
+ human: 'Log stream completed.',
+ };
+};
diff --git a/packages/twenty-cli/src/commands/local/start/local-start.command-definition.ts b/packages/twenty-cli/src/commands/local/start/local-start.command-definition.ts
new file mode 100644
index 00000000000..08a8c209e32
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/start/local-start.command-definition.ts
@@ -0,0 +1,33 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const LOCAL_START_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['local', 'start'],
+ description: 'Start the local Twenty development environment',
+ options: [
+ {
+ flags: '-p, --port <port>',
+ description:
+ 'HTTP port for a new instance (default: 2020, or 2021 with --test)',
+ },
+ {
+ flags: '--test',
+ description: 'Use the separate local test instance',
+ },
+ ],
+ arguments: [
+ {
+ name: 'version',
+ description:
+ 'Twenty version or image tag (new instances: engines.twenty, then latest)',
+ required: false,
+ },
+ ],
+ examples: ['twenty local start', 'twenty local start 2.53.1 --test'],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/local/start/run-local-start-command'))
+ .runLocalStartCommand,
+};
diff --git a/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts b/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts
new file mode 100644
index 00000000000..e6a6cdd1faf
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/start/run-local-start-command.ts
@@ -0,0 +1,89 @@
+import satisfies from 'semver/functions/satisfies';
+import valid from 'semver/functions/valid';
+import { isDefined } from 'twenty-shared/utils';
+
+import { readStringArgument } from '@/catalog/read-command-values';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { checkLocalRuntime } from '@/local/check-local-runtime';
+import { createLocalContainer } from '@/local/create-local-container';
+import { readLocalOptions } from '@/local/read-local-options';
+import { readLocalContainer } from '@/local/read-local-container';
+import { getLocalEngineRange } from '@/local/get-local-engine-range';
+import { getLocalImage } from '@/local/get-local-image';
+import { resolveLocalImage } from '@/local/resolve-local-image';
+import { runDocker } from '@/local/run-docker';
+import { waitForLocalEnvironment } from '@/local/wait-for-local-environment';
+import { CliError } from '@/output/cli-error';
+
+export const runLocalStartCommand: CommandRun<CommandContext> = async ({
+ options,
+ arguments: commandArguments,
+ output,
+ signal,
+}) => {
+ const { environment, port: requestedPort } = readLocalOptions(options);
+ const version = readStringArgument(commandArguments, 0);
+ const requestedImage = isDefined(version)
+ ? getLocalImage(version)
+ : undefined;
+
+ await checkLocalRuntime(signal);
+ const existing = await readLocalContainer({ environment, signal });
+ const port = existing?.port ?? requestedPort ?? environment.port;
+
+ if (
+ isDefined(existing) &&
+ ((isDefined(requestedPort) && requestedPort !== existing.port) ||
+ (isDefined(requestedImage) && requestedImage !== existing.image))
+ ) {
+ throw new CliError({
+ code: 'CONFLICT',
+ message: `${environment.name} already uses ${existing.image} on port ${existing.port}.`,
+ hint: 'Omit the version and --port options to reuse this instance.',
+ });
+ }
+
+ const range = isDefined(existing) ? getLocalEngineRange() : undefined;
+ const existingVersion = valid(existing?.image.split(':').at(-1));
+ if (
+ isDefined(existing) &&
+ isDefined(range) &&
+ (!isDefined(existingVersion) || !satisfies(existingVersion, range))
+ ) {
+ output.warn({
+ code: 'LOCAL_VERSION_MISMATCH',
+ message: `The existing image ${existing.image} does not establish compatibility with engines.twenty ${range}.`,
+ });
+ }
+
+ if (isDefined(existing) && !existing.isRunning) {
+ output.progress({ message: 'Starting the existing local environment…' });
+ await runDocker({ args: ['start', existing.id], signal });
+ }
+
+ if (!isDefined(existing)) {
+ const image =
+ requestedImage ??
+ (await resolveLocalImage({ version: undefined, signal }));
+ output.progress({ message: `Pulling ${image}…` });
+ await runDocker({ args: ['pull', image], signal });
+ output.progress({
+ message: `Starting ${image} on http://localhost:${port}…`,
+ });
+ await createLocalContainer({ environment, image, port, signal });
+ }
+
+ output.progress({
+ message: 'Waiting for the local environment to be ready…',
+ });
+ const data = await waitForLocalEnvironment({
+ environment: { ...environment, port },
+ signal,
+ });
+
+ return {
+ data,
+ human: `Local Twenty is ready at ${data.url}\nSign in: twenty auth login --url ${data.url} --name ${options.test ? 'local-test' : 'local'}`,
+ };
+};
diff --git a/packages/twenty-cli/src/commands/local/status/local-status.command-definition.ts b/packages/twenty-cli/src/commands/local/status/local-status.command-definition.ts
new file mode 100644
index 00000000000..db9dcae3d56
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/status/local-status.command-definition.ts
@@ -0,0 +1,20 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const LOCAL_STATUS_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['local', 'status'],
+ description: 'Show local environment status, URL and image',
+ options: [
+ {
+ flags: '--test',
+ description: 'Use the separate local test instance',
+ },
+ ],
+ examples: ['twenty local status --json'],
+ outputModes: ['human', 'json'],
+ writes: false,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/local/status/run-local-status-command'))
+ .runLocalStatusCommand,
+};
diff --git a/packages/twenty-cli/src/commands/local/status/run-local-status-command.ts b/packages/twenty-cli/src/commands/local/status/run-local-status-command.ts
new file mode 100644
index 00000000000..139f98a5204
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/status/run-local-status-command.ts
@@ -0,0 +1,21 @@
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { checkLocalRuntime } from '@/local/check-local-runtime';
+import { getLocalStatus } from '@/local/get-local-status';
+import { readLocalOptions } from '@/local/read-local-options';
+import { readLocalContainer } from '@/local/read-local-container';
+
+export const runLocalStatusCommand: CommandRun<CommandContext> = async ({
+ options,
+ signal,
+}) => {
+ const { environment } = readLocalOptions(options);
+ await checkLocalRuntime(signal);
+ const container = await readLocalContainer({ environment, signal });
+ const data = await getLocalStatus({ environment, container, signal });
+
+ return {
+ data,
+ human: `Status: ${data.status}\nURL: ${data.url}${data.image ? `\nImage: ${data.image}` : ''}`,
+ };
+};
diff --git a/packages/twenty-cli/src/commands/local/stop/local-stop.command-definition.ts b/packages/twenty-cli/src/commands/local/stop/local-stop.command-definition.ts
new file mode 100644
index 00000000000..e2f20af82e0
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/stop/local-stop.command-definition.ts
@@ -0,0 +1,20 @@
+import { type LocalCommandDefinition } from '@/catalog/types/command-definition.type';
+
+export const LOCAL_STOP_COMMAND_DEFINITION: LocalCommandDefinition = {
+ path: ['local', 'stop'],
+ description: 'Stop the local environment, preserving its data',
+ options: [
+ {
+ flags: '--test',
+ description: 'Use the separate local test instance',
+ },
+ ],
+ examples: ['twenty local stop'],
+ outputModes: ['human', 'json'],
+ writes: true,
+ needsProject: false,
+ needsTarget: false,
+ load: async () =>
+ (await import('@/commands/local/stop/run-local-stop-command'))
+ .runLocalStopCommand,
+};
diff --git a/packages/twenty-cli/src/commands/local/stop/run-local-stop-command.ts b/packages/twenty-cli/src/commands/local/stop/run-local-stop-command.ts
new file mode 100644
index 00000000000..fc3c7f5af46
--- /dev/null
+++ b/packages/twenty-cli/src/commands/local/stop/run-local-stop-command.ts
@@ -0,0 +1,30 @@
+import { isDefined } from 'twenty-shared/utils';
+import { type CommandRun } from '@/catalog/types/command-run.type';
+import { type CommandContext } from '@/catalog/types/command-context.type';
+import { checkLocalRuntime } from '@/local/check-local-runtime';
+import { readLocalOptions } from '@/local/read-local-options';
+import { readLocalContainer } from '@/local/read-local-container';
+import { runDocker } from '@/local/run-docker';
+
+export const runLocalStopCommand: CommandRun<CommandContext> = async ({
+ options,
+ signal,
+}) => {
+ const { environment } = readLocalOptions(options);
+ await checkLocalRuntime(signal);
+ const container = await readLocalContainer({ environment, signal });
+ if (container?.isRunning) {
+ await runDocker({ args: ['stop', container.id], signal });
+ }
+
+ return {
+ data: {
+ name: environment.name,
+ stopped: isDefined(container),
+ dataPreserved: true,
+ },
+ human: isDefined(container)
+ ? 'Local environment stopped. Data is preserved.'
+ : 'No local environment has been created.',
+ };
+};
diff --git a/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts b/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts
new file mode 100644
index 00000000000..a6bf35d9f35
--- /dev/null
+++ b/packages/twenty-cli/src/local/__tests__/resolve-local-image.spec.ts
@@ -0,0 +1,93 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getEngineVersionRange } from '@/app/manifest/get-engine-version-range';
+import { resolveLocalImage } from '@/local/resolve-local-image';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+
+vi.mock('@/app/manifest/get-engine-version-range', () => ({
+ getEngineVersionRange: vi.fn(),
+}));
+vi.mock('@/transport/fetch-with-proxy', () => ({ fetchWithProxy: vi.fn() }));
+const signal = new AbortController().signal;
+
+beforeEach(() => {
+ vi.mocked(getEngineVersionRange).mockReturnValue(null);
+});
+afterEach(() => {
+ vi.resetAllMocks();
+});
+
+describe('local image selection', () => {
+ it('selects the highest compatible published version across pages', async () => {
+ vi.mocked(getEngineVersionRange).mockReturnValue('^2.52.0');
+ vi.mocked(fetchWithProxy)
+ .mockResolvedValueOnce(
+ Response.json({
+ results: [
+ { name: 'v2.52.0' },
+ { name: 'latest' },
+ { name: 'v3.0.0' },
+ ],
+ next: 'next',
+ }),
+ )
+ .mockResolvedValueOnce(
+ Response.json({
+ results: [{ name: 'v2.53.1' }, { name: 'v2.54.0-beta.1' }],
+ next: null,
+ }),
+ );
+ expect(await resolveLocalImage({ version: undefined, signal })).toBe(
+ 'twentycrm/twenty-app-dev:v2.53.1',
+ );
+ });
+
+ it.each([
+ {
+ failure: 'network failure',
+ response: () => Promise.reject(new Error('Offline')),
+ reason: 'Offline',
+ },
+ {
+ failure: 'rate limit',
+ response: () => Promise.resolve(new Response(null, { status: 429 })),
+ reason: 'Image registry request failed (HTTP 429)',
+ },
+ {
+ failure: 'malformed response',
+ response: () => Promise.resolve(Response.json({ results: null })),
+ reason: 'Invalid image registry response',
+ },
+ {
+ failure: 'no compatible version',
+ response: () =>
+ Promise.resolve(
+ Response.json({ results: [{ name: 'v1.0.0' }], next: null }),
+ ),
+ reason: 'No published image matches engines.twenty',
+ },
+ ])(
+ 'reports $failure instead of falling back to latest',
+ async ({ response, reason }) => {
+ vi.mocked(getEngineVersionRange).mockReturnValue('^2.52.0');
+ vi.mocked(fetchWithProxy).mockImplementation(response);
+ await expect(
+ resolveLocalImage({ version: undefined, signal }),
+ ).rejects.toMatchObject({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: `Could not select a published Twenty image matching ^2.52.0: ${reason}`,
+ cause: expect.any(Error),
+ });
+ },
+ );
+
+ it('rejects an invalid app range before sending a request', async () => {
+ vi.mocked(getEngineVersionRange).mockReturnValue('invalid');
+ await expect(
+ resolveLocalImage({ version: undefined, signal }),
+ ).rejects.toMatchObject({
+ code: 'INVALID_INPUT',
+ });
+ expect(fetchWithProxy).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-cli/src/local/__tests__/run-docker.spec.ts b/packages/twenty-cli/src/local/__tests__/run-docker.spec.ts
new file mode 100644
index 00000000000..10f8f05e09b
--- /dev/null
+++ b/packages/twenty-cli/src/local/__tests__/run-docker.spec.ts
@@ -0,0 +1,183 @@
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { build } from 'esbuild';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ describe,
+ expect,
+ it,
+ vi,
+} from 'vitest';
+
+import { runDocker } from '@/local/run-docker';
+
+const directory = await mkdtemp(join(tmpdir(), 'twenty-local-runtime-'));
+
+beforeAll(async () => {
+ await writeFile(
+ join(directory, 'docker'),
+ `#!${process.execPath}
+if (process.argv[2] === 'fail') {
+ process.stderr.write('image version does not exist');
+ process.exitCode = 1;
+} else if (process.argv[2] === 'unicode') {
+ const stdout = Buffer.from('é🙂');
+ const stderr = Buffer.from('汉');
+ process.stdout.write(stdout.subarray(0, 1));
+ setTimeout(() => process.stderr.write(stderr.subarray(0, 1)), 50);
+ setTimeout(() => process.stdout.write(stdout.subarray(1)), 100);
+ setTimeout(() => process.stderr.write(stderr.subarray(1)), 150);
+} else if (process.argv[2] === 'logs') {
+ process.on('SIGTERM', () => {});
+ process.stdout.write(String(process.pid));
+ setInterval(() => {}, 100);
+} else {
+ process.stdout.write(JSON.stringify(process.argv.slice(2)));
+}
+`,
+ { mode: 0o700 },
+ );
+});
+afterAll(async () => {
+ await rm(directory, { recursive: true, force: true });
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
+
+describe('Docker subprocess', () => {
+ it('passes arguments literally without invoking a shell', async () => {
+ vi.stubEnv('PATH', directory);
+ const args = ['inspect', 'value; $(echo injected)'];
+ expect(
+ JSON.parse(
+ await runDocker({ args, signal: new AbortController().signal }),
+ ),
+ ).toEqual(args);
+ });
+
+ it('preserves split UTF-8 characters independently on stdout and stderr', async () => {
+ vi.stubEnv('PATH', directory);
+ let output = '';
+ await runDocker({
+ args: ['unicode'],
+ signal: new AbortController().signal,
+ onOutput: async (message) => {
+ output += message;
+ },
+ });
+ expect(output).toBe('é🙂汉');
+ });
+
+ it('reports Docker failures with the actual diagnostic', async () => {
+ vi.stubEnv('PATH', directory);
+ await expect(
+ runDocker({ args: ['fail'], signal: new AbortController().signal }),
+ ).rejects.toMatchObject({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: 'docker fail failed: image version does not exist',
+ });
+ });
+
+ it('reports a missing Docker executable as a runtime failure', async () => {
+ vi.stubEnv('PATH', join(directory, 'absent'));
+ await expect(
+ runDocker({ args: ['info'], signal: new AbortController().signal }),
+ ).rejects.toMatchObject({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ });
+ });
+
+ it('emits the CLI cancellation envelope on a real SIGINT while Docker is running', async () => {
+ const fixture = join(directory, 'command.cjs');
+ const sourceRoot = fileURLToPath(new URL('../../', import.meta.url));
+ await build({
+ stdin: {
+ contents: `
+ import { runCommand } from './program/run-command';
+ import { runDocker } from './local/run-docker';
+ void runCommand({
+ definition: {
+ path: ['local', 'logs'], outputModes: ['ndjson'], needsTarget: false,
+ load: async () => async ({ signal, output }) => {
+ await runDocker({ args: ['logs'], signal, onOutput: async (message) => output.event('record', { message }, signal) });
+ return { data: {} };
+ },
+ },
+ outputMode: 'ndjson', commandArguments: [], options: {},
+ });
+ `,
+ resolveDir: sourceRoot,
+ },
+ tsconfig: join(sourceRoot, '../tsconfig.json'),
+ outfile: fixture,
+ bundle: true,
+ platform: 'node',
+ format: 'cjs',
+ logLevel: 'silent',
+ });
+ const result = await new Promise<{ code: number | null; output: string }>(
+ (resolve, reject) => {
+ const child = spawn(process.execPath, [fixture], {
+ env: { ...process.env, PATH: directory },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let output = '';
+ let hasInterrupted = false;
+ const timeout = setTimeout(() => {
+ child.kill('SIGKILL');
+ reject(new Error('Cancellation timed out'));
+ }, 5000);
+ child.stdout.on('data', (chunk) => {
+ output += String(chunk);
+ if (!hasInterrupted && output.includes('\n')) {
+ hasInterrupted = true;
+ child.kill('SIGINT');
+ }
+ });
+ child.once('error', (error) => {
+ clearTimeout(timeout);
+ reject(error);
+ });
+ child.once('close', (code) => {
+ clearTimeout(timeout);
+ resolve({ code, output });
+ });
+ },
+ );
+ expect(result.code).toBe(130);
+ const events = result.output
+ .trim()
+ .split('\n')
+ .map((line) => JSON.parse(line));
+ expect(events.at(-1)).toMatchObject({
+ type: 'error',
+ data: { code: 'CANCELLED' },
+ });
+ expect(() => process.kill(Number(events[0].data.message), 0)).toThrow();
+ });
+
+ it('cancels a streaming subprocess, including one that ignores SIGTERM', async () => {
+ vi.stubEnv('PATH', directory);
+ const controller = new AbortController();
+ let processId = 0;
+ await expect(
+ runDocker({
+ args: ['logs'],
+ signal: controller.signal,
+ onOutput: async (message) => {
+ processId = Number(message);
+ controller.abort();
+ },
+ }),
+ ).rejects.toMatchObject({ code: 'CANCELLED' });
+ expect(processId).toBeGreaterThan(0);
+ expect(() => process.kill(processId, 0)).toThrow();
+ });
+});
diff --git a/packages/twenty-cli/src/local/check-local-health.ts b/packages/twenty-cli/src/local/check-local-health.ts
new file mode 100644
index 00000000000..4090b12e51b
--- /dev/null
+++ b/packages/twenty-cli/src/local/check-local-health.ts
@@ -0,0 +1,19 @@
+export const checkLocalHealth = async ({
+ port,
+ signal,
+}: {
+ port: number;
+ signal: AbortSignal;
+}) => {
+ try {
+ const response = await fetch(`http://127.0.0.1:${port}/healthz`, {
+ signal: AbortSignal.any([signal, AbortSignal.timeout(3000)]),
+ redirect: 'error',
+ });
+ await response.body?.cancel();
+ return response.ok;
+ } catch {
+ signal.throwIfAborted();
+ return false;
+ }
+};
diff --git a/packages/twenty-cli/src/local/check-local-runtime.ts b/packages/twenty-cli/src/local/check-local-runtime.ts
new file mode 100644
index 00000000000..81a8c13556f
--- /dev/null
+++ b/packages/twenty-cli/src/local/check-local-runtime.ts
@@ -0,0 +1,29 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { runDocker } from '@/local/run-docker';
+import { CliError } from '@/output/cli-error';
+
+export const checkLocalRuntime = async (signal: AbortSignal) => {
+ let endpoint = process.env.DOCKER_HOST;
+ if (
+ !isNonEmptyString(endpoint) ||
+ isNonEmptyString(process.env.DOCKER_CONTEXT)
+ ) {
+ endpoint = (
+ await runDocker({
+ args: ['context', 'inspect', '--format', '{{.Endpoints.docker.Host}}'],
+ signal,
+ })
+ ).trim();
+ }
+
+ if (!endpoint.startsWith('unix://') && !endpoint.startsWith('npipe://')) {
+ throw new CliError({
+ code: 'INVALID_CONFIG',
+ message: 'Local environments require a local Docker socket.',
+ hint: 'Select a local Docker context and unset any remote DOCKER_HOST override.',
+ });
+ }
+
+ await runDocker({ args: ['info', '--format', '{{.ServerVersion}}'], signal });
+};
diff --git a/packages/twenty-cli/src/local/create-local-container.ts b/packages/twenty-cli/src/local/create-local-container.ts
new file mode 100644
index 00000000000..d6bd87f0fce
--- /dev/null
+++ b/packages/twenty-cli/src/local/create-local-container.ts
@@ -0,0 +1,38 @@
+import { runDocker } from '@/local/run-docker';
+import { type LocalEnvironment } from '@/local/types/local-environment.type';
+
+export const createLocalContainer = async ({
+ environment,
+ image,
+ port,
+ signal,
+}: {
+ environment: Pick<
+ LocalEnvironment,
+ 'name' | 'volumes' | 'environmentVariables'
+ >;
+ image: string;
+ port: number;
+ signal: AbortSignal;
+}) =>
+ runDocker({
+ args: [
+ 'run',
+ '--detach',
+ '--name',
+ environment.name,
+ '--publish',
+ `127.0.0.1:${port}:${port}`,
+ '--env',
+ `NODE_PORT=${port}`,
+ '--env',
+ `SERVER_URL=http://localhost:${port}`,
+ ...environment.environmentVariables.flatMap((value) => ['--env', value]),
+ ...Object.entries(environment.volumes).flatMap(([destination, name]) => [
+ '--volume',
+ `${name}:${destination}`,
+ ]),
+ image,
+ ],
+ signal,
+ });
diff --git a/packages/twenty-cli/src/local/get-local-engine-range.ts b/packages/twenty-cli/src/local/get-local-engine-range.ts
new file mode 100644
index 00000000000..244fe72c740
--- /dev/null
+++ b/packages/twenty-cli/src/local/get-local-engine-range.ts
@@ -0,0 +1,9 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { getEngineVersionRange } from '@/app/manifest/get-engine-version-range';
+import { listAncestorDirectories } from '@/app/project/list-ancestor-directories';
+
+export const getLocalEngineRange = () =>
+ listAncestorDirectories(process.cwd())
+ .map(getEngineVersionRange)
+ .find(isDefined);
diff --git a/packages/twenty-cli/src/local/get-local-environment.ts b/packages/twenty-cli/src/local/get-local-environment.ts
new file mode 100644
index 00000000000..95c5083ded4
--- /dev/null
+++ b/packages/twenty-cli/src/local/get-local-environment.ts
@@ -0,0 +1,24 @@
+import { type LocalEnvironment } from '@/local/types/local-environment.type';
+
+export const LOCAL_IMAGE_REPOSITORY = 'twentycrm/twenty-app-dev';
+
+const LOCAL_TEST_ENVIRONMENT_VARIABLES = [
+ 'MARKETPLACE_CATALOG_SYNC_CRON_ENABLED=false',
+ 'API_RATE_LIMITING_SHORT_LIMIT=100000',
+ 'API_RATE_LIMITING_LONG_LIMIT=100000',
+];
+
+export const getLocalEnvironment = (isTest: boolean): LocalEnvironment => {
+ const name = isTest ? 'twenty-app-dev-test' : 'twenty-app-dev';
+
+ return {
+ name,
+ port: isTest ? 2021 : 2020,
+ environmentVariables: isTest ? [...LOCAL_TEST_ENVIRONMENT_VARIABLES] : [],
+ volumes: {
+ '/data/postgres': `${name}-data`,
+ '/data/clickhouse': `${name}-clickhouse`,
+ '/app/packages/twenty-server/.local-storage': `${name}-storage`,
+ },
+ };
+};
diff --git a/packages/twenty-cli/src/local/get-local-image.ts b/packages/twenty-cli/src/local/get-local-image.ts
new file mode 100644
index 00000000000..ef133b42e5c
--- /dev/null
+++ b/packages/twenty-cli/src/local/get-local-image.ts
@@ -0,0 +1,20 @@
+import valid from 'semver/functions/valid';
+import { isDefined } from 'twenty-shared/utils';
+
+import { LOCAL_IMAGE_REPOSITORY } from '@/local/get-local-environment';
+import { CliError } from '@/output/cli-error';
+
+export const getLocalImage = (version: string) => {
+ const normalized = valid(version);
+ const tag = isDefined(normalized) ? `v${normalized}` : version;
+
+ if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$/.test(tag)) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ message:
+ 'Use a server version such as 2.53.1 or a valid image tag such as latest.',
+ });
+ }
+
+ return `${LOCAL_IMAGE_REPOSITORY}:${tag}`;
+};
diff --git a/packages/twenty-cli/src/local/get-local-status.ts b/packages/twenty-cli/src/local/get-local-status.ts
new file mode 100644
index 00000000000..3aa8c1c6d92
--- /dev/null
+++ b/packages/twenty-cli/src/local/get-local-status.ts
@@ -0,0 +1,31 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { checkLocalHealth } from '@/local/check-local-health';
+import {
+ type LocalContainer,
+ type LocalEnvironment,
+} from '@/local/types/local-environment.type';
+
+export const getLocalStatus = async ({
+ environment,
+ container,
+ signal,
+}: {
+ environment: Pick<LocalEnvironment, 'name' | 'port'>;
+ container: Pick<LocalContainer, 'port' | 'image' | 'isRunning'> | undefined;
+ signal: AbortSignal;
+}) => {
+ const data = {
+ name: environment.name,
+ url: `http://localhost:${container?.port ?? environment.port}`,
+ image: container?.image ?? null,
+ };
+ if (!isDefined(container)) {
+ return { ...data, status: 'not-created' };
+ }
+ if (!container.isRunning) {
+ return { ...data, status: 'stopped' };
+ }
+ const isHealthy = await checkLocalHealth({ port: container.port, signal });
+ return { ...data, status: isHealthy ? 'healthy' : 'starting' };
+};
diff --git a/packages/twenty-cli/src/local/read-local-container-ports.ts b/packages/twenty-cli/src/local/read-local-container-ports.ts
new file mode 100644
index 00000000000..1987fb82b54
--- /dev/null
+++ b/packages/twenty-cli/src/local/read-local-container-ports.ts
@@ -0,0 +1,50 @@
+import { isArray, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+
+export const readLocalContainerPorts = ({
+ containerName,
+ portBindings,
+}: {
+ containerName: string;
+ portBindings: Record<string, unknown>;
+}) => {
+ const tcpPorts = Object.entries(portBindings).filter(([key]) =>
+ key.endsWith('/tcp'),
+ );
+ if (tcpPorts.length !== 1) {
+ throw new CliError({
+ code: 'CONFLICT',
+ message: `${containerName} must publish exactly one TCP port.`,
+ });
+ }
+
+ const [containerPortKey, bindings] = tcpPorts[0];
+ if (
+ !isArray(bindings) ||
+ bindings.length !== 1 ||
+ !isPlainObject(bindings[0]) ||
+ !isString(bindings[0].HostPort)
+ ) {
+ throw new CliError({
+ code: 'CONFLICT',
+ message: `${containerName} must bind its TCP port to exactly one host port.`,
+ });
+ }
+
+ const port = Number(bindings[0].HostPort);
+ const containerPort = Number(containerPortKey.split('/')[0]);
+ if (
+ ![port, containerPort].every(
+ (value) => Number.isInteger(value) && value >= 1 && value <= 65535,
+ )
+ ) {
+ throw new CliError({
+ code: 'CONFLICT',
+ message: `${containerName} has a port outside the range 1 to 65535.`,
+ });
+ }
+
+ return { port, containerPort };
+};
diff --git a/packages/twenty-cli/src/local/read-local-container.ts b/packages/twenty-cli/src/local/read-local-container.ts
new file mode 100644
index 00000000000..6008fd3373c
--- /dev/null
+++ b/packages/twenty-cli/src/local/read-local-container.ts
@@ -0,0 +1,86 @@
+import { isBoolean, isNonEmptyString, isString } from '@sniptt/guards';
+import { isPlainObject } from 'twenty-shared/utils';
+
+import { LOCAL_IMAGE_REPOSITORY } from '@/local/get-local-environment';
+import { readLocalContainerPorts } from '@/local/read-local-container-ports';
+import { runDocker } from '@/local/run-docker';
+import {
+ type LocalContainer,
+ type LocalEnvironment,
+} from '@/local/types/local-environment.type';
+import { CliError } from '@/output/cli-error';
+
+export const readLocalContainer = async ({
+ environment,
+ signal,
+}: {
+ environment: Pick<LocalEnvironment, 'name'>;
+ signal: AbortSignal;
+}): Promise<LocalContainer | undefined> => {
+ const id = (
+ await runDocker({
+ args: [
+ 'container',
+ 'ls',
+ '--all',
+ '--filter',
+ `name=^/${environment.name}$`,
+ '--format',
+ '{{.ID}}',
+ ],
+ signal,
+ })
+ ).trim();
+
+ if (!isNonEmptyString(id)) {
+ return undefined;
+ }
+
+ const value: unknown = JSON.parse(
+ await runDocker({
+ args: ['container', 'inspect', '--format', '{{json .}}', id],
+ signal,
+ }),
+ );
+
+ if (
+ !isPlainObject(value) ||
+ !isString(value.Id) ||
+ !isPlainObject(value.Config) ||
+ !isString(value.Config.Image) ||
+ !isPlainObject(value.State) ||
+ !isBoolean(value.State.Running) ||
+ !isPlainObject(value.HostConfig) ||
+ !isPlainObject(value.HostConfig.PortBindings)
+ ) {
+ throw new CliError({
+ code: 'INVALID_RESPONSE',
+ message: 'Docker returned an invalid container description.',
+ });
+ }
+
+ const image = value.Config.Image;
+
+ if (
+ !image.startsWith(`${LOCAL_IMAGE_REPOSITORY}:`) &&
+ !image.startsWith(`${LOCAL_IMAGE_REPOSITORY}@`)
+ ) {
+ throw new CliError({
+ code: 'CONFLICT',
+ message: `${environment.name} belongs to another image.`,
+ hint: 'Rename that container before using twenty local.',
+ });
+ }
+
+ const { port } = readLocalContainerPorts({
+ containerName: environment.name,
+ portBindings: value.HostConfig.PortBindings,
+ });
+
+ return {
+ id: value.Id,
+ image,
+ isRunning: value.State.Running,
+ port,
+ };
+};
diff --git a/packages/twenty-cli/src/local/read-local-integer.ts b/packages/twenty-cli/src/local/read-local-integer.ts
new file mode 100644
index 00000000000..ed9b799610d
--- /dev/null
+++ b/packages/twenty-cli/src/local/read-local-integer.ts
@@ -0,0 +1,26 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { EXIT_CODE } from '@/output/constants/exit-code.constant';
+
+export const readLocalInteger = ({
+ value,
+ name,
+ maximum,
+}: {
+ value: string | undefined;
+ name: string;
+ maximum: number;
+}) => {
+ if (!isDefined(value)) {
+ return undefined;
+ }
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > maximum) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ exitCode: EXIT_CODE.USAGE,
+ message: `${name} must be an integer between 1 and ${maximum}.`,
+ });
+ }
+ return Number(value);
+};
diff --git a/packages/twenty-cli/src/local/read-local-options.ts b/packages/twenty-cli/src/local/read-local-options.ts
new file mode 100644
index 00000000000..68aefe41a76
--- /dev/null
+++ b/packages/twenty-cli/src/local/read-local-options.ts
@@ -0,0 +1,15 @@
+import {
+ readBooleanOption,
+ readStringOption,
+} from '@/catalog/read-command-values';
+import { getLocalEnvironment } from '@/local/get-local-environment';
+import { readLocalInteger } from '@/local/read-local-integer';
+
+export const readLocalOptions = (options: Record<string, unknown>) => ({
+ environment: getLocalEnvironment(readBooleanOption(options, 'test')),
+ port: readLocalInteger({
+ value: readStringOption(options, 'port'),
+ name: '--port',
+ maximum: 65535,
+ }),
+});
diff --git a/packages/twenty-cli/src/local/resolve-local-image.ts b/packages/twenty-cli/src/local/resolve-local-image.ts
new file mode 100644
index 00000000000..af1554ae30f
--- /dev/null
+++ b/packages/twenty-cli/src/local/resolve-local-image.ts
@@ -0,0 +1,86 @@
+import { isArray, isString } from '@sniptt/guards';
+import maxSatisfying from 'semver/ranges/max-satisfying';
+import valid from 'semver/functions/valid';
+import validRange from 'semver/ranges/valid';
+import { isDefined, isPlainObject } from 'twenty-shared/utils';
+
+import { getLocalEngineRange } from '@/local/get-local-engine-range';
+import { getLocalImage } from '@/local/get-local-image';
+import { LOCAL_IMAGE_REPOSITORY } from '@/local/get-local-environment';
+import { CliError } from '@/output/cli-error';
+import { fetchWithProxy } from '@/transport/fetch-with-proxy';
+import { readBoundedBody } from '@/transport/read-bounded-body';
+
+export const resolveLocalImage = async ({
+ version,
+ signal,
+}: {
+ version: string | undefined;
+ signal: AbortSignal;
+}) => {
+ if (isDefined(version)) {
+ return getLocalImage(version);
+ }
+
+ const range = getLocalEngineRange();
+
+ if (!isDefined(range)) {
+ return getLocalImage('latest');
+ }
+
+ if (!validRange(range)) {
+ throw new CliError({
+ code: 'INVALID_INPUT',
+ message: 'The app engines.twenty range is invalid.',
+ hint: 'Fix engines.twenty or pass a version explicitly.',
+ });
+ }
+
+ const versions: string[] = [];
+ const lookupSignal = AbortSignal.any([signal, AbortSignal.timeout(15_000)]);
+
+ try {
+ for (let page = 1; page <= 20; page++) {
+ const response = await fetchWithProxy(
+ `https://hub.docker.com/v2/repositories/${LOCAL_IMAGE_REPOSITORY}/tags?page_size=100&page=${page}`,
+ { signal: lookupSignal },
+ );
+ if (!response.ok) {
+ await response.body?.cancel();
+ throw new Error(
+ `Image registry request failed (HTTP ${response.status})`,
+ );
+ }
+ const body: unknown = JSON.parse(
+ Buffer.from(
+ await readBoundedBody(response, 2 * 1024 * 1024),
+ ).toString(),
+ );
+ if (!isPlainObject(body) || !isArray(body.results)) {
+ throw new Error('Invalid image registry response');
+ }
+ for (const entry of body.results) {
+ if (isPlainObject(entry) && isString(entry.name) && valid(entry.name)) {
+ versions.push(entry.name);
+ }
+ }
+ if (!isDefined(body.next)) {
+ const match = maxSatisfying(versions, range);
+ if (isDefined(match)) {
+ return getLocalImage(match);
+ }
+ throw new Error('No published image matches engines.twenty');
+ }
+ }
+ throw new Error('Image registry listing exceeded 2000 tags');
+ } catch (error) {
+ signal.throwIfAborted();
+ const reason = error instanceof Error ? error.message : String(error);
+ throw new CliError({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: `Could not select a published Twenty image matching ${range}: ${reason}`,
+ hint: 'Check the range and your connection, or pass a version explicitly.',
+ cause: error,
+ });
+ }
+};
diff --git a/packages/twenty-cli/src/local/run-docker.ts b/packages/twenty-cli/src/local/run-docker.ts
new file mode 100644
index 00000000000..05c66bbf2c1
--- /dev/null
+++ b/packages/twenty-cli/src/local/run-docker.ts
@@ -0,0 +1,73 @@
+import execa from 'execa';
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+
+import { CliError } from '@/output/cli-error';
+import { createCancelledError } from '@/output/create-cancelled-error';
+
+export const runDocker = async ({
+ args,
+ signal,
+ onOutput,
+}: {
+ args: string[];
+ signal: AbortSignal;
+ onOutput?: (message: string) => Promise<void>;
+}) => {
+ signal.throwIfAborted();
+
+ const subprocess = execa('docker', args, {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ all: true,
+ buffer: !onOutput,
+ reject: false,
+ maxBuffer: 4 * 1024 * 1024,
+ });
+ subprocess.stdout?.setEncoding('utf8');
+ subprocess.stderr?.setEncoding('utf8');
+ subprocess.all?.setEncoding('utf8');
+ const cancel = () =>
+ subprocess.kill('SIGTERM', { forceKillAfterTimeout: 1000 });
+
+ signal.addEventListener('abort', cancel, { once: true });
+ if (signal.aborted) {
+ cancel();
+ }
+
+ try {
+ if (isDefined(onOutput) && isDefined(subprocess.all)) {
+ for await (const chunk of subprocess.all) {
+ await onOutput(String(chunk));
+ }
+ }
+
+ const result = await subprocess;
+
+ signal.throwIfAborted();
+
+ if (result.failed) {
+ throw new CliError({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: isNonEmptyString(result.stderr?.trim())
+ ? `docker ${args[0]} failed: ${result.stderr.trim().slice(-4096)}`
+ : `docker ${args[0]} failed.`,
+ hint: 'Check Docker is installed and running, then retry.',
+ details: {
+ exitCode: result.exitCode,
+ stderr: result.stderr?.slice(-16384) ?? '',
+ },
+ });
+ }
+
+ return result.stdout ?? '';
+ } catch (error) {
+ cancel();
+ await subprocess.catch(() => undefined);
+ if (signal.aborted) {
+ throw createCancelledError();
+ }
+ throw error;
+ } finally {
+ signal.removeEventListener('abort', cancel);
+ }
+};
diff --git a/packages/twenty-cli/src/local/types/local-environment.type.ts b/packages/twenty-cli/src/local/types/local-environment.type.ts
new file mode 100644
index 00000000000..fcd56c082c7
--- /dev/null
+++ b/packages/twenty-cli/src/local/types/local-environment.type.ts
@@ -0,0 +1,13 @@
+export type LocalEnvironment = {
+ name: string;
+ port: number;
+ volumes: Record<string, string>;
+ environmentVariables: string[];
+};
+
+export type LocalContainer = {
+ id: string;
+ image: string;
+ isRunning: boolean;
+ port: number;
+};
diff --git a/packages/twenty-cli/src/local/wait-for-local-environment.ts b/packages/twenty-cli/src/local/wait-for-local-environment.ts
new file mode 100644
index 00000000000..44f798ab8f9
--- /dev/null
+++ b/packages/twenty-cli/src/local/wait-for-local-environment.ts
@@ -0,0 +1,28 @@
+import { waitForLocalHealth } from '@/local/wait-for-local-health';
+import { getLocalStatus } from '@/local/get-local-status';
+import { readLocalContainer } from '@/local/read-local-container';
+import { type LocalEnvironment } from '@/local/types/local-environment.type';
+import { CliError } from '@/output/cli-error';
+
+export const waitForLocalEnvironment = async ({
+ environment,
+ signal,
+}: {
+ environment: Pick<LocalEnvironment, 'name' | 'port'>;
+ signal: AbortSignal;
+}) => {
+ await waitForLocalHealth({ port: environment.port, signal });
+ const status = await getLocalStatus({
+ environment,
+ container: await readLocalContainer({ environment, signal }),
+ signal,
+ });
+ if (status.status !== 'healthy') {
+ throw new CliError({
+ code: 'LOCAL_ENVIRONMENT_FAILED',
+ message: 'The local environment stopped responding during startup.',
+ hint: 'Check twenty local logs (add --test for the test instance). Data volumes are preserved.',
+ });
+ }
+ return status;
+};
diff --git a/packages/twenty-cli/src/local/wait-for-local-health.ts b/packages/twenty-cli/src/local/wait-for-local-health.ts
new file mode 100644
index 00000000000..1c00c211a92
--- /dev/null
+++ b/packages/twenty-cli/src/local/wait-for-local-health.ts
@@ -0,0 +1,28 @@
+import { setTimeout as delay } from 'node:timers/promises';
+
+import { checkLocalHealth } from '@/local/check-local-health';
+import { CliError } from '@/output/cli-error';
+
+export const waitForLocalHealth = async ({
+ port,
+ signal,
+}: {
+ port: number;
+ signal: AbortSignal;
+}) => {
+ const deadline = Date.now() + 300_000;
+
+ while (Date.now() < deadline) {
+ if (await checkLocalHealth({ port, signal })) {
+ return;
+ }
+ await delay(1000, undefined, { signal });
+ }
+
+ throw new CliError({
+ code: 'TIMEOUT',
+ message:
+ 'The local environment did not become healthy within five minutes.',
+ hint: 'The container was left in place. Run twenty local logs (add --test for the test instance).',
+ });
+};
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 a8bf2d44bf2..6669b54c812 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
@@ -34,6 +34,7 @@ export type CliErrorCode =
| 'INVALID_REMOTE_NAME'
| 'INVALID_REQUEST_PATH'
| 'INVALID_RESPONSE'
+ | 'LOCAL_ENVIRONMENT_FAILED'
| 'NETWORK_ERROR'
| 'NODE_VERSION_UNSUPPORTED'
| 'NOT_FOUND'
diff --git a/packages/twenty-cli/src/program/run-command.ts b/packages/twenty-cli/src/program/run-command.ts
index d1687b101de..fbb607f282e 100644
--- a/packages/twenty-cli/src/program/run-command.ts
+++ b/packages/twenty-cli/src/program/run-command.ts
@@ -43,7 +43,7 @@ export const runCommand = async ({
const abortOnInterrupt = () => abortController.abort();
let target: ResolvedTarget | undefined;
- process.once('SIGINT', abortOnInterrupt);
+ process.on('SIGINT', abortOnInterrupt);
try {
assertOutputModeSupported(definition, outputMode);
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx
index 579d6e9db7e..072ba0798ce 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/local-server.mdx
@@ -1,38 +1,78 @@
---
-title: Local Server
-description: Connect the standalone CLI to a local Twenty server.
+title: Local Environment
+description: Run the full Twenty development environment with the CLI.
---
import { PageBanner } from "/snippets/page-banner.mdx"
-## Setup
+## Start Twenty locally
-The standalone CLI connects to a running Twenty server. It does not start or manage Docker containers.
-
-Use the [self-hosting guide](/developers/self-host/self-host) to run Twenty with Docker. In a Twenty repository checkout, the existing development environment also works:
+Install and start Docker, then run:
```bash
-bash packages/twenty-utils/setup-dev-env.sh
-yarn start
+twenty local start
+twenty auth login --url http://localhost:2020 --name local
```
-Then authenticate against the server URL for your workspace:
+`local start` runs the web UI, API, worker and databases. It works outside an app
+folder, waits for the environment to be ready, and prints its URL. Sign-in is a
+separate step. To install your app afterward, run `twenty app apply --create
+--remote local` from its directory.
+
+For a new instance, pass a version explicitly or let the CLI select the highest
+published version matching your app's `engines.twenty`. Outside an app with that
+setting, it uses `latest`. Existing instances keep their version and data.
```bash
-twenty auth login --url http://localhost:3000 --name local
-twenty app apply --create --remote local
+twenty local start 2.53.1
+twenty local status
+twenty local logs
+twenty local logs --lines 100 --no-follow
+twenty local stop
```
-Use the actual URL and port of your server. For subdomain workspaces, use the workspace's hostname.
+New instances listen only on loopback, on port `2020`. Use `--port <port>` when
+creating an instance to choose another port. Use a local Docker socket context;
+remote Docker engines are not supported by these commands.
+
+`stop` keeps the container and all data.
## Integration tests
-Use a separate disposable server or workspace. Integration test setup installs an app and teardown uninstalls it. Set `TWENTY_API_URL` and `TWENTY_API_KEY` to that test instance before running `yarn test`.
+Use the separate test instance, default port `2021`:
+
+```bash
+twenty local start --test
+twenty local status --test
+TWENTY_API_URL=http://localhost:2021 yarn test
+```
+
+Set `TWENTY_API_KEY` to a key for that instance. Integration tests install and
+uninstall an app, so keep them separate from your development workspace.
+Pass `--test` to logs or stop when managing this instance.
+
+The generated CI workflow provisions an isolated instance through
+`twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test@main` and installs the
+standalone CLI separately.
+
+## Other local setups
+
+For a Twenty source checkout, the existing development environment also works:
+
+```bash
+bash packages/twenty-utils/setup-dev-env.sh
+yarn start
+twenty auth login --url http://localhost:3000 --name local
+```
-The generated CI workflow provisions an isolated instance through `twentyhq/twenty/.github/actions/spawn-twenty-app-dev-test@main` and installs the standalone CLI separately.
+Use the actual URL and port of your server. For subdomain workspaces, use the
+workspace's hostname. For production deployment, follow the
+[self-hosting guide](/developers/self-host/self-host).
## Project dependencies
-Install `twenty-sdk` and `twenty-client-sdk` as project dependencies. Install the `twenty` CLI globally, then run `twenty app typecheck`, `twenty app build`, and `twenty app apply` from the app directory.
+Install `twenty-sdk` and `twenty-client-sdk` as project dependencies. Install the
+`twenty` CLI globally, then run `twenty app typecheck`, `twenty app build`, and
+`twenty app apply` from the app directory.
<PageBanner illustration="dev-self-host" />
diff --git a/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx b/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
index 0c53b42837c..f99188a18a6 100644
--- a/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
+++ b/packages/twenty-docs/developers/extend/apps/getting-started/troubleshooting.mdx
@@ -7,7 +7,7 @@ import { PageBanner } from "/snippets/page-banner.mdx"
## Common issues
-- **Local server errors**, check your Docker or repository development environment. The standalone CLI does not manage containers.
+- **Local environment errors**, check `twenty local status` and `twenty local logs --no-follow`. Docker must be installed and running with a local socket context. Add `--test` for the test instance. A failed start keeps its container and data for diagnosis.
- **Wrong Node version** — Need 24.5+ or 26.5+ (`engines.node: ^24.5.0 || ^26.5.1`). Check with `node -v`.
- **Yarn 4 missing** — Run `corepack enable` (on Node 26, first `npm install -g corepack`).
- **Dependencies broken** — `rm -rf node_modules && yarn install`.
diff --git a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
index 7705a888410..2e9f52a072e 100644
--- a/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
+++ b/packages/twenty-docs/developers/extend/apps/operations/cli.mdx
@@ -33,6 +33,7 @@ The examples below use `twenty`. Prefix them with `npx twenty@latest` if you did
| `api` | Send raw REST or GraphQL requests |
| `open` | Open the workspace in your browser |
| `app` | Create, build, sync, debug and uninstall apps |
+| `local` | Start, inspect and stop a local development environment |
| `doctor` | Diagnose the CLI, app SDK and workspace connection |
Every command that talks to a workspace accepts `--remote <name>` to target a saved connection other than the default one, and `--json` for structured output.
@@ -46,7 +47,7 @@ twenty auth login --url https://acme.twenty.com --use
twenty auth status
```
-Use your workspace's address, or the server's address for a local setup: `http://localhost:2020` for the [local Docker server](/developers/extend/apps/getting-started/local-server), `http://localhost:3000` for a source checkout. You can copy the exact command from **Settings > Developers > CLI**. Browser sign-in needs Twenty 2.42 or later.
+Use your workspace's address, or the server's address for a local setup: `http://localhost:2020` for the [local development environment](/developers/extend/apps/getting-started/local-server), `http://localhost:3000` for a source checkout. You can copy the exact command from **Settings > Developers > CLI**. Browser sign-in needs Twenty 2.42 or later.
Keep several connections by naming them: