diff --git a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx index 4aed1fa7a96..60dc5eb22cb 100644 --- a/apps/docs/content/docs/platform/enterprise/self-hosted.mdx +++ b/apps/docs/content/docs/platform/enterprise/self-hosted.mdx @@ -19,7 +19,7 @@ Set the server flag, then restart the application: ENTERPRISE_ENABLED=true ``` -The server flag controls access and everything the browser shows, including SSO on the login page and the Function block's **Sandbox** selector: the browser reads the server's resolved settings, so there is no `NEXT_PUBLIC_` variable to set. Browser variables left over from older releases do nothing; on a Compose install or source checkout, `bunx sim-setup doctor` reports them. See [Verify your install](/platform/self-hosting/verify). +The server flag controls access and everything the browser shows, including SSO on the login page and the Function block's **Sandbox** selector: the browser reads the server's resolved settings, so there is no `NEXT_PUBLIC_` variable to set. Browser variables left over from older releases do nothing; on a Compose install or source checkout, `npx sim-setup doctor` reports them. See [Verify your install](/platform/self-hosting/verify). Individual flags override the master switch. For example, to enable the suite with data drains disabled: @@ -268,7 +268,7 @@ JavaScript without `import`, `require`, a selected sandbox, or a sandbox file-pa | Symptom | Check | | --- | --- | | A settings section is missing | Check its server flag and restart the app after changing environment variables. These values load at boot; a rebuild is not needed. | -| The login page has no SSO option, or Function has no Sandbox selector | Check `SSO_ENABLED` (or `ENTERPRISE_ENABLED`) and Sandbox readiness, then restart the app. Run `bunx sim-setup doctor` to check Sandbox readiness. | +| The login page has no SSO option, or Function has no Sandbox selector | Check `SSO_ENABLED` (or `ENTERPRISE_ENABLED`) and Sandbox readiness, then restart the app. Run `npx sim-setup doctor` to check Sandbox readiness. | | **Settings → Sandboxes** shows an upgrade notice | Check Sandbox entitlement, provider credentials, and the immutable Function base. | | An enabled feature has no effect in a workspace | Confirm that the workspace belongs to an organization. Use the backfill or workspace move procedure if needed. | | Retention deletes nothing | Check `DATA_RETENTION_ENABLED`, explicit windows, scheduler requests, and `CRON_SECRET`. | diff --git a/apps/docs/content/docs/platform/self-hosting/architecture.mdx b/apps/docs/content/docs/platform/self-hosting/architecture.mdx index ba603792f53..5f4265ec939 100644 --- a/apps/docs/content/docs/platform/self-hosting/architecture.mdx +++ b/apps/docs/content/docs/platform/self-hosting/architecture.mdx @@ -74,7 +74,7 @@ The chart can also render the optional `copilot` service, its separate PostgreSQ | **Secrets** | `ENCRYPTION_KEY`, `API_ENCRYPTION_KEY`, `BETTER_AUTH_SECRET`, `INTERNAL_API_SECRET`, `CRON_SECRET` | Secret manager and separate recovery copies | - Neither the production Compose file nor the Helm chart mounts a volume for local uploads. Without configured cloud storage or your own volume, recreating the app container loses those files. Local files are also invisible to other replicas. Configure [object storage](/platform/self-hosting/object-storage) before storing durable files or scaling. + Without object storage, uploads are local: Compose keeps them in the `sim_uploads` volume on one host, and the Helm chart keeps them on each pod, lost when it is recreated. Configure [object storage](/platform/self-hosting/object-storage) before storing durable files or scaling. diff --git a/apps/docs/content/docs/platform/self-hosting/desktop.mdx b/apps/docs/content/docs/platform/self-hosting/desktop.mdx index a05697e60b3..bdda0b4ef47 100644 --- a/apps/docs/content/docs/platform/self-hosting/desktop.mdx +++ b/apps/docs/content/docs/platform/self-hosting/desktop.mdx @@ -30,13 +30,13 @@ Install the official Sim desktop app and connect it to your deployment. You do n From your installation directory: ```bash -bunx sim-setup desktop +npx sim-setup desktop ``` The command reads Compose/Helm configuration, resolves the installer, and prints the download link and server URL. It offers to open the installer in your browser. Use `--no-open` to skip that prompt, or supply the public origin directly: ```bash -bunx sim-setup desktop --url https://sim.example.com --no-open +npx sim-setup desktop --url https://sim.example.com --no-open ``` `--url` skips discovery. Without the CLI, open `https:///api/desktop/update/download` in a browser. diff --git a/apps/docs/content/docs/platform/self-hosting/docker.mdx b/apps/docs/content/docs/platform/self-hosting/docker.mdx index 8d8b65ac690..f8963d17e4c 100644 --- a/apps/docs/content/docs/platform/self-hosting/docker.mdx +++ b/apps/docs/content/docs/platform/self-hosting/docker.mdx @@ -11,17 +11,17 @@ Use the production Compose stack for a single-node installation. It starts the a - Docker Engine or Docker Desktop, running. - Docker Compose 2.24.0 or later. The file uses optional `env_file` entries introduced in that version. -- Bun for `bunx`, and Node.js 20 or later for the published `sim-setup` executable. +- Node.js 20 or later, which provides `npx` for the `sim-setup` CLI. - Available host ports 3000 and 3002, with enough resources for your workload. See [resource examples](/platform/self-hosting#requirements). - A public domain and TLS proxy for remote access. ## Quick start ```bash -bunx sim-setup +npx sim-setup ``` -The wizard creates `./sim` with a generated `.env` and production Compose file, then starts published container images. Pass `--dir ` for another directory. Open [http://localhost:3000](http://localhost:3000). +The wizard creates `./sim` with a generated `.env` and production Compose file, then starts published container images. Pass `--dir ` for another directory, and `--url https://sim.yourdomain.com` to set the public URL (Custom setup also asks for it). Open [http://localhost:3000](http://localhost:3000), or your public URL. `bunx sim-setup` works too if you use Bun. For a manual installation, obtain the Compose file from a source checkout: @@ -69,11 +69,20 @@ Set `CRON_SECRET` for scheduled work. Without it, the cron service prints instru ### 2. Configure durable uploads - - The production Compose file persists PostgreSQL but does not mount `/app/apps/sim/uploads`. Recreating the app container loses uploads stored there. Configure object storage or a persistent mount before saving files you need to retain. - +Without object storage, the app stores uploads in the `sim_uploads` volume, so they survive container recreation and updates. It stays on this host and needs its own backup. A one-shot `uploads-init` service makes it writable by the app user. + +Follow [Object storage](/platform/self-hosting/object-storage) for AWS S3, Azure Blob, or Google Cloud Storage. + +#### Existing installs: keep uploads from before the volume -Follow [Object storage](/platform/self-hosting/object-storage) for AWS S3, Azure Blob, Google Cloud Storage, or local-volume configuration. Local disk is not shared across app replicas. +If your install predates the `sim_uploads` volume, uploads live inside the app container and recreating it discards them. Copy them out before switching to the new Compose file or running `npx sim-setup update`, then copy them in: + +```bash +docker compose -f docker-compose.prod.yml cp simstudio:/app/apps/sim/uploads ./uploads-backup +# switch to the new docker-compose.prod.yml (or run npx sim-setup update), then: +docker compose -f docker-compose.prod.yml cp ./uploads-backup/. simstudio:/app/apps/sim/uploads +docker compose -f docker-compose.prod.yml exec -u 0 simstudio chown -R nextjs:nodejs /app/apps/sim/uploads +``` ### 3. Start and verify services @@ -92,8 +101,9 @@ curl -fsS http://localhost:3000/api/health | `redis` | Not published | Required. Rate limits, shared coordination, pub/sub, and caches. | | `cron` | None | Calls background job endpoints. | | `migrations` | None | Applies migrations once, then exits. | +| `uploads-init` | None | Hands the uploads volume to the app user once, then exits. | -Expect five services running and `migrations` exited successfully. The migrator has no healthcheck because it is a one-shot job. +Expect five services running, and `migrations` and `uploads-init` exited successfully. The migrator has no healthcheck because it is a one-shot job. ```bash docker compose -f docker-compose.prod.yml logs -f cron @@ -123,6 +133,8 @@ sim.yourdomain.com { Route `/socket.io` to realtime on 3002 and other requests to the app on 3000. The 250 MB decimal Caddy limit clears the configured 220 MiB deployed-chat cap, but the app's current Next.js proxy buffer still limits matching requests to 10 MiB. See [Request size limits](/platform/self-hosting/networking#request-size-limits) before increasing payload sizes. `flush_interval -1` explicitly disables response buffering; Caddy already flushes SSE immediately. It also keeps the upstream request running if the client disconnects. See [Caddy streaming behavior](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy#streaming). +When the proxy runs on the same host, set `SIM_APP_PUBLISH=127.0.0.1:3000` and `SIM_REALTIME_PUBLISH=127.0.0.1:3002` in `.env` so the app and realtime are reachable only through it. Keep the ports; `sim-setup` checks 3000 and 3002. + This example assumes Caddy runs on the Docker host. A containerized proxy needs reachable Compose service addresses instead of its own `localhost`. For Nginx, Traefik, cloud load balancers, or separate socket hosts, see [Networking](/platform/self-hosting/networking). ## Ollama @@ -135,7 +147,7 @@ For production, keep this Compose stack and point `OLLAMA_URL` at an Ollama serv OLLAMA_URL=http://host.docker.internal:11434 ``` -Production Compose maps `host.docker.internal` to the host gateway, including on Linux. You can instead use a reachable host IP. The Ollama server must listen on an interface reachable from the container. +Production Compose maps `host.docker.internal` to the host gateway, including on Linux. You can instead use a reachable host IP. The Ollama server must listen on an interface reachable from the container. On Linux, bind it to the Docker bridge address that `host.docker.internal` resolves to, usually `OLLAMA_HOST=172.17.0.1:11434` (check with `ip -4 addr show docker0`). Ollama's API has no authentication, so listen on `0.0.0.0` only behind a firewall that blocks port 11434 from outside the host. ```bash docker compose -f docker-compose.prod.yml up -d @@ -225,11 +237,11 @@ docker compose -f "$COMPOSE_FILE" up -d --force-recreate simstudio ## The `sim-setup` CLI -Invoke commands as `bunx sim-setup ` unless the package is installed globally. Run `doctor`, `config`, and the wizard from the configuration directory. Lifecycle commands discover running production/local Compose stacks, source checkouts, and Helm releases. A stack started with the Ollama overlay is managed as a production install, through `docker-compose.prod.yml` alone: the CLI acts on the Sim services and leaves the Ollama container untouched. +Invoke commands as `npx sim-setup ` unless the package is installed globally. Run `doctor`, `config`, and the wizard from the configuration directory. Lifecycle commands discover running production/local Compose stacks, source checkouts, and Helm releases. Compose commands apply every file the stack was started with, such as the Ollama overlay. For a stopped stack they use `COMPOSE_FILE` from its `.env`, else `docker-compose.prod.yml` plus `docker-compose.override.yml` when that file exists. `update` prints the files it applies. Compose does not record profiles, so set `COMPOSE_PROFILES` in `.env` (for example `COMPOSE_PROFILES=cpu`) for a stack that uses them. | Command | Behavior | | --- | --- | -| `sim-setup` | Wizard. `--quick` uses defaults and asks essential questions; `--mode compose\|dev\|k8s` chooses the target. Dev and Kubernetes modes require a source checkout. | +| `sim-setup` | Wizard. `--quick` uses defaults and asks essential questions; `--mode compose\|dev\|k8s` chooses the target; `--url ` sets a Compose install's public URL. Dev and Kubernetes modes require a source checkout. | | `status` | Reports detected installations and health. | | `logs` | Follows Compose logs or the Kubernetes app deployment. In dev mode, prints container log commands; the app runs in your terminal. | | `start` / `stop` / `restart` | Starts, stops, or restarts Compose services. In dev mode, manages only PostgreSQL and Redis; start/stop the dev server yourself. For Kubernetes, prints port-forward or scale commands without applying them. | @@ -261,12 +273,12 @@ Restore only to the intended database: docker compose -f docker-compose.prod.yml exec -T db psql -U postgres simstudio < backup.sql ``` -Use your configured role/database if you changed `POSTGRES_*`. `-T` disables TTY allocation for redirected input/output. Compose stores database data in the `postgres_data` volume; file uploads and encryption keys need separate backups. +Use your configured role/database if you changed `POSTGRES_*`. `-T` disables TTY allocation for redirected input/output. Compose stores database data in the `postgres_data` volume and local uploads in the `sim_uploads` volume; back up uploads and encryption keys separately. For an image update, change the pinned `SIM_VERSION` in `.env`, then: ```bash -bunx sim-setup update +npx sim-setup update ``` Read [Upgrades](/platform/self-hosting/upgrades) before updating or restoring an existing installation. diff --git a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx index 8527aba1411..068c8faeab8 100644 --- a/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx +++ b/apps/docs/content/docs/platform/self-hosting/environment-variables.mdx @@ -146,7 +146,7 @@ For hosted models, Sim checks catalog-supported widths and falls back to the mod | `1536` | `text-embedding-3-small`, `text-embedding-3-large`, `gemini-embedding-001` | | `3072` | `text-embedding-3-large`, `gemini-embedding-001` | -For Compose or a source checkout, run `bunx sim-setup add knowledge-embeddings` to choose OpenAI, Azure OpenAI, OpenRouter, Gemini, or Ollama and write its configuration. The three OpenAI-family transports share model/width choices. `bunx sim-setup config` reports the family selected by `KB_EMBEDDING_MODEL`. For Helm, set the variables through chart values or your secret strategy. Run Ollama yourself; the setup command configures a connection, not an Ollama installation. +For Compose or a source checkout, run `npx sim-setup add knowledge-embeddings` to choose OpenAI, Azure OpenAI, OpenRouter, Gemini, or Ollama and write its configuration. The three OpenAI-family transports share model/width choices. `npx sim-setup config` reports the family selected by `KB_EMBEDDING_MODEL`. For Helm, set the variables through chart values or your secret strategy. Run Ollama yourself; the setup command configures a connection, not an Ollama installation. The Embeddings block reads the same `OLLAMA_URL`. It lists the models on that server that report an embedding capability, with the width each one emits where Ollama reports it, so a workflow can embed @@ -214,7 +214,7 @@ Plain JavaScript without imports runs in isolated-vm within Node child workers i | `COPILOT_API_KEY` | API key for the Chat service (the Mothership). Required for Chat, the Sim Chat workflow block, and Inbox operations that use that service. See [Chat service](/platform/self-hosting/chat) | | `SIM_AGENT_API_URL` | Mothership origin the Sim server calls. Defaults to `https://www.copilot.sim.ai`, the Sim-hosted service | | `MOTHERSHIP_SIM_TRANSPORT` | `direct` (the Mothership calls Sim) or `checkpoint` (Sim polls the Mothership for workspace tool calls over outbound HTTPS). Self-hosted Sim defaults to `checkpoint` | -| `NEXT_PUBLIC_CHAT_DISABLED` | Set to `true` to hide the Chat module: the workspace lands on your first workflow, with no chats list or editor Chat panel. Chat is shown when unset; `bunx sim-setup` sets it for you if you skip the chat key | +| `NEXT_PUBLIC_CHAT_DISABLED` | Set to `true` to hide the Chat module: the workspace lands on your first workflow, with no chats list or editor Chat panel. Chat is shown when unset; `npx sim-setup` sets it for you if you skip the chat key | | `PII_URL` | Base URL of the Presidio service backing PII detection and redaction. The Helm chart wires it to its own `pii` Service when `pii.enabled`; on Compose point it at the PII service on your network. Local development and the Helm fallback use `http://localhost:5001`; that address works only when the service is reachable there. Point production at a running service to use redaction | | `ADMIN_API_KEY` | Admin API key for GitOps operations and organization provisioning | @@ -236,7 +236,7 @@ Most enterprise features read their settings from the organization that owns a w ## File storage -By default Sim writes uploads to local disk. Neither stock production Compose nor the default Helm chart mounts the upload directory, so configure cloud storage or a persistent local layout before retaining files. See [Object storage](/platform/self-hosting/object-storage) for the full setup, bucket layout, and IAM policy. +By default Sim writes uploads to local disk. See [Object storage](/platform/self-hosting/object-storage) for the setup, bucket layout, and IAM policy. | Variable | Description | |----------|-------------| diff --git a/apps/docs/content/docs/platform/self-hosting/index.mdx b/apps/docs/content/docs/platform/self-hosting/index.mdx index 8765f5c8933..6edf8b78bb0 100644 --- a/apps/docs/content/docs/platform/self-hosting/index.mdx +++ b/apps/docs/content/docs/platform/self-hosting/index.mdx @@ -19,10 +19,10 @@ Compose bundles PostgreSQL, Redis, and a scheduler. The Helm chart bundles Postg ## Quick start -Install Bun, Node.js 20 or newer, Docker, and Docker Compose 2.24.0 or later, then run: +Install Node.js 20 or newer, Docker, and Docker Compose 2.24.0 or later, then run: ```bash -bunx sim-setup +npx sim-setup ``` The wizard creates a `./sim` directory with a production Compose file and generated `.env`, including `POSTGRES_PASSWORD`. It starts published container images. Open [http://localhost:3000](http://localhost:3000). @@ -50,7 +50,7 @@ These are sizing suggestions, not enforced minimums or capacity guarantees. The - Verify [background jobs](/platform/self-hosting/background-jobs), including the scheduler's `CRON_SECRET`. - Recreating an app container with unmounted local uploads loses those files. Losing an encryption key makes the data encrypted with it unreadable. A database backup does not replace file storage or key backups. + A database backup does not cover local uploads or encryption keys; back them up separately. Losing an encryption key makes the data encrypted with it unreadable. Run [Verify your install](/platform/self-hosting/verify) before opening the deployment to your team and after upgrades or restores. diff --git a/apps/docs/content/docs/platform/self-hosting/object-storage.mdx b/apps/docs/content/docs/platform/self-hosting/object-storage.mdx index 3f60ddb64c9..336892f1f21 100644 --- a/apps/docs/content/docs/platform/self-hosting/object-storage.mdx +++ b/apps/docs/content/docs/platform/self-hosting/object-storage.mdx @@ -17,7 +17,7 @@ Configure file storage before uploading durable files or adding app replicas. Si | **[Google Cloud Storage](https://cloud.google.com/storage)** | Production on GCP | - Local disk writes to `/app/apps/sim/uploads` inside the container. Neither `docker-compose.prod.yml` nor the Helm chart mounts a volume there, so every uploaded file is lost the moment the container is recreated — and files are **not** shared across replicas. Mount your own volume at that path if you must stay on local disk; for any multi-replica or production deployment, use S3, Azure Blob, or Google Cloud Storage. + Local disk writes to `/app/apps/sim/uploads` inside the container. `docker-compose.prod.yml` mounts the `sim_uploads` volume there, so files survive container recreation, but they stay on that one host and are **not** shared across replicas. The Helm chart mounts no volume there, so recreating a pod loses them. For any multi-replica or production deployment, use S3, Azure Blob, or Google Cloud Storage. ## How the backend is selected diff --git a/apps/docs/content/docs/platform/self-hosting/security.mdx b/apps/docs/content/docs/platform/self-hosting/security.mdx index 639fec2e8da..2e4aeafd043 100644 --- a/apps/docs/content/docs/platform/self-hosting/security.mdx +++ b/apps/docs/content/docs/platform/self-hosting/security.mdx @@ -340,7 +340,7 @@ The Compose files do not publish `db` on a host port. `simstudio`, `realtime`, a - **You set `POSTGRES_PASSWORD` before the first start.** Nothing else to do — updating the file closes the port. - **You never set it.** Postgres applies `POSTGRES_PASSWORD` only when it creates the data volume, so the database still uses `postgres`. Set `POSTGRES_PASSWORD=postgres` in `.env` so the stack starts, then rotate it: run `docker compose -f docker-compose.prod.yml exec db psql -U postgres -c "ALTER ROLE CURRENT_USER PASSWORD ''"` (with your `POSTGRES_USER` in place of `postgres` if you set one), set `POSTGRES_PASSWORD` to the same value, and run `docker compose -f docker-compose.prod.yml up -d`. Setting a new value in `.env` alone does not change the database's password and locks the app out. - `bunx sim-setup start` and `bunx sim-setup update` write the right value for you and print the rotation steps. + `npx sim-setup start` and `npx sim-setup update` write the right value for you and print the rotation steps. To reach the database from the host — `psql`, a desktop client, a backup job — use `docker compose -f docker-compose.prod.yml exec db psql -U postgres simstudio`, or pass a second Compose file that publishes it on loopback only and connect over an SSH tunnel: diff --git a/apps/docs/content/docs/platform/self-hosting/troubleshooting.mdx b/apps/docs/content/docs/platform/self-hosting/troubleshooting.mdx index 13ed133d51c..4a65438307f 100644 --- a/apps/docs/content/docs/platform/self-hosting/troubleshooting.mdx +++ b/apps/docs/content/docs/platform/self-hosting/troubleshooting.mdx @@ -10,9 +10,9 @@ Start with the checks for your deployment type, then follow the symptom below. On a production or local-development Compose install (including one running the Ollama overlay), or a source checkout, run the built-in checker first. It checks configuration and common dependency failures. It reads env files, so it is not a Kubernetes tool — on Helm, skip to the checks below. ```bash -bunx sim-setup doctor -bunx sim-setup doctor --fix # repair what it safely can -bunx sim-setup doctor --json # machine-readable, for CI +npx sim-setup doctor +npx sim-setup doctor --fix # repair what it safely can +npx sim-setup doctor --json # machine-readable, for CI ``` On a standalone Compose install, run it from the directory holding your `.env` and Compose file. From a source checkout, run it there — it resolves the per-application env files itself and needs no root `.env`. It exits `1` when any check fails, so scripts can use the exit status. See [Verify Your Install](/platform/self-hosting/verify#sim-setup-doctor) for what each group of checks covers. @@ -193,6 +193,8 @@ Inside Docker, `localhost` = the container, not your host machine. OLLAMA_URL=http://host.docker.internal:11434 ``` +On Linux, Ollama must also listen where the container reaches the host: bind it to the Docker bridge address, usually `OLLAMA_HOST=172.17.0.1:11434`. Its API has no authentication, so do not bind `0.0.0.0` unless a firewall blocks port 11434 from outside the host. + ## LM Studio requests route to Ollama Sim identifies dynamically discovered LM Studio and vLLM models by their `vllm/` prefix. If the endpoint is unavailable and you manually enter the raw LM Studio model identifier, Sim treats that unknown identifier as an Ollama model. diff --git a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx index 4d9e14837b1..4f429532af5 100644 --- a/apps/docs/content/docs/platform/self-hosting/upgrades.mdx +++ b/apps/docs/content/docs/platform/self-hosting/upgrades.mdx @@ -153,7 +153,7 @@ kubectl logs -n simstudio deploy/sim-app -c migrations --tail=100 ```bash -bunx sim-setup update +npx sim-setup update # The file that started your install. A stack running the Ollama overlay is a # docker-compose.prod.yml install — see below. COMPOSE_FILE=docker-compose.prod.yml @@ -161,7 +161,7 @@ COMPOSE_FILE=docker-compose.prod.yml docker compose -f "$COMPOSE_FILE" logs migrations ``` -`bunx sim-setup update` obtains the new images, then brings the stack up with +`npx sim-setup update` obtains the new images, then brings the stack up with `docker compose up -d`, keeping data volumes. What it runs depends on which Compose file the install uses: @@ -170,13 +170,15 @@ install uses: | `docker-compose.prod.yml` | Refreshes its managed copy of the Compose file, writes `POSTGRES_PASSWORD` to `.env` if it is missing, then `docker compose pull` — the versions configured by `SIM_VERSION`, or `latest` when unset | | `docker-compose.local.yml` | `docker compose build --pull` — rebuilds from source against refreshed base images, no pull of published images | -Inspect the result with `bunx sim-setup logs`, which targets whichever Compose file the install uses. +Inspect the result with `npx sim-setup logs`, which targets whichever Compose file the install uses. + +If your install predates the `sim_uploads` volume, copy its uploads out first: see [keep uploads from before the volume](/platform/self-hosting/docker#existing-installs-keep-uploads-from-before-the-volume). `sim-setup update` stops and asks before recreating an app container that still holds uploads. `docker-compose.prod.yml` requires `POSTGRES_PASSWORD`. If you manage the file yourself and Compose stops with `required variable POSTGRES_PASSWORD is missing a value`, confirm which password initialized the existing database volume. If it was never set, the old default was `postgres`; restore that value first, then see [Postgres on Compose](/platform/self-hosting/security#postgres-on-compose) to rotate it. Before updating a pinned production install, replace `SIM_VERSION` in `.env` with the chosen release tag. The update command pulls that configured tag; it does not automatically advance a pin. -The CLI detects only those two files. A stack started with the `docker-compose.ollama.yml` overlay is detected as a `docker-compose.prod.yml` install, and `update` upgrades its Sim services through that file alone, keeping `OLLAMA_URL` from `.env`. It does not touch the Ollama container. To refresh the Ollama image as well, run the update with both files: +The CLI detects installs by those two files. For a stack started with more files, such as the `docker-compose.ollama.yml` overlay, `update` applies every file the stack was started with and saves the set as `COMPOSE_FILE` in `.env`, so it still applies after `docker compose down`. Compose does not record profiles, so the profile-scoped Ollama service is updated only when `.env` sets `COMPOSE_PROFILES` (for example `COMPOSE_PROFILES=gpu`). Otherwise refresh it by hand: ```bash # The Ollama service is profile-scoped, so pass the profile you installed diff --git a/apps/docs/content/docs/platform/self-hosting/verify.mdx b/apps/docs/content/docs/platform/self-hosting/verify.mdx index a649427f341..e70a9137f28 100644 --- a/apps/docs/content/docs/platform/self-hosting/verify.mdx +++ b/apps/docs/content/docs/platform/self-hosting/verify.mdx @@ -12,7 +12,7 @@ Run these checks after installation, an upgrade, or a restore. Use a test worksp For Compose or a source checkout, run from the directory holding your env files: ```bash -bunx sim-setup doctor +npx sim-setup doctor ``` Doctor reports these groups: @@ -99,7 +99,7 @@ docker compose -f docker-compose.prod.yml logs cron curl -fsS http://localhost:3000/api/health ``` -Expect `simstudio`, `realtime`, `db`, `redis`, and `cron` to be running, with `migrations` completed successfully. Without `CRON_SECRET`, the cron service exits instead of running schedules. +Expect `simstudio`, `realtime`, `db`, `redis`, and `cron` to be running, with `migrations` and `uploads-init` completed successfully. Without `CRON_SECRET`, the cron service exits instead of running schedules. ## Read failures [#reading-the-failures] diff --git a/apps/docs/scripts/fixtures/content-baseline.json b/apps/docs/scripts/fixtures/content-baseline.json index 89a18efcee8..1cbbd8e32ee 100644 --- a/apps/docs/scripts/fixtures/content-baseline.json +++ b/apps/docs/scripts/fixtures/content-baseline.json @@ -172580,16 +172580,16 @@ { "lang": "bash", "meta": null, - "sha256": "1b5a91e0c8e98301de482bfdac88a0740597f0d7b4f197d2278a49bd62252752", - "bytes": 22, - "line": 28 + "sha256": "f6c25d1f99edeaa5029c6bae30235083b238b80b215b13eb7f3d5e34efabc9ee", + "bytes": 21, + "line": 32 }, { "lang": "bash", "meta": null, - "sha256": "8869220eac65502159ded115c61d4806be247fbdc930b07d52d32dde70f4f106", - "bytes": 62, - "line": 34 + "sha256": "c6e7fb800384d7d5ef95ed9a935fca407d1d5fa60a7d1efb17c5df96c1a82090", + "bytes": 61, + "line": 38 }, { "lang": "bash", @@ -172734,8 +172734,8 @@ { "lang": "bash", "meta": null, - "sha256": "a68c0e57699fd1b6173497de2b48e69da088d4f060252545cc6073e05474d543", - "bytes": 14, + "sha256": "115d390d2a2ce355d6ecfe6a662b9e2f6e73f285ec4186638f676cb9eb9007c6", + "bytes": 13, "line": 20 }, { @@ -172752,6 +172752,13 @@ "bytes": 370, "line": 41 }, + { + "lang": "bash", + "meta": null, + "sha256": "ac53018b6ccf14d539980fc8206ce97fadc6a32220a60333cf7a8bef91f27f77", + "bytes": 377, + "line": 80 + }, { "lang": "bash", "meta": null, @@ -172860,9 +172867,9 @@ { "lang": "bash", "meta": null, - "sha256": "a5f21e5199143694b8a6b0048a1cad17a98186f489694b49deacc108edf1fa7b", - "bytes": 21, - "line": 268 + "sha256": "fed433dfd89f812c99e9b905b5040307b08f5f828e78a6f6aa9322b7302b2264", + "bytes": 20, + "line": 280 } ], "links": [ @@ -173416,8 +173423,8 @@ { "lang": "bash", "meta": null, - "sha256": "a68c0e57699fd1b6173497de2b48e69da088d4f060252545cc6073e05474d543", - "bytes": 14, + "sha256": "115d390d2a2ce355d6ecfe6a662b9e2f6e73f285ec4186638f676cb9eb9007c6", + "bytes": 13, "line": 24 }, { @@ -176111,8 +176118,8 @@ { "lang": "bash", "meta": null, - "sha256": "95f834e604341dd3a4a7dbe6d3e03ba145a0ad5be37a545e49cb8c2650d38542", - "bytes": 140, + "sha256": "28b55f7fe8f07a34e08d95fd5517b6d6bbbb21984c824825fdeaf8e008a8158f", + "bytes": 137, "line": 12 }, { @@ -176556,9 +176563,9 @@ { "lang": "bash", "meta": null, - "sha256": "ad878e0b3ad9eca63a1d754f876211eebdd440c656ee0d3587aaa68ade3700bb", - "bytes": 275, - "line": 155 + "sha256": "8b1b7dd0aa41d3378e82618677b50ff44a7b9cbbe71038d2c1d30b5480c070bc", + "bytes": 274, + "line": 157 }, { "lang": "bash", @@ -176708,8 +176715,8 @@ { "lang": "bash", "meta": null, - "sha256": "697d0449cc0b626ecd35be20d8ce55d1f41160fae7ccdad9af48a57a5b69a4e1", - "bytes": 21, + "sha256": "76422de41fcefba9fc85682b50cf9b41f5990ec1b095efb82638f80ac1d0bdc7", + "bytes": 20, "line": 14 }, { diff --git a/docker-compose.local.yml b/docker-compose.local.yml index f6ecea7db75..504bfd1e165 100644 --- a/docker-compose.local.yml +++ b/docker-compose.local.yml @@ -37,6 +37,9 @@ services: # resolve, which it does not on Linux by default. extra_hosts: - 'host.docker.internal:host-gateway' + # Local file storage; the image creates the directory for the app user. + volumes: + - sim_uploads:/app/apps/sim/uploads depends_on: db: condition: service_healthy @@ -47,11 +50,11 @@ services: realtime: condition: service_healthy healthcheck: - test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3000'] - interval: 90s + test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3000/api/health'] + interval: 15s timeout: 5s retries: 3 - start_period: 10s + start_period: 60s realtime: env_file: @@ -84,10 +87,10 @@ services: memory: 1G healthcheck: test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3002/health'] - interval: 90s + interval: 15s timeout: 5s retries: 3 - start_period: 10s + start_period: 30s migrations: build: @@ -142,3 +145,4 @@ services: volumes: postgres_data: + sim_uploads: diff --git a/docker-compose.ollama.yml b/docker-compose.ollama.yml index 8da49c8d623..707813b39d2 100644 --- a/docker-compose.ollama.yml +++ b/docker-compose.ollama.yml @@ -18,8 +18,8 @@ services: simstudio: environment: # Required in .env rather than hardcoded here, so a run of the base file - # alone (`sim-setup update`) still points the app at Ollama. Both - # Ollama services answer to the network name `ollama`. + # alone still points the app at Ollama. Both Ollama services answer to + # the network name `ollama`. - 'OLLAMA_URL=${OLLAMA_URL:?set OLLAMA_URL=http://ollama:11434 in .env}' # NVIDIA GPU (needs the NVIDIA Container Toolkit on the host). diff --git a/docker-compose.prod.yml b/docker-compose.prod.yml index 77661f9b85a..3c82e237add 100644 --- a/docker-compose.prod.yml +++ b/docker-compose.prod.yml @@ -7,8 +7,9 @@ services: # so one variable drives all three. Set SIM_VERSION in .env to upgrade. image: ghcr.io/simstudioai/simstudio:${SIM_VERSION:-latest} restart: unless-stopped + # Set SIM_APP_PUBLISH=127.0.0.1:3000 in .env to expose the app only to a proxy on this host. Keep port 3000; sim-setup probes it. ports: - - '3000:3000' + - '${SIM_APP_PUBLISH:-3000}:3000' deploy: resources: limits: @@ -58,7 +59,12 @@ services: # resolve, which it does not on Linux by default. extra_hosts: - 'host.docker.internal:host-gateway' + # Local file storage when no cloud storage is configured; kept on this host. + volumes: + - sim_uploads:/app/apps/sim/uploads depends_on: + uploads-init: + condition: service_completed_successfully db: condition: service_healthy redis: @@ -68,11 +74,11 @@ services: realtime: condition: service_healthy healthcheck: - test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3000'] - interval: 90s + test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3000/api/health'] + interval: 15s timeout: 5s retries: 3 - start_period: 10s + start_period: 60s realtime: env_file: @@ -80,8 +86,9 @@ services: required: false image: ghcr.io/simstudioai/realtime:${SIM_VERSION:-latest} restart: unless-stopped + # SIM_REALTIME_PUBLISH works like SIM_APP_PUBLISH; keep port 3002. ports: - - '3002:3002' + - '${SIM_REALTIME_PUBLISH:-3002}:3002' deploy: resources: limits: @@ -105,10 +112,19 @@ services: condition: service_completed_successfully healthcheck: test: ['CMD', 'curl', '-fsS', 'http://127.0.0.1:3002/health'] - interval: 90s + interval: 15s timeout: 5s retries: 3 - start_period: 10s + start_period: 30s + + # Makes the uploads volume writable by the app's non-root user, for images that do not create the directory themselves. + uploads-init: + image: ghcr.io/simstudioai/simstudio:${SIM_VERSION:-latest} + user: '0:0' + entrypoint: ['chown', 'nextjs:nodejs', '/app/apps/sim/uploads'] + volumes: + - sim_uploads:/app/apps/sim/uploads + restart: 'no' migrations: image: ghcr.io/simstudioai/migrations:${SIM_VERSION:-latest} @@ -187,3 +203,4 @@ services: volumes: postgres_data: + sim_uploads: diff --git a/docker/app.Dockerfile b/docker/app.Dockerfile index ff6480a20ef..80c347abb22 100644 --- a/docker/app.Dockerfile +++ b/docker/app.Dockerfile @@ -261,6 +261,9 @@ RUN mkdir -p apps/sim/.next/cache apps/sim/.next/server/route-cache && \ chmod 1777 /tmp VOLUME ["/tmp", "/app/apps/sim/.next/cache", "/app/apps/sim/.next/server/route-cache"] +# Owned by the app user so a named volume mounted here starts writable. +RUN mkdir -p apps/sim/uploads && chown nextjs:nodejs apps/sim/uploads + # Switch to non-root user USER nextjs diff --git a/packages/sim-setup/src/arguments.test.ts b/packages/sim-setup/src/arguments.test.ts index 2e69c35303a..3150d3b9317 100644 --- a/packages/sim-setup/src/arguments.test.ts +++ b/packages/sim-setup/src/arguments.test.ts @@ -2,6 +2,39 @@ import { describe, expect, it } from 'vitest' import { parseSetupArguments } from './arguments' describe('parseSetupArguments', () => { + it('accepts a public origin for the Compose wizard without its trailing slash', () => { + expect(parseSetupArguments(['--url', 'https://sim.example.com/'])).toEqual({ + kind: 'wizard', + quick: false, + url: 'https://sim.example.com', + }) + expect(parseSetupArguments(['--mode', 'compose', '--url=http://10.0.0.5:3000'])).toEqual({ + kind: 'wizard', + quick: false, + mode: 'compose', + url: 'http://10.0.0.5:3000', + }) + }) + + it('accepts --yes only for update', () => { + expect(parseSetupArguments(['update', '--yes'])).toEqual({ + kind: 'lifecycle', + command: 'update', + yes: true, + }) + expect(() => parseSetupArguments(['stop', '--yes'])).toThrow('stop does not accept: --yes') + }) + + it.each([ + [['--url', 'sim.example.com'], 'is not a URL'], + [['--url', 'ftp://sim.example.com'], 'must use http or https'], + [['--url', 'https://sim.example.com/app'], 'must be an origin with no path'], + [['--url', 'https://user:pass@sim.example.com'], 'must not contain credentials'], + [['--mode', 'dev', '--url', 'https://sim.example.com'], 'applies only to --mode compose'], + ])('rejects wizard --url %j', (args, message) => { + expect(() => parseSetupArguments(args)).toThrow(message) + }) + it('rejects unknown and duplicate wizard options', () => { expect(() => parseSetupArguments(['--quik'])).toThrow('Unknown setup option: --quik') expect(() => parseSetupArguments(['--quick', '--quick'])).toThrow( diff --git a/packages/sim-setup/src/arguments.ts b/packages/sim-setup/src/arguments.ts index cc08714b045..27d9256af61 100644 --- a/packages/sim-setup/src/arguments.ts +++ b/packages/sim-setup/src/arguments.ts @@ -1,3 +1,5 @@ +import { parsePublicUrl } from './urls' + export type WizardMode = 'compose' | 'dev' | 'k8s' export const LIFECYCLE_COMMANDS = [ @@ -16,12 +18,12 @@ export type LifecycleCommand = (typeof LIFECYCLE_COMMANDS)[number] export type SetupInvocation = | { kind: 'help' } | { kind: 'version' } - | { kind: 'wizard'; quick: boolean; mode?: WizardMode } + | { kind: 'wizard'; quick: boolean; mode?: WizardMode; url?: string } | { kind: 'config' } | { kind: 'add'; feature: string; args: string[] } | { kind: 'doctor'; fix: boolean; json: boolean } | { kind: 'desktop'; url?: string; noOpen: boolean } - | { kind: 'lifecycle'; command: LifecycleCommand } + | { kind: 'lifecycle'; command: LifecycleCommand; yes?: boolean } export class SetupArgumentError extends Error { constructor(message: string) { @@ -121,9 +123,24 @@ function parseCore( if (!command || command.startsWith('-')) { const quick = oneFlag(args, '--quick') const withoutQuick = args.filter((arg) => arg !== '--quick') - const { mode, remaining } = parseMode(withoutQuick) + const { mode, remaining: withoutMode } = parseMode(withoutQuick) + const { value: rawUrl, remaining } = parseValueOption( + withoutMode, + '--url', + '--url requires the public URL Sim is served at' + ) if (remaining.length > 0) fail(`Unknown setup option: ${remaining[0]}`) - return { kind: 'wizard', quick, ...(mode ? { mode } : {}) } + if (rawUrl !== undefined && mode && mode !== 'compose') { + fail('--url applies only to --mode compose') + } + const url = rawUrl === undefined ? undefined : parsePublicUrl(rawUrl) + if (url && 'error' in url) fail(`invalid --url: ${url.error}`) + return { + kind: 'wizard', + quick, + ...(mode ? { mode } : {}), + ...(url ? { url: url.url } : {}), + } } const commandArgs = args.slice(1) @@ -174,6 +191,14 @@ function parseCore( } if (isLifecycleCommand(command)) { + if (command === 'update') { + const yes = oneFlag(commandArgs, '--yes') + expectNoArguments( + command, + commandArgs.filter((arg) => arg !== '--yes') + ) + return { kind: 'lifecycle', command, ...(yes ? { yes } : {}) } + } expectNoArguments(command, commandArgs) return { kind: 'lifecycle', command } } diff --git a/packages/sim-setup/src/capability-config.ts b/packages/sim-setup/src/capability-config.ts index 98f5b635f15..0defb04968e 100644 --- a/packages/sim-setup/src/capability-config.ts +++ b/packages/sim-setup/src/capability-config.ts @@ -21,6 +21,9 @@ import { STORAGE_CAPABILITY, } from '@sim/deployment-config/env-capabilities' +/** Where the configuration being written runs: a source checkout, Compose, or a cluster. */ +export type SetupDeployment = 'development' | 'compose' | 'kubernetes' + export type SetupHint = | string | { @@ -82,6 +85,8 @@ export interface ProviderSetupDefinition { env?: Readonly> prompts: readonly SetupPrompt[] currentWhen?: SetupCondition + /** Deployments that cannot run this provider, so setup does not offer it there. */ + unavailableOn?: readonly SetupDeployment[] } type ProviderSetupMap = { @@ -345,7 +350,8 @@ export const STORAGE_SETUP = defineCapabilitySetup(STORAGE_CAPABILITY, { hint: { development: 'fine for local dev (external-fetch flows like Instagram publish need cloud storage)', - containerized: 'files live in the container — LOST on restart; evaluation only', + containerized: + 'files persist in the sim_uploads volume on this host — not shared across hosts or replicas', }, }, providers: { @@ -658,6 +664,8 @@ export const SANDBOX_SETUP = defineCapabilitySetup(SANDBOX_CAPABILITY, { }, kubernetes: { hint: 'sandbox pods in your own cluster, isolated by a RuntimeClass', + // A Compose stack has no in-cluster service account to create sandbox pods with. + unavailableOn: ['compose'], prompts: [ { type: 'choice', diff --git a/packages/sim-setup/src/capability-setup.ts b/packages/sim-setup/src/capability-setup.ts index d5ad7317602..209d966e51f 100644 --- a/packages/sim-setup/src/capability-setup.ts +++ b/packages/sim-setup/src/capability-setup.ts @@ -17,13 +17,14 @@ import { type CapabilitySetupDefinition, matchesSetupCondition, type SetupCondition, + type SetupDeployment, type SetupHint, type SetupPrompt, } from './capability-config' import * as p from './prompter' export interface CapabilitySetupContext { - containerized: boolean + deployment: SetupDeployment } export interface EnvCapabilitySetupTransition { @@ -37,6 +38,7 @@ interface ResolvedSetupOption { hint?: SetupHint kind: 'provider' | 'default' | 'action' providerId?: string + unavailableOn?: readonly SetupDeployment[] env: Readonly> prompts: readonly SetupPrompt[] currentWhen?: SetupCondition @@ -75,7 +77,7 @@ function resolveHint( context: CapabilitySetupContext ): string | undefined { if (!hint || typeof hint === 'string') return hint - return context.containerized ? hint.containerized : hint.development + return context.deployment === 'development' ? hint.development : hint.containerized } /** Adds the standard status marker without discarding an option's explanatory hint. */ @@ -144,6 +146,7 @@ export function getCapabilitySetupOptions( env: providerSetup.env ?? {}, prompts: providerSetup.prompts, currentWhen: providerSetup.currentWhen, + unavailableOn: providerSetup.unavailableOn, } }) @@ -178,6 +181,21 @@ export function getCapabilitySetupOptions( }) } +/** + * The options to offer for `context`: every option except a provider the + * deployment cannot run, which stays listed only while it is the current + * configuration so the operator can still see and replace it. + */ +function getAvailableCapabilitySetupOptions( + setup: CapabilitySetupDefinition, + context: CapabilitySetupContext, + currentOptionId: string | undefined +): readonly ResolvedSetupOption[] { + return getCapabilitySetupOptions(setup).filter( + (option) => option.id === currentOptionId || !option.unavailableOn?.includes(context.deployment) + ) +} + /** Resolves the setup option representing the effective current configuration, if one exists. */ export function resolveCurrentCapabilitySetupOptionId( setup: CapabilitySetupDefinition, @@ -482,8 +500,8 @@ export async function promptCapabilitySetup( currentValues: ReadonlyMap, context: CapabilitySetupContext ): Promise { - const options = getCapabilitySetupOptions(setup) const currentOptionId = resolveCurrentCapabilitySetupOptionId(setup, currentValues) + const options = getAvailableCapabilitySetupOptions(setup, context, currentOptionId) const selectedOptionId = await p.select({ message: setup.message, options: options.map((option) => ({ @@ -510,11 +528,11 @@ export async function promptOptionalCapabilitySetup( context: CapabilitySetupContext, skipHint: string ): Promise { - const options = getCapabilitySetupOptions(setup) + const currentOptionId = resolveCurrentCapabilitySetupOptionId(setup, currentValues) + const options = getAvailableCapabilitySetupOptions(setup, context, currentOptionId) if (options.some((option) => option.id === SKIP_OPTION_ID)) { throw new Error(`Capability ${setup.definition.id} uses reserved option ${SKIP_OPTION_ID}`) } - const currentOptionId = resolveCurrentCapabilitySetupOptionId(setup, currentValues) const selectedOptionId = await p.select({ message: setup.message, options: [ diff --git a/packages/sim-setup/src/checks.test.ts b/packages/sim-setup/src/checks.test.ts index 9f9d342ae27..481c532873d 100644 --- a/packages/sim-setup/src/checks.test.ts +++ b/packages/sim-setup/src/checks.test.ts @@ -2,11 +2,25 @@ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' -const { fakeRoot } = vi.hoisted(() => { +const { fakeRoot, mockSpawnSync, mockHttpHealth } = vi.hoisted(() => { const { mkdtempSync } = require('node:fs') as typeof import('node:fs') const { tmpdir } = require('node:os') as typeof import('node:os') const { join } = require('node:path') as typeof import('node:path') - return { fakeRoot: mkdtempSync(join(tmpdir(), 'sim-setup-checks-')) } + return { + fakeRoot: mkdtempSync(join(tmpdir(), 'sim-setup-checks-')), + mockSpawnSync: vi.fn(() => ({ status: 1, stdout: '', stderr: '' })), + mockHttpHealth: vi.fn(async (_url: string) => false), + } +}) + +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, spawnSync: mockSpawnSync } +}) + +vi.mock('./probes', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, httpHealth: mockHttpHealth } }) vi.mock('./context', async (importOriginal) => { @@ -133,6 +147,145 @@ describe('setup coherence checks', () => { }) }) +describe('realtime reachability from the browser', () => { + async function socketFindings(appUrl: string) { + const findings = await runChecks(rootContext({ NEXT_PUBLIC_APP_URL: appUrl }), ['coherence']) + return findings.filter((finding) => finding.message.includes('NEXT_PUBLIC_SOCKET_URL')) + } + + it.each(['https://sim.example.com', 'http://sim.internal:8080', 'http://[::1]:3000'])( + 'does not warn when %s is proxied or loopback', + async (appUrl) => { + expect(await socketFindings(appUrl)).toEqual([]) + } + ) + + it('treats a blank NEXT_PUBLIC_SOCKET_URL as unset, as the browser does', async () => { + const findings = await runChecks( + rootContext({ + NEXT_PUBLIC_APP_URL: 'http://192.168.1.10:3000', + NEXT_PUBLIC_SOCKET_URL: ' ', + }), + ['coherence'] + ) + + expect( + findings.filter((finding) => finding.message.includes('NEXT_PUBLIC_SOCKET_URL')) + ).toEqual([expect.objectContaining({ status: 'warn' })]) + }) + + it('points an app served directly on :3000 at realtime on :3002', async () => { + expect(await socketFindings('http://192.168.1.10:3000')).toEqual([ + expect.objectContaining({ + status: 'warn', + fix: expect.stringContaining('NEXT_PUBLIC_SOCKET_URL=http://192.168.1.10:3002'), + }), + ]) + }) +}) + +describe("doctor probing a Compose install's host Ollama", () => { + async function ollamaFinding() { + const ctx = { ...rootContext({ OLLAMA_URL: 'http://host.docker.internal:11434' }), live: true } + const findings = await runChecks(ctx, ['live']) + return findings.find((finding) => finding.message.toLowerCase().includes('ollama')) + } + + it('passes when Ollama answers only on the Docker bridge address', async () => { + mockHttpHealth.mockImplementation(async (url: string) => !url.includes('localhost')) + + expect(await ollamaFinding()).toMatchObject({ status: 'pass' }) + }) + + it('does not probe a Compose-internal Ollama service from the host', async () => { + mockHttpHealth.mockImplementation(async () => false) + const ctx = { ...rootContext({ OLLAMA_URL: 'http://ollama:11434' }), live: true } + + const findings = await runChecks(ctx, ['live']) + + expect(findings.find((finding) => finding.message.includes('ollama'))).toMatchObject({ + status: 'skip', + }) + expect(mockHttpHealth).not.toHaveBeenCalledWith('http://ollama:11434/api/tags') + }) + + it('warns when Ollama answers on neither loopback nor the bridge', async () => { + mockHttpHealth.mockImplementation(async () => false) + + expect(await ollamaFinding()).toMatchObject({ status: 'warn' }) + }) +}) + +describe('Compose root .env required keys', () => { + const secrets = [ + `BETTER_AUTH_SECRET=${'a'.repeat(32)}`, + `ENCRYPTION_KEY=${'b'.repeat(64)}`, + `INTERNAL_API_SECRET=${'c'.repeat(32)}`, + ].join('\n') + const prodFile = path.join(fakeRoot, 'docker-compose.prod.yml') + const localFile = path.join(fakeRoot, 'docker-compose.local.yml') + + /** A source checkout whose root .env holds `env` while Docker reports `runningFile` for it. */ + async function schemaFindings(env: string, runningFile: string) { + rmSync(fakeRoot, { recursive: true, force: true }) + mkdirSync(fakeRoot, { recursive: true }) + writeFileSync(path.join(fakeRoot, '.env'), `${env}\n`) + writeFileSync( + prodFile, + `services:\n cron:\n image: cron\n db:\n environment:\n - POSTGRES_PASSWORD=\${POSTGRES_PASSWORD:?is required}\n` + ) + writeFileSync(localFile, 'services:\n db:\n image: pgvector\n') + mockSpawnSync.mockReturnValue({ + status: 0, + stdout: JSON.stringify([{ Name: 'sim', Status: 'running(5)', ConfigFiles: runningFile }]), + stderr: '', + }) + return runChecks(loadCheckContext(false), ['schema']) + } + + const about = (key: string, findings: Awaited>) => + findings.filter((finding) => finding.message.includes(key)) + + beforeEach(() => vi.stubEnv('POSTGRES_PASSWORD', undefined)) + + it('generates a missing CRON_SECRET, without which the cron service never runs', async () => { + const findings = await schemaFindings(secrets, prodFile) + + expect(about('CRON_SECRET', findings)).toEqual([ + expect.objectContaining({ + status: 'fail', + fix: expect.stringContaining('the app and cron containers'), + autofix: expect.any(Function), + }), + ]) + }) + + it('reports a missing POSTGRES_PASSWORD the Compose file requires without inventing one', async () => { + const findings = await schemaFindings(`${secrets}\nCRON_SECRET=${'d'.repeat(32)}`, prodFile) + + const postgres = about('POSTGRES_PASSWORD', findings) + expect(postgres).toEqual([ + expect.objectContaining({ status: 'fail', fix: expect.stringContaining('sim-setup start') }), + ]) + expect(postgres[0]?.autofix).toBeUndefined() + }) + + it('accepts a POSTGRES_PASSWORD exported in the shell, which Compose reads over .env', async () => { + vi.stubEnv('POSTGRES_PASSWORD', 'from-shell') + + const findings = await schemaFindings(`${secrets}\nCRON_SECRET=${'d'.repeat(32)}`, prodFile) + + expect(about('POSTGRES_PASSWORD', findings)).toEqual([]) + }) + + it('holds a checkout running docker-compose.local.yml to neither production-only key', async () => { + const findings = await schemaFindings(secrets, localFile) + + expect(about('POSTGRES_PASSWORD', findings)).toEqual([]) + expect(about('CRON_SECRET', findings)).toEqual([]) + }) +}) + describe('registration mode checks', () => { function registrationFindings(findings: Awaited>) { return findings.filter((finding) => diff --git a/packages/sim-setup/src/checks.ts b/packages/sim-setup/src/checks.ts index a9b6c0dea29..0dbe2363c41 100644 --- a/packages/sim-setup/src/checks.ts +++ b/packages/sim-setup/src/checks.ts @@ -1,3 +1,6 @@ +import { existsSync, readFileSync } from 'node:fs' +import { networkInterfaces } from 'node:os' +import path from 'node:path' import { ASYNC_JOBS_CAPABILITY, CORE_CONFIGURATION_KEYS, @@ -13,7 +16,11 @@ import { STORAGE_CAPABILITY, } from '@sim/deployment-config/env-capabilities' import { REGISTRATION_MODES, resolveRegistrationMode } from '@sim/deployment-config/registration' +import { isLoopbackHostname } from '@sim/security/hostnames' import { getSetupCommand } from './capability-config' +import { composeFileRequiresPostgresPassword } from './compose-database' +import { listComposeProjects } from './compose-project' +import { SETUP_CONTEXT } from './context' import { portOpen } from './detect' import { type EnvFile, @@ -23,6 +30,7 @@ import { isPlaceholder, isTruthy, isUsableSecret, + ROOT, readEnvFile, SECRET_KEYS, SHARED_KEYS, @@ -86,6 +94,11 @@ export interface CheckContext { /** The file holding app configuration for this layout — what coherence reads. */ primary: EnvFile live: boolean + /** + * The production Compose file, when this root-layout install runs it. Only + * that file requires `POSTGRES_PASSWORD` and runs the cron service. + */ + composeFile?: string } /** Split wins when both exist: the per-app files are what a dev run actually loads. */ @@ -108,7 +121,31 @@ export function loadCheckContext(live: boolean): CheckContext { root: readEnvFile('root'), } const layout = detectLayout(env) - return { env, layout, primary: layout === 'root' ? env.root : env.sim, live } + const composeFile = layout === 'root' ? productionComposeFileInUse() : undefined + return { + env, + layout, + primary: layout === 'root' ? env.root : env.sim, + live, + ...(composeFile ? { composeFile } : {}), + } +} + +/** + * The production Compose file when this install runs it. A standalone install + * only ever runs that file; a source checkout always has it on disk but may run + * `docker-compose.local.yml` instead, so there it counts only when Docker + * recorded it for a project. + */ +function productionComposeFileInUse(): string | undefined { + const file = path.join(ROOT, 'docker-compose.prod.yml') + if (!existsSync(file)) return undefined + if (SETUP_CONTEXT.kind === 'standalone') return file + const target = path.resolve(file) + const recorded = listComposeProjects().some((project) => + project.files.some((entry) => path.resolve(entry) === target) + ) + return recorded ? file : undefined } export const REQUIRED_APP_KEYS = CORE_CONFIGURATION_KEYS @@ -131,6 +168,21 @@ const REQUIRED_KEYS: Partial> = { root: ['BETTER_AUTH_SECRET', 'ENCRYPTION_KEY', 'INTERNAL_API_SECRET'], } +/** Required keys for `target`, including those only the production Compose file needs. */ +function requiredKeys(ctx: CheckContext, target: EnvTarget): readonly string[] { + const keys = REQUIRED_KEYS[target] ?? [] + return target === 'root' && ctx.composeFile ? [...keys, 'CRON_SECRET'] : keys +} + +/** How to apply a missing key once doctor generates it, when recreating containers matters. */ +function missingKeyFollowUp(ctx: CheckContext, key: string): string | undefined { + if (key !== 'CRON_SECRET' || !ctx.composeFile) return undefined + const containers = /^ {2}cron:/m.test(readFileSync(ctx.composeFile, 'utf8')) + ? 'the app and cron containers' + : 'the app container' + return `doctor --fix generates it; then run npx sim-setup start to recreate ${containers}` +} + const MIN_32_KEYS = new Set(SECRET_KEYS) const URL_KEYS = ['DATABASE_URL', 'BETTER_AUTH_URL', 'NEXT_PUBLIC_APP_URL'] @@ -217,7 +269,7 @@ function checkSchema(ctx: CheckContext): Finding[] { const file = ctx.env[target] if (!file.exists) continue const missing: string[] = [] - for (const key of REQUIRED_KEYS[target] ?? []) { + for (const key of requiredKeys(ctx, target)) { const value = file.vars.get(key) if (!value) { missing.push(key) @@ -225,7 +277,9 @@ function checkSchema(ctx: CheckContext): Finding[] { group: 'schema', status: 'fail', message: `${rel(file)}: ${key} is missing or empty`, - fix: MIN_32_KEYS.has(key) ? 'doctor --fix generates it' : `set ${key} in ${rel(file)}`, + fix: + missingKeyFollowUp(ctx, key) ?? + (MIN_32_KEYS.has(key) ? 'doctor --fix generates it' : `set ${key} in ${rel(file)}`), autofix: autofixForMissing(ctx, target, key), }) continue @@ -277,6 +331,7 @@ function checkSchema(ctx: CheckContext): Finding[] { } } } + if (target === 'root') findings.push(...checkPostgresPassword(ctx)) if (missing.length === 0 && findings.every((f) => !f.message.startsWith(rel(file)))) { findings.push({ group: 'schema', @@ -288,6 +343,52 @@ function checkSchema(ctx: CheckContext): Finding[] { return findings } +/** + * The production Compose file refuses to start without `POSTGRES_PASSWORD`. It + * must match the password the data volume was created with, so doctor never + * invents one: `sim-setup start` picks the right value for the volume. + */ +function checkPostgresPassword(ctx: CheckContext): Finding[] { + if (!ctx.composeFile || !composeFileRequiresPostgresPassword(ctx.composeFile)) return [] + if (ctx.env.root.vars.get('POSTGRES_PASSWORD') || process.env.POSTGRES_PASSWORD) return [] + return [ + { + group: 'schema', + status: 'fail', + message: `.env: POSTGRES_PASSWORD is missing — ${path.basename(ctx.composeFile)} will not start without it`, + fix: 'run: npx sim-setup start (it writes the password matching your database volume)', + }, + ] +} + +/** + * The browser finds realtime from `NEXT_PUBLIC_SOCKET_URL`, else from the page + * origin when that origin is not loopback (`getSocketUrl` in the app). A page + * served straight from the app's :3000 then looks for realtime on :3000, where + * nothing answers; a proxied origin works when the proxy routes `/socket.io`. + */ +function checkSocketUrl(vars: ReadonlyMap): Finding[] { + const appUrl = vars.get('NEXT_PUBLIC_APP_URL') + // The browser trims the override and ignores it when blank, as getSocketUrl does. + if (!appUrl || vars.get('NEXT_PUBLIC_SOCKET_URL')?.trim()) return [] + let origin: URL + try { + origin = new URL(appUrl) + } catch { + return [] + } + if (isLoopbackHostname(origin.hostname) || origin.port !== '3000') return [] + return [ + { + group: 'coherence', + status: 'warn', + message: + 'NEXT_PUBLIC_APP_URL serves the app directly on :3000 but NEXT_PUBLIC_SOCKET_URL is unset — the browser looks for the realtime server on :3000 instead of :3002', + fix: `set NEXT_PUBLIC_SOCKET_URL=${origin.protocol}//${origin.hostname}:3002, or serve Sim behind a reverse proxy that routes /socket.io to realtime :3002`, + }, + ] +} + function checkConsistency(ctx: CheckContext): Finding[] { // Consistency is about the same key agreeing across files; a single root // file has nothing to disagree with. @@ -526,21 +627,7 @@ function checkCoherence(ctx: CheckContext): Finding[] { } } - const appUrlValue = sim.vars.get('NEXT_PUBLIC_APP_URL') - if ( - appUrlValue && - !appUrlValue.includes('localhost') && - !appUrlValue.includes('127.0.0.1') && - !sim.vars.get('NEXT_PUBLIC_SOCKET_URL') - ) { - findings.push({ - group: 'coherence', - status: 'warn', - message: - 'NEXT_PUBLIC_APP_URL is not localhost but NEXT_PUBLIC_SOCKET_URL is unset — the browser cannot find the realtime server', - fix: 'set NEXT_PUBLIC_SOCKET_URL to the public URL of the realtime service (:3002)', - }) - } + findings.push(...checkSocketUrl(sim.vars)) if (findings.length === 0) { findings.push({ @@ -723,11 +810,72 @@ async function checkService(label: string, port: number, url: string): Promise { +/** The Docker bridge address Compose's `host-gateway` points at when the host does not report one. */ +const DEFAULT_DOCKER_BRIDGE = '172.17.0.1' + +/** The host's `docker0` IPv4 address, which `host.docker.internal` resolves to on Linux. */ +function dockerBridgeAddress(): string { + const bridge = networkInterfaces().docker0?.find((entry) => entry.family === 'IPv4') + return bridge?.address ?? DEFAULT_DOCKER_BRIDGE +} + +/** + * Where doctor, running on the host, probes the Ollama a Compose app reaches + * through `host.docker.internal` — a name the host itself usually cannot + * resolve. Ollama may listen on loopback (Docker Desktop forwards to it) or, + * as the setup advice recommends on Linux, only on the Docker bridge address. + */ +function hostOllamaUrls(ollamaUrl: string, compose: boolean): string[] { + if (!compose) return [ollamaUrl] + try { + const url = new URL(ollamaUrl) + if (url.hostname !== 'host.docker.internal') return [ollamaUrl] + return ['localhost', dockerBridgeAddress()].map((host) => { + url.hostname = host + return url.toString() + }) + } catch { + return [ollamaUrl] + } +} + +/** + * The Compose service a compose install's `OLLAMA_URL` names, such as `ollama` + * from the bundled overlay. A single-label host other than `localhost` resolves + * only on the Compose network, so the host cannot probe it. + */ +function composeServiceHost(ollamaUrl: string, compose: boolean): string | null { + if (!compose) return null + try { + const { hostname } = new URL(ollamaUrl) + return /^[a-z0-9_-]+$/i.test(hostname) && !isLoopbackHostname(hostname) ? hostname : null + } catch { + return null + } +} + +async function checkOllama(sim: EnvFile, compose: boolean): Promise { const ollamaUrl = sim.vars.get('OLLAMA_URL') if (!ollamaUrl) return [] + const service = composeServiceHost(ollamaUrl, compose) + if (service) { + return [ + { + group: 'live', + status: 'skip', + message: `ollama: OLLAMA_URL names the Compose service "${service}", reachable only inside the stack`, + }, + ] + } + let reachable = false + for (const probeUrl of hostOllamaUrls(ollamaUrl, compose)) { + if (await httpHealth(`${probeUrl.replace(/\/$/, '')}/api/tags`)) { + reachable = true + break + } + } return [ - (await httpHealth(`${ollamaUrl.replace(/\/$/, '')}/api/tags`)) + reachable ? { group: 'live', status: 'pass', message: 'ollama reachable' } : { group: 'live', @@ -751,7 +899,7 @@ async function checkLive(ctx: CheckContext): Promise { checkRedis(sim), checkService('app', 3000, 'http://localhost:3000/api/health'), checkService('realtime', 3002, 'http://localhost:3002/health'), - checkOllama(sim), + checkOllama(sim, ctx.layout === 'root'), ]) return [...database, ...redis, ...app, ...realtime, ...ollama] } diff --git a/packages/sim-setup/src/compose-project.test.ts b/packages/sim-setup/src/compose-project.test.ts index 9432056ea7a..4de74ef62c5 100644 --- a/packages/sim-setup/src/compose-project.test.ts +++ b/packages/sim-setup/src/compose-project.test.ts @@ -1,5 +1,8 @@ -import { describe, expect, it } from 'vitest' -import { standaloneComposeProjectName } from './compose-project' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { composeFileSet, standaloneComposeProjectName } from './compose-project' describe('standaloneComposeProjectName', () => { it('isolates installations that share the same directory basename', () => { @@ -8,3 +11,107 @@ describe('standaloneComposeProjectName', () => { ) }) }) + +describe('composeFileSet', () => { + let dir: string + let base: string + + beforeEach(() => { + dir = mkdtempSync(path.join(tmpdir(), 'sim-setup-files-')) + base = path.join(dir, 'docker-compose.prod.yml') + }) + afterEach(() => rmSync(dir, { recursive: true, force: true })) + + it('keeps the files Compose recorded for the running project over .env and overrides', () => { + writeFileSync(base, '') + const overlay = path.join(dir, 'docker-compose.ollama.yml') + writeFileSync(overlay, '') + writeFileSync(path.join(dir, '.env'), 'COMPOSE_FILE=other.yml\n') + writeFileSync(path.join(dir, 'docker-compose.override.yml'), '') + + expect(composeFileSet({ baseFile: base, dir, recordedFiles: [base, overlay] })).toEqual({ + files: [base, overlay], + warnings: [], + }) + }) + + it('leaves out a recorded overlay that no longer exists and says so', () => { + writeFileSync(base, '') + const gone = path.join(dir, 'docker-compose.ollama.yml') + + const { files, warnings } = composeFileSet({ + baseFile: base, + dir, + recordedFiles: [base, gone], + }) + + expect(files).toEqual([base]) + expect(warnings).toEqual([expect.stringContaining(gone)]) + }) + + it('reads COMPOSE_FILE from the install .env with its path separator', () => { + writeFileSync(base, '') + mkdirSync(path.join(dir, 'overlays')) + writeFileSync(path.join(dir, 'overlays/cron.yml'), '') + writeFileSync( + path.join(dir, '.env'), + 'COMPOSE_PATH_SEPARATOR=;\nCOMPOSE_FILE=docker-compose.prod.yml;overlays/cron.yml\n' + ) + + expect(composeFileSet({ baseFile: base, dir }).files).toEqual([ + base, + path.join(dir, 'overlays/cron.yml'), + ]) + }) + + it('splits COMPOSE_FILE on the OS path-list separator by default, as Compose does', () => { + const posixDelimiter = path.delimiter + Object.assign(path, { delimiter: ';' }) + try { + writeFileSync(base, '') + writeFileSync(path.join(dir, 'cron.yml'), '') + writeFileSync(path.join(dir, '.env'), 'COMPOSE_FILE=docker-compose.prod.yml;cron.yml\n') + + expect(composeFileSet({ baseFile: base, dir }).files).toEqual([ + base, + path.join(dir, 'cron.yml'), + ]) + } finally { + Object.assign(path, { delimiter: posixDelimiter }) + } + }) + + it('leaves out a COMPOSE_FILE entry that no longer exists and says so', () => { + writeFileSync(base, '') + writeFileSync(path.join(dir, '.env'), 'COMPOSE_FILE=docker-compose.prod.yml:gone.yml\n') + + const { files, warnings } = composeFileSet({ baseFile: base, dir }) + + expect(files).toEqual([base]) + expect(warnings).toEqual([expect.stringContaining(path.join(dir, 'gone.yml'))]) + }) + + it('ignores a COMPOSE_FILE that does not include the base file', () => { + writeFileSync(path.join(dir, 'docker-compose.local.yml'), '') + writeFileSync(path.join(dir, 'docker-compose.ollama.yml'), '') + writeFileSync( + path.join(dir, '.env'), + 'COMPOSE_FILE=docker-compose.local.yml:docker-compose.ollama.yml\n' + ) + + const { files, warnings } = composeFileSet({ baseFile: base, dir }) + + expect(files).toEqual([base]) + expect(warnings).toEqual([ + expect.stringContaining('does not include an existing docker-compose.prod.yml'), + ]) + }) + + it('adds docker-compose.override.yml only when it exists', () => { + expect(composeFileSet({ baseFile: base, dir }).files).toEqual([base]) + + const override = path.join(dir, 'docker-compose.override.yml') + writeFileSync(override, '') + expect(composeFileSet({ baseFile: base, dir }).files).toEqual([base, override]) + }) +}) diff --git a/packages/sim-setup/src/compose-project.ts b/packages/sim-setup/src/compose-project.ts index 2ec93d39adb..d5d7dadd000 100644 --- a/packages/sim-setup/src/compose-project.ts +++ b/packages/sim-setup/src/compose-project.ts @@ -1,5 +1,12 @@ +import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' +import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' +import { toRecordOrNull } from '@sim/utils/object' +import { parseEnv } from './env-files' + +/** The file Compose merges over the base file when it runs without `-f`. */ +const COMPOSE_OVERRIDE_FILE = 'docker-compose.override.yml' /** Returns the stable Docker Compose project name for a new standalone installation. */ export function standaloneComposeProjectName(root: string): string { @@ -20,3 +27,134 @@ export function legacyComposeProjectName(root: string): string { } return name } + +/** A Compose project as `docker compose ls` reports it, with its files in `-f` order. */ +export interface ComposeProjectRecord { + name: string + files: string[] +} + +/** + * Parses `docker compose ls --format json`, or returns `null` when the output is + * not that shape. `ConfigFiles` is comma-separated when a project was started + * with several `-f` files. + */ +export function parseComposeProjects(output: string): ComposeProjectRecord[] | null { + let parsed: unknown + try { + parsed = JSON.parse(output) + } catch { + return null + } + if (!Array.isArray(parsed)) return null + const projects: ComposeProjectRecord[] = [] + for (const item of parsed) { + const record = toRecordOrNull(item) + const name = record?.Name + const configFiles = record?.ConfigFiles + if (typeof name !== 'string' || typeof configFiles !== 'string') return null + const files = configFiles + .split(',') + .map((file) => file.trim()) + .filter(Boolean) + if (files.length === 0) return null + projects.push({ name, files }) + } + return projects +} + +/** Every Compose project Docker knows about, or none when Docker cannot be queried. */ +export function listComposeProjects(): ComposeProjectRecord[] { + const result = spawnSync('docker', ['compose', 'ls', '-a', '--format', 'json'], { + encoding: 'utf8', + }) + if (result.status !== 0) return [] + return parseComposeProjects(result.stdout) ?? [] +} + +/** A resolved Compose file set and what was left out of it, for the caller to report. */ +export interface ComposeFileSet { + files: string[] + warnings: string[] +} + +/** Keeps the files still on disk, recording a warning for each one that is gone. */ +function existingFiles(files: readonly string[], origin: string, warnings: string[]): string[] { + const present = files.filter((file) => existsSync(file)) + for (const file of files) { + if (!present.includes(file)) + warnings.push(`${file} ${origin} but no longer exists; leaving it out`) + } + return present +} + +/** + * The Compose files every operation on an install must pass, in order. Passing + * `-f` turns off Compose's own `COMPOSE_FILE` and override-file lookup, so a + * bare `-f ` silently drops overlays (Ollama, custom cron, external + * database) and `up` recreates services without them. The set is, in order of + * preference: + * + * 1. the files `docker compose ls` recorded for the project, minus any that no + * longer exist, as long as the base file survives, + * 2. `COMPOSE_FILE` from the install's `.env`, split on `COMPOSE_PATH_SEPARATOR` + * (default: the OS path-list separator, as Compose does) and resolved against + * the install directory, when it includes the base file, + * 3. the base file plus `docker-compose.override.yml` when that file exists. + */ +export function composeFileSet({ + baseFile, + dir, + recordedFiles = [], +}: { + baseFile: string + dir: string + recordedFiles?: readonly string[] +}): ComposeFileSet { + const base = path.resolve(baseFile) + const warnings: string[] = [] + + const recorded = existingFiles(recordedFiles, 'was recorded for this stack', warnings) + if (recorded.some((file) => path.resolve(file) === base)) return { files: recorded, warnings } + + const envPath = path.join(dir, '.env') + const env = existsSync(envPath) + ? parseEnv(readFileSync(envPath, 'utf8')) + : new Map() + const configured = env.get('COMPOSE_FILE') + if (configured) { + const separator = env.get('COMPOSE_PATH_SEPARATOR') || path.delimiter + const listed = configured + .split(separator) + .map((entry) => entry.trim()) + .filter(Boolean) + .map((entry) => path.resolve(dir, entry)) + const files = existingFiles(listed, `is listed in COMPOSE_FILE in ${envPath}`, warnings) + if (files.includes(base)) return { files, warnings } + warnings.push( + `COMPOSE_FILE in ${envPath} does not include an existing ${path.basename(baseFile)}; ignoring it` + ) + } + + const override = path.join(dir, COMPOSE_OVERRIDE_FILE) + return { files: existsSync(override) ? [baseFile, override] : [baseFile], warnings } +} + +/** + * The `COMPOSE_FILE` value that reproduces `files` for the install in `dir`: + * paths relative to it, joined with `separator` (the install's + * `COMPOSE_PATH_SEPARATOR`, else the OS path-list separator Compose defaults to). + * Saving it keeps overlays once `docker compose down` erases the record of them. + */ +export function composeFileEnvValue( + files: readonly string[], + dir: string, + separator: string = path.delimiter +): string { + return files.map((file) => path.relative(dir, file) || '.').join(separator) +} + +/** Expands a Compose file set into its `-f` arguments. */ +export function composeFileArgs(files: readonly string[]): string[] { + return files.flatMap((file) => ['-f', file]) +} diff --git a/packages/sim-setup/src/configuration-sources.ts b/packages/sim-setup/src/configuration-sources.ts index a07565472b1..b61cbe42a7a 100644 --- a/packages/sim-setup/src/configuration-sources.ts +++ b/packages/sim-setup/src/configuration-sources.ts @@ -7,6 +7,7 @@ import { DEPLOYMENT_CONFIGURATION_KEYS, } from '@sim/deployment-config/env-capabilities' import { toRecordOrNull } from '@sim/utils/object' +import { parseComposeProjects } from './compose-project' import { isPlaceholder, parseEnv, ROOT, SHARED_KEYS } from './env-files' export type ConfigurationSourceKind = 'dev' | 'compose' | 'helm' @@ -315,25 +316,6 @@ export function parseDockerInspectEnvironment(output: string): Map file.trim()) - .filter(Boolean) - if (files.length === 0) return null - projects.push({ name, configFiles: files }) - } - return projects -} - /** Reads `docker compose config --format json` and returns the resolved app environment. */ export function parseComposeConfigEnvironment(output: string): Map | null { const parsed = toRecordOrNull(parseJson(output)) @@ -658,7 +640,10 @@ function discoverComposeProjects( if (info.status !== 0) return { projects: [] } const listed = runSafely(runner, 'docker', ['compose', 'ls', '-a', '--format', 'json'], root) if (listed.status !== 0) return { projects: [] } - const projects = parseComposeProjects(listed.stdout) + const projects = parseComposeProjects(listed.stdout)?.map(({ name, files }) => ({ + name, + configFiles: files, + })) if (!projects) throw new Error('Docker Compose returned an invalid project list') const discovered: DiscoveredComposeProject[] = [] diff --git a/packages/sim-setup/src/feature-setup.test.ts b/packages/sim-setup/src/feature-setup.test.ts index 85e85993545..1e0888cbd35 100644 --- a/packages/sim-setup/src/feature-setup.test.ts +++ b/packages/sim-setup/src/feature-setup.test.ts @@ -2,7 +2,17 @@ import { SANDBOX_CAPABILITY, validateCapabilityFieldInput, } from '@sim/deployment-config/env-capabilities' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' + +const { mockSelect } = vi.hoisted(() => ({ mockSelect: vi.fn() })) + +vi.mock('./prompter', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, select: mockSelect } +}) + +import { SANDBOX_SETUP, type SetupDeployment } from './capability-config' +import { promptCapabilitySetup } from './capability-setup' import type { ConfigurationSource } from './configuration-sources' import { resolveFeatureSetupDestination } from './feature-setup' @@ -72,3 +82,32 @@ describe('sandbox capability setup', () => { ).toContain('immutable E2B build reference') }) }) + +describe('sandbox providers offered per deployment', () => { + async function offeredSandboxProviders( + deployment: SetupDeployment, + current: Record = {} + ): Promise { + mockSelect.mockReset() + mockSelect.mockResolvedValue('disabled') + await promptCapabilitySetup(SANDBOX_SETUP, new Map(Object.entries(current)), { deployment }) + const [{ options }] = mockSelect.mock.calls[0] as [{ options: { value: string }[] }] + return options.map((option) => option.value) + } + + it('does not offer Kubernetes sandboxes to a Compose install', async () => { + expect(await offeredSandboxProviders('compose')).not.toContain('kubernetes') + }) + + it('keeps Kubernetes sandboxes for source checkouts', async () => { + expect(await offeredSandboxProviders('development')).toContain('kubernetes') + }) + + it('still lists Kubernetes on Compose while it is the configured provider', async () => { + const offered = await offeredSandboxProviders('compose', { + SANDBOX_PROVIDER: 'kubernetes', + SANDBOX_K8S_RUNTIME_CLASS: 'gvisor', + }) + expect(offered).toContain('kubernetes') + }) +}) diff --git a/packages/sim-setup/src/feature-setup.ts b/packages/sim-setup/src/feature-setup.ts index 5fbe3e2d8fd..98b6a332fda 100644 --- a/packages/sim-setup/src/feature-setup.ts +++ b/packages/sim-setup/src/feature-setup.ts @@ -7,6 +7,7 @@ import { getCapabilitySetup, getOAuthClientSetupFields, SETUP_FEATURES, + type SetupDeployment, type SetupFeatureId, } from './capability-config' import { promptCapabilitySetup } from './capability-setup' @@ -137,7 +138,7 @@ export interface FeatureSetupDestination { source: ConfigurationSource target: Extract vars: Map - containerized: boolean + deployment: SetupDeployment } /** Resolves the one effective configuration this checkout can safely update. */ @@ -176,7 +177,7 @@ export function resolveFeatureSetupDestination( source, target: source.kind === 'compose' ? 'root' : 'sim', vars: source.values, - containerized: source.kind === 'compose', + deployment: source.kind === 'compose' ? 'compose' : 'development', } } @@ -192,7 +193,7 @@ export async function runFeatureSetup(feature: string, args: readonly string[]): if (capabilitySetup) { const result = await promptCapabilitySetup(capabilitySetup, vars, { - containerized: destination.containerized, + deployment: destination.deployment, }) values = result.values remove = result.remove @@ -214,7 +215,7 @@ export async function runFeatureSetup(feature: string, args: readonly string[]): const label = SETUP_FEATURES.find((item) => item.id === feature)?.label p.outro( theme.accent( - destination.containerized + destination.deployment === 'compose' ? `${label} written to .env. Recreate the app container for it to take effect.` : `${label} configured.` ) diff --git a/packages/sim-setup/src/index.ts b/packages/sim-setup/src/index.ts index 73c76f6e328..16a5f75abb1 100644 --- a/packages/sim-setup/src/index.ts +++ b/packages/sim-setup/src/index.ts @@ -10,18 +10,19 @@ const SETUP_FEATURES = 'email | storage | sandbox | jobs | knowledge | knowledge-embeddings | chat | llm | integration ' const USAGE = `Usage: - sim-setup [--quick] [--dir ] [--mode compose|dev|k8s] + sim-setup [--quick] [--dir ] [--mode compose|dev|k8s] [--url ] sim-setup config show configured capabilities and integrations sim-setup add configure ${SETUP_FEATURES} sim-setup desktop [--url ] install the macOS desktop app against this deployment sim-setup doctor [--fix] [--json] check your setup sim-setup start | stop | restart bring your install up / down / cycle - sim-setup update pull/rebuild and apply Compose images + sim-setup update [--yes] pull/rebuild and apply Compose images sim-setup status show what's installed and healthy sim-setup logs follow logs sim-setup down remove containers (data kept) sim-setup reset archive .env + wipe managed data +--url sets the public origin a Compose install is served at (default http://localhost:3000). Note: dev and k8s modes require a Sim source checkout.` async function main(): Promise { @@ -62,13 +63,13 @@ async function main(): Promise { if (invocation.kind === 'lifecycle') { const { runLifecycle } = await import('./lifecycle') - await runLifecycle(invocation.command) + await runLifecycle(invocation.command, { yes: invocation.yes }) return } if (invocation.kind === 'wizard') { const { runWizard } = await import('./wizard') - await runWizard({ quick: invocation.quick, mode: invocation.mode }) + await runWizard({ quick: invocation.quick, mode: invocation.mode, url: invocation.url }) return } } diff --git a/packages/sim-setup/src/lifecycle-overlays.test.ts b/packages/sim-setup/src/lifecycle-overlays.test.ts new file mode 100644 index 00000000000..bbacfbb182f --- /dev/null +++ b/packages/sim-setup/src/lifecycle-overlays.test.ts @@ -0,0 +1,65 @@ +import { readFileSync, rmSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { afterAll, describe, expect, it, vi } from 'vitest' + +const { stackDir, mockSpawnSync } = vi.hoisted(() => { + const { mkdtempSync } = require('node:fs') as typeof import('node:fs') + const { tmpdir } = require('node:os') as typeof import('node:os') + const { join } = require('node:path') as typeof import('node:path') + return { stackDir: mkdtempSync(join(tmpdir(), 'sim-setup-down-')), mockSpawnSync: vi.fn() } +}) + +vi.mock('node:child_process', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, spawnSync: mockSpawnSync } +}) + +vi.mock('./context', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, SETUP_CONTEXT: { kind: 'standalone', root: stackDir, existing: true } } +}) + +import { runLifecycle } from './lifecycle' + +afterAll(() => rmSync(stackDir, { recursive: true, force: true })) + +describe('a standalone stack started with an overlay', () => { + it('keeps the overlay when started again after down removed the project', async () => { + const base = path.join(stackDir, 'docker-compose.prod.yml') + const overlay = path.join(stackDir, 'docker-compose.ollama.yml') + writeFileSync(base, 'services:\n simstudio:\n image: ghcr.io/simstudioai/simstudio\n') + writeFileSync(overlay, 'services:\n ollama:\n image: ollama/ollama\n') + writeFileSync(path.join(stackDir, '.env'), 'COMPOSE_PROJECT_NAME=sim-overlay\n') + let projects = [ + { Name: 'sim-overlay', Status: 'running(6)', ConfigFiles: `${base},${overlay}` }, + ] + const upCalls: string[][] = [] + mockSpawnSync.mockImplementation((command: string, args: string[]) => { + if (command !== 'docker' || args[0] !== 'compose') + return { status: 1, stdout: '', stderr: '' } + if (args[1] === 'ls') return { status: 0, stdout: JSON.stringify(projects), stderr: '' } + if (args.includes('up')) upCalls.push(args) + return { status: 0, stdout: '', stderr: '' } + }) + + await runLifecycle('start') + projects = [] + await runLifecycle('start') + + expect(upCalls).toHaveLength(2) + expect(upCalls[1]).toEqual([ + 'compose', + '-p', + 'sim-overlay', + '-f', + base, + '-f', + overlay, + 'up', + '-d', + ]) + expect(readFileSync(path.join(stackDir, '.env'), 'utf8')).toContain( + `COMPOSE_FILE=docker-compose.prod.yml${path.delimiter}docker-compose.ollama.yml` + ) + }) +}) diff --git a/packages/sim-setup/src/lifecycle.test.ts b/packages/sim-setup/src/lifecycle.test.ts index 0bccc8a85ad..59a70602922 100644 --- a/packages/sim-setup/src/lifecycle.test.ts +++ b/packages/sim-setup/src/lifecycle.test.ts @@ -38,6 +38,7 @@ import { type Install, runLifecycle, serviceStatusRows, + uploadsLostOnRecreate, } from './lifecycle' afterAll(() => { @@ -181,3 +182,64 @@ describe('status service rows', () => { ]) }) }) + +describe('Compose operations on a stack started with overlays', () => { + it('passes every recorded Compose file so the overlay services survive', async () => { + rmSync(path.join(fakeRoot, 'apps'), { recursive: true, force: true }) + const stackDir = mkdtempSync(path.join(tmpdir(), 'sim-setup-overlay-')) + const base = path.join(stackDir, 'docker-compose.prod.yml') + const overlay = path.join(stackDir, 'docker-compose.ollama.yml') + writeFileSync(base, 'services:\n simstudio:\n image: ghcr.io/simstudioai/simstudio\n') + writeFileSync(overlay, 'services:\n ollama:\n image: ollama/ollama\n') + const composeCalls: string[][] = [] + mockSpawnSync.mockImplementation((command: string, args: string[]) => { + if (command !== 'docker' || args[0] !== 'compose') + return { status: 1, stdout: '', stderr: '' } + if (args[1] === 'ls') { + const stack = { + Name: 'sim-overlay', + Status: 'running(6)', + ConfigFiles: `${base},${overlay}`, + } + return { status: 0, stdout: JSON.stringify([stack]), stderr: '' } + } + composeCalls.push(args) + return { status: 0, stdout: '', stderr: '' } + }) + + try { + await runLifecycle('stop') + } finally { + rmSync(stackDir, { recursive: true, force: true }) + } + + expect(composeCalls).toEqual([ + ['compose', '-p', 'sim-overlay', '-f', base, '-f', overlay, 'stop'], + ]) + }) +}) + +describe('uploads an update would discard', () => { + const uploadsMount = JSON.stringify([ + { Type: 'volume', Name: 'sim_sim_uploads', Destination: '/app/apps/sim/uploads' }, + ]) + + const legacyFiles = [ + 'C /app', + 'C /app/apps/sim', + 'A /app/apps/sim/uploads', + 'A /app/apps/sim/uploads/workspace/report.pdf', + ].join('\n') + + it.each([ + ['files with no volume at the uploads path, running or stopped', '[]', legacyFiles, true], + ['files on the sim_uploads volume', uploadsMount, '', false], + ['only the empty uploads directory itself', '[]', 'A /app/apps/sim/uploads', false], + ['changes elsewhere in the container', '[]', 'A /tmp/scratch', false], + ['a container whose changes could not be read, with no volume', '[]', null, true], + ['a container whose changes could not be read, with the volume', uploadsMount, null, false], + ['mounts that could not be read', null, legacyFiles, false], + ])('%s', (_, mounts, changes, atRisk) => { + expect(uploadsLostOnRecreate(mounts, changes)).toBe(atRisk) + }) +}) diff --git a/packages/sim-setup/src/lifecycle.ts b/packages/sim-setup/src/lifecycle.ts index de013cf98b7..48558848869 100644 --- a/packages/sim-setup/src/lifecycle.ts +++ b/packages/sim-setup/src/lifecycle.ts @@ -1,6 +1,7 @@ import { spawnSync } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' +import { toRecordOrNull } from '@sim/utils/object' import { ensureProductionComposeFile } from './compose-asset' import { choosePostgresPassword, @@ -8,7 +9,13 @@ import { postgresUser, reportPostgresPasswordChoice, } from './compose-database' -import { legacyComposeProjectName } from './compose-project' +import { + composeFileArgs, + composeFileEnvValue, + composeFileSet, + legacyComposeProjectName, + listComposeProjects, +} from './compose-project' import { directoryOverride, resolveSetupContextAtRoot, SETUP_CONTEXT } from './context' import { DB_CONTAINER, type Detection, REDIS_CONTAINER, runDetection } from './detect' import { archiveEnvFile, archiveFile, parseEnv, ROOT, upsertEnv, writeEnvFile } from './env-files' @@ -18,7 +25,7 @@ import { forwardCommands, isLocalKubeContext } from './modes/k8s' import { httpHealth } from './probes' import * as p from './prompter' import { glyph, theme } from './theme' -import { APP_SIGNUP_URL, APP_URL } from './urls' +import { APP_URL, configuredAppUrl, signupUrl } from './urls' const REALTIME_HEALTH = 'http://localhost:3002/health' const POSTGRES_VOLUME = 'sim-postgres-data' @@ -153,11 +160,13 @@ function dockerRun(args: string[], failMessage: string, cwd: string = ROOT): voi export interface ComposeInstall { kind: 'compose' - /** Absolute path to the compose file Docker recorded for the project. */ + /** Absolute path to the Sim compose file Docker recorded for the project. */ file: string /** Directory the stack was brought up from — every compose op runs here. */ dir: string project: string + /** Every file Docker recorded for the project, overlays included, in `-f` order. */ + recordedFiles?: string[] } interface DevInstall { kind: 'dev' @@ -172,12 +181,6 @@ interface K8sInstall { } export type Install = ComposeInstall | DevInstall | K8sInstall -interface ComposeProject { - Name: string - Status: string - ConfigFiles: string -} - /** * Markers that a compose file is actually Sim's: the published app image * (docker-compose.prod.yml) or the app Dockerfile this repo builds @@ -216,27 +219,16 @@ function isSimComposeFile(file: string): boolean { * wherever it was started from. */ function composeInstalls(): ComposeInstall[] { - const raw = dockerText(['compose', 'ls', '-a', '--format', 'json']) - if (!raw) return [] - let projects: ComposeProject[] - try { - projects = JSON.parse(raw) - } catch { - return [] - } const installs: ComposeInstall[] = [] - for (const project of projects) { - // ConfigFiles is a comma-separated list when a stack was started with -f more than once. - const file = (project.ConfigFiles ?? '') - .split(',') - .map((entry) => entry.trim()) - .find(isSimComposeFile) + for (const project of listComposeProjects()) { + const file = project.files.find(isSimComposeFile) if (!file) continue installs.push({ kind: 'compose', file, dir: path.dirname(file), - project: project.Name, + project: project.name, + recordedFiles: project.files, }) } return installs @@ -264,6 +256,44 @@ export function composeInstallFromDirectory( } } +/** Installs whose file-set warnings were already shown, so each prints once per run. */ +const warnedInstalls = new WeakSet() + +/** The Compose files an op on `install` applies, overlays included. */ +function installComposeFiles(install: ComposeInstall): string[] { + const { files, warnings } = composeFileSet({ + baseFile: install.file, + dir: install.dir, + recordedFiles: install.recordedFiles, + }) + if (!warnedInstalls.has(install)) { + warnedInstalls.add(install) + for (const warning of warnings) p.log.warn(warning) + } + return files +} + +/** + * `docker compose down` removes the project, and with it the record of which + * overlays it ran with, so the next `start` would rebuild from the base file + * alone. Saving a multi-file set as `COMPOSE_FILE` in the install's `.env` + * keeps it; a `COMPOSE_FILE` the operator already set is left alone. + */ +function persistComposeFiles(install: ComposeInstall, files: readonly string[]): void { + if (files.length <= 1) return + const envPath = path.join(install.dir, '.env') + const content = existsSync(envPath) ? readFileSync(envPath, 'utf8') : '' + const vars = parseEnv(content) + if (vars.get('COMPOSE_FILE')) return + const value = composeFileEnvValue( + files, + install.dir, + vars.get('COMPOSE_PATH_SEPARATOR') || undefined + ) + writeEnvFile(envPath, upsertEnv(content, 'COMPOSE_FILE', value)) + p.log.step(`Saved COMPOSE_FILE=${value} in ${envPath} so these files apply after down`) +} + /** * Compose args for an op on a detected install. `-p` is not optional: without it * Compose re-derives the project from the working directory, and that name is @@ -276,7 +306,13 @@ export function composeInstallFromDirectory( * the file's own relative paths (build contexts, env_file) resolve against it. */ function composeArgs(install: ComposeInstall, ...verb: string[]): string[] { - return ['compose', '-p', install.project, '-f', install.file, ...verb] + return [ + 'compose', + '-p', + install.project, + ...composeFileArgs(installComposeFiles(install)), + ...verb, + ] } /** @@ -292,7 +328,7 @@ function ensureComposePostgresPassword(install: ComposeInstall): void { if (!choice) return writeEnvFile(envPath, upsertEnv(content, 'POSTGRES_PASSWORD', choice.value)) reportPostgresPasswordChoice(choice, { - compose: `docker compose -p ${install.project} -f ${install.file}`, + compose: ['docker', ...composeArgs(install)].join(' '), user: postgresUser(vars.get('POSTGRES_USER')), envPath, }) @@ -394,16 +430,26 @@ function k8sReachHints(context: string): string { ].join('\n') } +/** Where an operator opens a Compose install: its configured public URL, not the probe origin. */ +function composeSignupUrl(install: ComposeInstall): string { + const envPath = path.join(install.dir, '.env') + const vars = existsSync(envPath) + ? parseEnv(readFileSync(envPath, 'utf8')) + : new Map() + return signupUrl(configuredAppUrl(vars)) +} + function start(install: Install): void { if (install.kind === 'compose') { ensureComposePostgresPassword(install) + persistComposeFiles(install, installComposeFiles(install)) const spin = p.spinner() spin.start('Starting containers…') dockerRun(composeArgs(install, 'up', '-d'), 'docker compose up failed', install.dir) spin.stop('Containers up') p.note( [ - `open ${APP_SIGNUP_URL}`, + `open ${composeSignupUrl(install)}`, 'follow logs: npx sim-setup logs', 'stop: npx sim-setup stop', ].join('\n'), @@ -466,7 +512,7 @@ function restart(install: Install): void { spin.start('Restarting containers…') dockerRun(composeArgs(install, 'restart'), 'docker compose restart failed', install.dir) spin.stop('Containers restarted') - p.note(`open ${APP_SIGNUP_URL}`, 'Running') + p.note(`open ${composeSignupUrl(install)}`, 'Running') return } if (install.kind === 'dev') { @@ -495,7 +541,86 @@ export function refreshComposeFileForUpdate(file: string, dir: string): string { return ensureProductionComposeFile(resolveSetupContextAtRoot(dir)) } -function update(install: Install): void { +/** Where the app keeps local uploads inside its container. */ +const UPLOADS_PATH = '/app/apps/sim/uploads' + +/** + * Whether recreating the app container would discard uploads: it holds files + * in its own filesystem at the uploads path, with no volume mounted there, as + * on installs that predate the `sim_uploads` volume. `mountsJson` is the + * container's `{{json .Mounts}}`, and `filesystemChanges` its `docker diff`, + * which works on stopped containers and never lists files on a mounted volume. + * Unreadable mounts say nothing about the container; an unreadable diff on an + * unmounted path is treated as at risk, since the files cannot be ruled out. + */ +export function uploadsLostOnRecreate( + mountsJson: string | null, + filesystemChanges: string | null +): boolean { + if (mountsJson === null) return false + let mounts: unknown + try { + mounts = JSON.parse(mountsJson) + } catch { + return false + } + if (!Array.isArray(mounts)) return false + if (mounts.some((mount) => toRecordOrNull(mount)?.Destination === UPLOADS_PATH)) return false + if (filesystemChanges === null) return true + return filesystemChanges + .split('\n') + .some((line) => /^[AC] /.test(line) && line.slice(2).startsWith(`${UPLOADS_PATH}/`)) +} + +/** Inspects the app container of `install`, running or stopped, for uploads an update would discard. */ +function inContainerUploadsAtRisk(install: ComposeInstall): boolean { + const container = dockerText([ + 'ps', + '-a', + '-q', + '--filter', + `label=com.docker.compose.project=${install.project}`, + '--filter', + 'label=com.docker.compose.service=simstudio', + ])?.split('\n')[0] + if (!container) return false + return uploadsLostOnRecreate( + dockerText(['inspect', '--format', '{{json .Mounts}}', container]), + dockerText(['diff', container]) + ) +} + +/** + * Stops an update that would discard in-container uploads until the operator + * has copied them out, printing the copy commands. Returns whether to continue. + */ +async function confirmUploadsCopied(install: ComposeInstall, yes: boolean): Promise { + if (!inContainerUploadsAtRisk(install)) return true + const compose = ['docker', ...composeArgs(install)].join(' ') + p.note( + [ + 'This app container stores uploads in its own filesystem. Updating recreates it', + 'and mounts the sim_uploads volume, so those files would be lost. Copy them out first:', + ` ${compose} cp simstudio:${UPLOADS_PATH} ./uploads-backup`, + 'then, after the update:', + ` ${compose} cp ./uploads-backup/. simstudio:${UPLOADS_PATH}`, + ` ${compose} exec -u 0 simstudio chown -R nextjs:nodejs ${UPLOADS_PATH}`, + ].join('\n'), + 'Uploads inside the app container' + ) + if (yes) return true + if (!process.stdin.isTTY) { + throw new SetupError('update would discard uploads stored inside the app container.', [ + `copy them out as shown above, then re-run ${theme.command('npx sim-setup update --yes')}`, + ]) + } + return p.confirm({ + message: 'Have you copied the uploads out? Continuing discards the ones in the container.', + initialValue: false, + }) +} + +async function update(install: Install, yes: boolean): Promise { if (install.kind === 'dev') { throw new SetupError('update is only available for Docker Compose installs.', [ 'update the source checkout with git, run bun install, then restart bun run dev:full', @@ -507,9 +632,22 @@ function update(install: Install): void { ]) } + if (!(await confirmUploadsCopied(install, yes))) { + p.log.info('Update cancelled.') + return + } const mode = getComposeUpdateMode(install.file) - if (mode === 'pull') install.file = refreshComposeFileForUpdate(install.file, install.dir) + if (mode === 'pull') { + const previous = path.resolve(install.file) + install.file = refreshComposeFileForUpdate(install.file, install.dir) + install.recordedFiles = install.recordedFiles?.map((file) => + path.resolve(file) === previous ? install.file : file + ) + } ensureComposePostgresPassword(install) + const files = installComposeFiles(install) + p.log.step(`Applying ${files.join(', ')}`) + persistComposeFiles(install, files) const spin = p.spinner() if (mode === 'pull') { spin.start('Pulling configured Sim images…') @@ -564,6 +702,7 @@ async function down(install: Install): Promise { return } if (install.kind === 'compose') { + persistComposeFiles(install, installComposeFiles(install)) dockerRun(composeArgs(install, 'down'), 'docker compose down failed', install.dir) p.log.step('Containers removed (volumes kept)') return @@ -618,7 +757,13 @@ async function reset(install: Install | null): Promise { // Tear down before archiving: Compose reads the required secrets from `.env` // even for `down`, and a failed teardown should leave the config in place. if (install?.kind === 'compose') { - dockerRun(composeArgs(install, 'down', '-v'), 'docker compose down -v failed', install.dir) + // Only the base file: an overlay's volumes (an Ollama model cache, say) are + // not Sim's data to wipe. Its containers go as orphans; its volumes stay. + dockerRun( + ['compose', '-p', install.project, '-f', install.file, 'down', '-v', '--remove-orphans'], + 'docker compose down -v failed', + install.dir + ) p.log.step('Containers and volumes removed') } else if (install?.kind === 'dev') { const names = managedNames(install) @@ -709,7 +854,10 @@ async function status(): Promise { console.log(` realtime (:3002) ${realtime ? glyph.pass : glyph.fail}`) } -export async function runLifecycle(command: LifecycleCommand): Promise { +export async function runLifecycle( + command: LifecycleCommand, + { yes = false }: { yes?: boolean } = {} +): Promise { if (command === 'status') return status() const installs = scopeInstallsToInvocation(detectInstalls(await runDetection())) @@ -730,7 +878,7 @@ export async function runLifecycle(command: LifecycleCommand): Promise { case 'restart': return restart(install) case 'update': - return update(install) + return update(install, yes) case 'logs': return showLogs(install) case 'down': diff --git a/packages/sim-setup/src/modes/compose.ts b/packages/sim-setup/src/modes/compose.ts index 0b9792c6204..a6ff21220b8 100644 --- a/packages/sim-setup/src/modes/compose.ts +++ b/packages/sim-setup/src/modes/compose.ts @@ -10,7 +10,15 @@ import { postgresUser, reportPostgresPasswordChoice, } from '../compose-database' -import { legacyComposeProjectName, standaloneComposeProjectName } from '../compose-project' +import { + type ComposeProjectRecord, + composeFileArgs, + composeFileEnvValue, + composeFileSet, + legacyComposeProjectName, + listComposeProjects, + standaloneComposeProjectName, +} from '../compose-project' import { SETUP_CONTEXT } from '../context' import type { Detection } from '../detect' import { ensureDocker } from '../docker' @@ -31,48 +39,64 @@ import { promptUnlocks, } from '../steps' import { glyph, theme } from '../theme' -import { APP_SIGNUP_URL, APP_URL } from '../urls' +import { APP_URL, configuredAppUrl, parsePublicUrl, signupUrl } from '../urls' const REQUIRED_PORTS = [3000, 3002] as const -interface ComposeProject { - Name: string - ConfigFiles: string -} - -/** Returns the active Compose project already associated with this exact configuration file. */ -function activeComposeProject(composeFile: string): string | null { - const result = spawnSync('docker', ['compose', 'ls', '-a', '--format', 'json'], { - encoding: 'utf8', - }) - if (result.status !== 0) return null - - let projects: ComposeProject[] - try { - projects = JSON.parse(result.stdout) - } catch { - return null - } +/** + * Returns the active Compose project already associated with this exact + * configuration file, with every file it was started with. + */ +function activeComposeProject(composeFile: string): ComposeProjectRecord | null { const target = path.resolve(composeFile) return ( - projects.find((project) => - project.ConfigFiles.split(',').some((file) => path.resolve(file.trim()) === target) - )?.Name ?? null + listComposeProjects().find((project) => + project.files.some((file) => path.resolve(file) === target) + ) ?? null ) } /** Builds a Compose command pinned to the selected standalone project when one is present. */ function composeArgs( - composeFile: string, + composeFiles: readonly string[], project: string | undefined, ...args: string[] ): string[] { - return ['compose', ...(project ? ['-p', project] : []), '-f', composeFile, ...args] + return ['compose', ...(project ? ['-p', project] : []), ...composeFileArgs(composeFiles), ...args] } /** Formats the pinned Compose prefix used in copyable diagnostics. */ -function composeCommand(composeFile: string, project: string | undefined): string { - return `docker compose${project ? ` -p ${project}` : ''} -f ${composeFile}` +function composeCommand(composeFiles: readonly string[], project: string | undefined): string { + return ['docker', ...composeArgs(composeFiles, project)].join(' ') +} + +/** + * The public origin to write as `NEXT_PUBLIC_APP_URL`, or `null` to remove it + * so Compose falls back to http://localhost:3000. A `--url` flag wins; Custom + * setup asks; Quick keeps whatever is configured (`undefined`). + */ +async function resolvePublicUrl( + flagUrl: string | undefined, + quick: boolean, + existing: string | undefined +): Promise { + if (flagUrl) return flagUrl + if (quick) return undefined + const answer = await p.text({ + message: `Public URL (blank = ${APP_URL})`, + placeholder: 'https://sim.example.com', + initialValue: existing ?? '', + defaultValue: '', + validate: (value) => { + if (!value?.trim()) return undefined + const parsed = parsePublicUrl(value) + return 'error' in parsed ? parsed.error : undefined + }, + }) + if (!answer.trim()) return null + const parsed = parsePublicUrl(answer) + if ('error' in parsed) throw new SetupError(parsed.error) + return parsed.url } /** @@ -81,8 +105,11 @@ function composeCommand(composeFile: string, project: string | undefined): strin * now — a project with only db/redis up publishes neither app port, so those * still need the conflict check. */ -function composePublishedPorts(composeFile: string, project: string | undefined): Set { - const ids = spawnSync('docker', composeArgs(composeFile, project, 'ps', '-q'), { +function composePublishedPorts( + composeFiles: readonly string[], + project: string | undefined +): Set { + const ids = spawnSync('docker', composeArgs(composeFiles, project, 'ps', '-q'), { cwd: ROOT, encoding: 'utf8', }) @@ -114,7 +141,7 @@ function composePublishedPorts(composeFile: string, project: string | undefined) * is fatal here: compose can't come up while the ports are held. */ async function ensureComposePortsFree( - composeFile: string, + composeFiles: readonly string[], project: string | undefined ): Promise { // A port this stack already publishes is not a conflict — `docker compose up @@ -123,7 +150,7 @@ async function ensureComposePortsFree( // Skip only the ports this project actually publishes: leftover db/redis // containers must not wave through a foreign process sitting on 3000, which // would otherwise surface as a raw compose bind error instead of the prompt. - const ours = composePublishedPorts(composeFile, project) + const ours = composePublishedPorts(composeFiles, project) const toCheck = REQUIRED_PORTS.filter((port) => !ours.has(port)) if (toCheck.length < REQUIRED_PORTS.length) { const skipped = REQUIRED_PORTS.filter((port) => ours.has(port)) @@ -135,11 +162,16 @@ async function ensureComposePortsFree( `free the ports, then re-run: ${theme.command('npx sim-setup')}`, `see what holds them: ${theme.command('lsof -nP -iTCP:3000 -sTCP:LISTEN')}`, `stop a container publishing them: ${theme.command('docker ps')}`, - `compose file in play: ${composeFile}`, + `compose files in play: ${composeFiles.join(', ')}`, ]) } -export async function runComposeMode(detection: Detection, quick: boolean): Promise { +/** Runs the Compose wizard and returns the public origin the install is configured for. */ +export async function runComposeMode( + detection: Detection, + quick: boolean, + flagUrl?: string +): Promise { await ensureDocker(true) const variant = SETUP_CONTEXT.kind === 'standalone' || quick @@ -167,18 +199,36 @@ export async function runComposeMode(detection: Detection, quick: boolean): Prom const values = collectSecrets(root) const remove = new Set() const configuredComposeProject = root.vars.get('COMPOSE_PROJECT_NAME') - const activeProject = - SETUP_CONTEXT.kind === 'standalone' ? activeComposeProject(composeFile) : null - if (configuredComposeProject && activeProject && configuredComposeProject !== activeProject) { + const recordedProject = activeComposeProject(composeFile) + const activeProject = SETUP_CONTEXT.kind === 'standalone' ? recordedProject : null + const { files: composeFiles, warnings: composeFileWarnings } = composeFileSet({ + baseFile: composeFile, + dir: ROOT, + recordedFiles: recordedProject?.files, + }) + for (const warning of composeFileWarnings) p.log.warn(warning) + if (composeFiles.length > 1 && !root.vars.get('COMPOSE_FILE')) { + values.COMPOSE_FILE = composeFileEnvValue( + composeFiles, + ROOT, + root.vars.get('COMPOSE_PATH_SEPARATOR') || undefined + ) + p.log.step(`Saving COMPOSE_FILE=${values.COMPOSE_FILE} so these files apply after down`) + } + if ( + configuredComposeProject && + activeProject && + configuredComposeProject !== activeProject.name + ) { throw new SetupError( - `COMPOSE_PROJECT_NAME is ${configuredComposeProject}, but ${composeFile} is running as project ${activeProject}.`, + `COMPOSE_PROJECT_NAME is ${configuredComposeProject}, but ${composeFile} is running as project ${activeProject.name}.`, ['stop the active project or restore its name in .env before running setup again'] ) } const composeProject = SETUP_CONTEXT.kind === 'standalone' ? (configuredComposeProject ?? - activeProject ?? + activeProject?.name ?? (SETUP_CONTEXT.existing ? legacyComposeProjectName(ROOT) : standaloneComposeProjectName(ROOT))) @@ -200,22 +250,25 @@ export async function runComposeMode(detection: Detection, quick: boolean): Prom const copilotKey = await promptCopilotKey(root.vars.get('COPILOT_API_KEY')) if (copilotKey) values.COPILOT_API_KEY = copilotKey Object.assign(values, chatFlagValues(copilotKey)) - Object.assign(values, await promptLlmKeys(detection, !quick)) + Object.assign(values, await promptLlmKeys(detection, !quick, 'compose')) + const publicUrl = await resolvePublicUrl(flagUrl, quick, root.vars.get('NEXT_PUBLIC_APP_URL')) + if (publicUrl) values.NEXT_PUBLIC_APP_URL = publicUrl + else if (publicUrl === null) remove.add('NEXT_PUBLIC_APP_URL') + const appUrl = publicUrl === undefined ? configuredAppUrl(root.vars) : (publicUrl ?? APP_URL) const stagedVars = new Map(root.vars) for (const [key, value] of Object.entries(values)) stagedVars.set(key, value) - const embeddings = await promptKnowledgeEmbeddings(stagedVars, { containerized: true }) + const embeddings = await promptKnowledgeEmbeddings(stagedVars, { deployment: 'compose' }) if (embeddings) { stageCapabilitySetupTransition(stagedVars, values, remove, embeddings) } if (!quick) { const storage = await promptCapabilitySetup(STORAGE_SETUP, stagedVars, { - containerized: true, + deployment: 'compose', }) stageCapabilitySetupTransition(stagedVars, values, remove, storage) - const appUrl = root.vars.get('NEXT_PUBLIC_APP_URL') ?? APP_URL Object.assign(values, await promptSignInProviders(stagedVars, appUrl)) const email = await promptCapabilitySetup(EMAIL_SETUP, stagedVars, { - containerized: true, + deployment: 'compose', }) stageCapabilitySetupTransition(stagedVars, values, remove, email) const security = await promptSecurity(root.vars) @@ -234,13 +287,13 @@ export async function runComposeMode(detection: Detection, quick: boolean): Prom p.log.step('Wrote .env (compose reads it for variable substitution)') if (postgresPassword) { reportPostgresPasswordChoice(postgresPassword, { - compose: composeCommand(composeFile, composeProject), + compose: composeCommand(composeFiles, composeProject), user: postgresUser(root.vars.get('POSTGRES_USER')), envPath: root.path, }) } - const validation = spawnSync('docker', composeArgs(composeFile, composeProject, 'config'), { + const validation = spawnSync('docker', composeArgs(composeFiles, composeProject, 'config'), { cwd: ROOT, encoding: 'utf8', }) @@ -250,11 +303,11 @@ export async function runComposeMode(detection: Detection, quick: boolean): Prom ) } - await ensureComposePortsFree(composeFile, composeProject) + await ensureComposePortsFree(composeFiles, composeProject) - const command = composeCommand(composeFile, composeProject) + const command = composeCommand(composeFiles, composeProject) p.log.step(`Running ${command} up -d`) - const result = spawnSync('docker', composeArgs(composeFile, composeProject, 'up', '-d'), { + const result = spawnSync('docker', composeArgs(composeFiles, composeProject, 'up', '-d'), { cwd: ROOT, stdio: 'inherit', }) @@ -277,9 +330,10 @@ export async function runComposeMode(detection: Detection, quick: boolean): Prom `${!appHealthy ? 'the app (:3000)' : 'realtime (:3002)'} never answered its health check.`, [ `follow the logs: ${theme.command(`${command} logs -f`)}`, - `first boots on slow disks can exceed the wait — if containers are still starting, just wait and open ${APP_SIGNUP_URL}`, + `first boots on slow disks can exceed the wait — if containers are still starting, just wait and open ${signupUrl(appUrl)}`, ] ) } spin.stop('App and realtime are healthy') + return appUrl } diff --git a/packages/sim-setup/src/modes/dev.ts b/packages/sim-setup/src/modes/dev.ts index fdab5cd329f..87c89a94061 100644 --- a/packages/sim-setup/src/modes/dev.ts +++ b/packages/sim-setup/src/modes/dev.ts @@ -102,7 +102,7 @@ export async function runDevMode( const copilotKey = await promptCopilotKey(simAfter.vars.get('COPILOT_API_KEY')) if (copilotKey) values.COPILOT_API_KEY = copilotKey Object.assign(values, chatFlagValues(copilotKey)) - Object.assign(values, await promptLlmKeys(detection, !quick)) + Object.assign(values, await promptLlmKeys(detection, !quick, 'development')) // Redis is required: quick adopts or starts one with no questions, custom // walks the where-should-it-live ladder. @@ -114,7 +114,7 @@ export async function runDevMode( const stagedVars = new Map(simAfter.vars) for (const [key, value] of Object.entries(values)) stagedVars.set(key, value) - const embeddings = await promptKnowledgeEmbeddings(stagedVars, { containerized: false }) + const embeddings = await promptKnowledgeEmbeddings(stagedVars, { deployment: 'development' }) if (embeddings) { stageCapabilitySetupTransition(stagedVars, values, remove, embeddings) } @@ -122,7 +122,7 @@ export async function runDevMode( if (!quick) { for (const setup of [JOBS_SETUP, STORAGE_SETUP, EMAIL_SETUP] as const) { const transition = await promptCapabilitySetup(setup, stagedVars, { - containerized: false, + deployment: 'development', }) stageCapabilitySetupTransition(stagedVars, values, remove, transition) } diff --git a/packages/sim-setup/src/modes/k8s.ts b/packages/sim-setup/src/modes/k8s.ts index cbb0043950e..b13a2d6a8b9 100644 --- a/packages/sim-setup/src/modes/k8s.ts +++ b/packages/sim-setup/src/modes/k8s.ts @@ -15,7 +15,7 @@ import { promptKnowledgeEmbeddings, } from '../steps' import { glyph, theme } from '../theme' -import { APP_SIGNUP_URL, APP_URL } from '../urls' +import { APP_URL, signupUrl } from '../urls' const RELEASE = 'sim-dev' const NAMESPACE = 'sim-dev' @@ -376,7 +376,7 @@ export async function runK8sMode(detection: Detection): Promise { if (existing) appEnv[key] = existing } const remove = new Set() - const embeddings = await promptKnowledgeEmbeddings(stagedVars, { containerized: true }) + const embeddings = await promptKnowledgeEmbeddings(stagedVars, { deployment: 'kubernetes' }) if (embeddings) { stageCapabilitySetupTransition(stagedVars, appEnv, remove, embeddings) } @@ -434,7 +434,7 @@ export async function runK8sMode(detection: Detection): Promise { p.note( [ - `open ${APP_SIGNUP_URL} (needs both forwards below)`, + `open ${signupUrl()} (needs both forwards below)`, `pods: kubectl --context ${shq(context)} -n ${NAMESPACE} get pods`, `app logs: kubectl --context ${shq(context)} -n ${NAMESPACE} logs deploy/${RELEASE}-app --tail 50`, // Both, always: the app alone loads but the editor's socket has nothing to @@ -472,7 +472,7 @@ export function forwardCommands(context: string): string[] { */ async function offerPortForward(context: string): Promise { const forward = await p.confirm({ - message: `Port-forward now so you can open ${APP_SIGNUP_URL}?`, + message: `Port-forward now so you can open ${signupUrl()}?`, initialValue: true, }) if (!forward) { diff --git a/packages/sim-setup/src/steps.ts b/packages/sim-setup/src/steps.ts index a9ffee642b7..35fcad6dc7e 100644 --- a/packages/sim-setup/src/steps.ts +++ b/packages/sim-setup/src/steps.ts @@ -5,7 +5,7 @@ import { } from '@sim/deployment-config/enterprise-features' import { createEgressPolicy } from '@sim/security/egress' import { getErrorMessage } from '@sim/utils/errors' -import { KNOWLEDGE_EMBEDDINGS_SETUP } from './capability-config' +import { KNOWLEDGE_EMBEDDINGS_SETUP, type SetupDeployment } from './capability-config' import { type CapabilitySetupContext, type EnvCapabilitySetupTransition, @@ -151,9 +151,19 @@ export function mothershipOverride(): Record { return { SIM_AGENT_API_URL: agentUrl } } +/** + * The `OLLAMA_URL` for an Ollama found on this host's :11434. Inside a Compose + * container `localhost` is the container itself, so Compose reaches the host + * through the `host.docker.internal` alias its app service declares. + */ +function ollamaUrlFor(deployment: SetupDeployment): string { + return deployment === 'compose' ? 'http://host.docker.internal:11434' : 'http://localhost:11434' +} + export async function promptLlmKeys( detection: Detection, - custom: boolean + custom: boolean, + deployment: SetupDeployment ): Promise> { const values: Record = {} if (detection.shellLlmKeys.length > 0) { @@ -173,7 +183,16 @@ export async function promptLlmKeys( message: 'Ollama is running on :11434 — wire it up for local models?', initialValue: true, }) - if (useOllama) values.OLLAMA_URL = 'http://localhost:11434' + if (useOllama) { + values.OLLAMA_URL = ollamaUrlFor(deployment) + if (deployment === 'compose') { + p.log.info( + theme.muted( + 'On Linux, bind Ollama to the Docker bridge address the app container reaches through host.docker.internal (usually OLLAMA_HOST=172.17.0.1:11434). Ollama has no authentication: listen on 0.0.0.0 only behind a firewall that blocks port 11434 from outside.' + ) + ) + } + } } if (custom && Object.keys(values).length === 0 && detection.shellLlmKeys.length === 0) { p.log.info( diff --git a/packages/sim-setup/src/urls.ts b/packages/sim-setup/src/urls.ts index 7342df84294..2d81591ffdf 100644 --- a/packages/sim-setup/src/urls.ts +++ b/packages/sim-setup/src/urls.ts @@ -9,4 +9,43 @@ export const APP_URL = 'http://localhost:3000' * hunting for a CTA before they can create the first account. Deep-linking to * signup lands them on the one thing they can actually do. */ -export const APP_SIGNUP_URL = `${APP_URL}/signup` +export function signupUrl(appUrl: string = APP_URL): string { + return `${appUrl}/signup` +} + +/** + * Validates a public Sim origin given on the command line or at a prompt and + * returns it without a trailing slash. Sim serves from the root of its origin, + * so a path, query, fragment, or credentials would produce a broken + * `NEXT_PUBLIC_APP_URL`. + */ +export function parsePublicUrl(input: string): { url: string } | { error: string } { + let parsed: URL + try { + parsed = new URL(input.trim()) + } catch { + return { error: `"${input}" is not a URL — expected something like https://sim.example.com` } + } + if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') { + return { error: `the public URL must use http or https, not ${parsed.protocol}` } + } + if (parsed.username || parsed.password) { + return { error: 'the public URL must not contain credentials' } + } + if (parsed.pathname !== '/' || parsed.search || parsed.hash) { + return { error: 'the public URL must be an origin with no path, like https://sim.example.com' } + } + return { url: parsed.origin } +} + +/** + * The public origin an install is configured for, or the local default when + * unset. A value that is not a bare origin is still what the app runs with, so + * it is returned as configured rather than replaced. + */ +export function configuredAppUrl(vars: ReadonlyMap): string { + const configured = vars.get('NEXT_PUBLIC_APP_URL') + if (!configured) return APP_URL + const parsed = parsePublicUrl(configured) + return 'url' in parsed ? parsed.url : configured.trim().replace(/\/+$/, '') +} diff --git a/packages/sim-setup/src/wizard.ts b/packages/sim-setup/src/wizard.ts index d2f869fbbba..14a1fd03e79 100644 --- a/packages/sim-setup/src/wizard.ts +++ b/packages/sim-setup/src/wizard.ts @@ -10,13 +10,15 @@ import { runK8sMode } from './modes/k8s' import { ensurePortsFree } from './ports' import * as p from './prompter' import { glyph, theme } from './theme' -import { APP_SIGNUP_URL } from './urls' +import { signupUrl } from './urls' export type WizardMode = 'compose' | 'dev' | 'k8s' export interface WizardFlags { quick: boolean mode?: WizardMode + /** Public origin for a Compose install, already validated by argument parsing. */ + url?: string } async function handleExistingConfig(detection: Detection): Promise<'continue' | 'doctor'> { @@ -62,6 +64,8 @@ async function selectMode(detection: Detection, flags: WizardFlags): Promise { warnLowSpecs(detection, mode) let startDevNow = false let devScript = 'dev:full' - if (mode === 'compose') await runComposeMode(detection, quick) + let openUrl = signupUrl() + if (mode === 'compose') openUrl = signupUrl(await runComposeMode(detection, quick, flags.url)) else if (mode === 'dev') { const dev = await runDevMode(detection, quick) startDevNow = dev.startNow @@ -171,7 +176,7 @@ export async function runWizard(flags: WizardFlags): Promise { p.note( [ - mode === 'k8s' ? `port-forward, then open ${APP_SIGNUP_URL}` : `open ${APP_SIGNUP_URL}`, + mode === 'k8s' ? `port-forward, then open ${openUrl}` : `open ${openUrl}`, 'manage it: npx sim-setup start · stop · update · status · logs', 'check your setup: npx sim-setup doctor', mode === 'dev' && !startDevNow ? `start Sim: bun run ${devScript}` : null, @@ -183,7 +188,7 @@ export async function runWizard(flags: WizardFlags): Promise { p.outro(theme.accent('Sim is ready.')) if (mode === 'compose' && process.platform === 'darwin') { - spawnSync('open', [APP_SIGNUP_URL], { stdio: 'ignore' }) + spawnSync('open', [openUrl], { stdio: 'ignore' }) } if (startDevNow) { // dev:full binds 3000 (app) and 3002 (realtime) — resolve any conflict