Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(deploy): ship the collab service (image, release, Helm, self-host, make up) (MUL-9775) (#11122)

Jiayuan Zhang8d88e5c71150
diff --git a/.dockerignore b/.dockerignore
index bf9f55035a..b97eb51085 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -35,10 +35,12 @@ coverage
/docs/
*.md
-# Dockerfile.web needs the web workspace and root dependency patch inputs.
-# Default-exclude other app files so they do not enter the build context.
+# Dockerfile.web and Dockerfile.collab need their workspaces and root
+# dependency patch inputs. Default-exclude other app files so they do not
+# enter the build context.
/apps/*
!/apps/web/
+!/apps/collab/
!/apps/mobile
/apps/mobile/*
!/apps/mobile/patches
diff --git a/.env.example b/.env.example
index 76f077e549..746e5b71cd 100644
--- a/.env.example
+++ b/.env.example
@@ -258,6 +258,24 @@ MULTICA_CLOUD_URL=
MULTICA_IMAGE_TAG=latest
MULTICA_BACKEND_IMAGE=ghcr.io/multica-ai/multica-backend
MULTICA_WEB_IMAGE=ghcr.io/multica-ai/multica-web
+MULTICA_COLLAB_IMAGE=ghcr.io/multica-ai/multica-collab
+
+# Live doc co-editing (optional; needs FF_DOCS_V1=true)
+# Docs work without it: each edit saves through the API. With it, everyone in
+# a doc edits it together in real time. For the self-host stack, set a long
+# random secret (openssl rand -hex 32) and start the collab service, both at
+# once: a secret with no collab service leaves editors waiting 8s per doc
+# before they fall back to saving through the API.
+# COLLAB_SECRET=
+# COMPOSE_PROFILES=collab
+#
+# `make up` starts collab and generates its own secret, so leave these
+# commented out for local development; a COLLAB_SECRET set here replaces the
+# generated one.
+#
+# Only needed when the CDN domain the backend reports cannot be derived:
+# CLOUDFRONT_DOMAIN with S3 storage, empty with local uploads.
+# MULTICA_CDN_DOMAIN=
# Email
# Two delivery options - only one needs to be configured:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index c51dbad99b..554cdb8ee6 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -354,8 +354,123 @@ jobs:
docker buildx imagetools inspect \
ghcr.io/${{ github.repository_owner }}/multica-web:${{ steps.meta.outputs.version }}
+ docker-collab-build:
+ needs: verify
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - platform: linux/amd64
+ runs-on: ubuntu-latest
+ - platform: linux/arm64
+ runs-on: ubuntu-24.04-arm
+ runs-on: ${{ matrix.runs-on }}
+ steps:
+ - name: Prepare
+ run: |
+ platform=${{ matrix.platform }}
+ echo "PLATFORM_PAIR=${platform//\//-}" >> "$GITHUB_ENV"
+
+ - name: Checkout
+ uses: actions/checkout@v4
+
+ - name: Compute collab image labels
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ghcr.io/${{ github.repository_owner }}/multica-collab
+ labels: |
+ org.opencontainers.image.title=Multica Collab
+ org.opencontainers.image.description=Multica live co-editing service for Workspace Docs
+
+ - name: Setup Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Login to GHCR
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Build and push by digest
+ id: build
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: Dockerfile.collab
+ pull: true
+ platforms: ${{ matrix.platform }}
+ labels: ${{ steps.meta.outputs.labels }}
+ cache-from: type=gha,scope=release-collab-${{ env.PLATFORM_PAIR }}
+ cache-to: type=gha,mode=max,scope=release-collab-${{ env.PLATFORM_PAIR }}
+ outputs: type=image,name=ghcr.io/${{ github.repository_owner }}/multica-collab,push-by-digest=true,name-canonical=true,push=true
+
+ - name: Export digest
+ run: |
+ mkdir -p /tmp/digests
+ digest="${{ steps.build.outputs.digest }}"
+ touch "/tmp/digests/${digest#sha256:}"
+
+ - name: Upload digest
+ uses: actions/upload-artifact@v4
+ with:
+ name: digests-collab-${{ env.PLATFORM_PAIR }}
+ path: /tmp/digests/*
+ if-no-files-found: error
+ retention-days: 1
+
+ docker-collab-merge:
+ needs: [verify, docker-collab-build]
+ runs-on: ubuntu-latest
+ concurrency:
+ group: release-docker-collab-${{ github.ref }}
+ cancel-in-progress: true
+ steps:
+ - name: Download digests
+ uses: actions/download-artifact@v4
+ with:
+ path: /tmp/digests
+ pattern: digests-collab-*
+ merge-multiple: true
+
+ - name: Setup Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Compute collab image tags
+ id: meta
+ uses: docker/metadata-action@v5
+ with:
+ images: ghcr.io/${{ github.repository_owner }}/multica-collab
+ flavor: |
+ latest=false
+ tags: |
+ type=raw,value=latest,enable=${{ needs.verify.outputs.is_stable == 'true' }}
+ type=raw,value=${{ needs.verify.outputs.tag_name }}
+ type=sha,prefix=sha-
+
+ - name: Login to GHCR
+ uses: docker/login-action@v3
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Create manifest list and push
+ working-directory: /tmp/digests
+ run: |
+ docker buildx imagetools create \
+ $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
+ $(printf 'ghcr.io/${{ github.repository_owner }}/multica-collab@sha256:%s ' *)
+
+ - name: Inspect image
+ run: |
+ docker buildx imagetools inspect \
+ ghcr.io/${{ github.repository_owner }}/multica-collab:${{ steps.meta.outputs.version }}
+
helm-chart:
- needs: [verify, docker-backend-merge, docker-web-merge]
+ # The chart's collab image defaults to the same tag, so it waits for it too.
+ needs: [verify, docker-backend-merge, docker-web-merge, docker-collab-merge]
if: github.repository_owner == 'multica-ai'
runs-on: ubuntu-latest
concurrency:
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 8a7ca0c835..b099c96811 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -344,8 +344,8 @@ An environment is the database, ports, CLI profile and processes that belong to
one checkout. It is a named object: it can be listed, inspected and deleted.
```bash
-make up # start this checkout's environment (api + web)
-make up C=api,web,daemon # choose the components
+make up # start this checkout's environment (api + collab + web)
+make up C=api,collab,web,daemon # choose the components
make status # what is running, and whether it is yours
make list # every environment on this machine
make down # stop the processes, keep the data
@@ -354,8 +354,11 @@ make destroy # stop, then drop the database and free the slot
make gc # collect expired environments or ones whose checkout is gone
```
-Components are `api` (Go backend), `web` (Next.js), `daemon` (agent daemon) and
-`desktop` (Electron). Selecting any of them implies `api`. `make up` is
+Components are `api` (Go backend), `collab` (live doc co-editing), `web`
+(Next.js), `daemon` (agent daemon) and `desktop` (Electron). Selecting any of
+them implies `api`. `collab` gets its own port and a secret generated for the
+environment, and the API is wired to it only while it runs, so leaving it out
+(`make up C=api,web`) just turns docs back to saving through the API. `make up` is
idempotent: re-running it against a live environment reuses the database, the
profile and any component already healthy.
diff --git a/Dockerfile.collab b/Dockerfile.collab
new file mode 100644
index 0000000000..b523262f6e
--- /dev/null
+++ b/Dockerfile.collab
@@ -0,0 +1,52 @@
+# Live co-editing service for Workspace Docs (apps/collab).
+#
+# It runs its TypeScript sources with tsx and imports the editor schema from
+# @multica/views, so the image carries the workspace sources it reaches plus
+# their production dependencies, installed from the repository root.
+
+# --- Dependencies + sources ---
+# Same pinned Node as Dockerfile.web; bump them together.
+FROM node:22.23.4-alpine AS deps
+
+WORKDIR /app
+
+COPY pnpm-lock.yaml pnpm-workspace.yaml package.json .npmrc ./
+# Root pnpm patchedDependencies is read even without the mobile workspace.
+COPY apps/mobile/patches/ apps/mobile/patches/
+COPY apps/collab/package.json apps/collab/
+COPY packages/views/package.json packages/views/
+COPY packages/core/package.json packages/core/
+COPY packages/ui/package.json packages/ui/
+
+RUN corepack enable && \
+ PNPM_VERSION="$(node -p 'require("./package.json").packageManager')" && \
+ corepack prepare "$PNPM_VERSION" --activate
+RUN pnpm install --frozen-lockfile --prod --filter "@multica/collab..."
+
+COPY apps/collab/ apps/collab/
+COPY packages/views/ packages/views/
+COPY packages/core/ packages/core/
+COPY packages/ui/ packages/ui/
+
+# --- Runtime ---
+FROM node:22.23.4-alpine AS runner
+
+# Alpine openssl security fixes (CVE-2026-63073, CVE-2026-75803).
+# Remove once the pinned node image includes libssl3 >= 3.5.8-r0.
+RUN apk add --no-cache "libcrypto3>=3.5.8-r0" "libssl3>=3.5.8-r0"
+
+ENV NODE_ENV=production
+ENV COLLAB_PORT=8095
+
+WORKDIR /app
+COPY --from=deps /app ./
+# Ship the license and attribution notices with the image (LICENSE condition 1b)
+COPY LICENSE NOTICE ./
+
+USER node
+WORKDIR /app/apps/collab
+
+EXPOSE 8095
+
+# One process, so SIGTERM reaches the handler that stores open docs.
+CMD ["node", "--import", "tsx", "src/index.ts"]
diff --git a/Makefile b/Makefile
index 24942ae187..71442aba13 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: help makehelp dev server daemon cli multica build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree remove-worktree db-up db-down db-drop db-reset selfhost selfhost-start selfhost-build selfhost-build-start selfhost-stop up down status list destroy gc env-exec api-dev web-dev desktop-dev
+.PHONY: help makehelp dev server daemon cli multica build test migrate-up migrate-down sqlc seed clean setup start stop check worktree-env setup-main start-main stop-main check-main setup-worktree start-worktree stop-worktree check-worktree remove-worktree db-up db-down db-drop db-reset selfhost selfhost-start selfhost-build selfhost-build-start selfhost-stop up down status list destroy gc env-exec api-dev web-dev collab-dev desktop-dev
MAIN_ENV_FILE ?= .env
WORKTREE_ENV_FILE ?= .env.worktree
@@ -70,7 +70,7 @@ endef
##@ Help
help: ## Show available make targets and common local workflows
- @awk 'BEGIN {FS = ":.*## "; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nQuick start:\n \033[36mmake up\033[0m Start this checkout'"'"'s environment (C=api,web,daemon,desktop)\n \033[36mmake status\033[0m Show what is running, and prove it is yours\n \033[36mmake down\033[0m Stop it again, keeping the database (C=daemon stops just that)\n \033[36mmake check\033[0m Run the full local verification pipeline\n\nCheckout modes:\n Main checkout uses \033[36m.env\033[0m\n Worktrees use \033[36m.env.worktree\033[0m (generate with \033[36mmake worktree-env\033[0m)\n\n"} \
+ @awk 'BEGIN {FS = ":.*## "; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nQuick start:\n \033[36mmake up\033[0m Start this checkout'"'"'s environment (C=api,collab,web,daemon,desktop)\n \033[36mmake status\033[0m Show what is running, and prove it is yours\n \033[36mmake down\033[0m Stop it again, keeping the database (C=daemon stops just that)\n \033[36mmake check\033[0m Run the full local verification pipeline\n\nCheckout modes:\n Main checkout uses \033[36m.env\033[0m\n Worktrees use \033[36m.env.worktree\033[0m (generate with \033[36mmake worktree-env\033[0m)\n\n"} \
/^##@/ {printf "\n\033[1m%s\033[0m\n", substr($$0, 5); next} \
/^[a-zA-Z0-9_.-]+:.*## / {printf " \033[36m%-18s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
@@ -159,14 +159,14 @@ selfhost-stop: ## Stop the self-hosted Docker Compose stack
# One verb per lifecycle step, shared by humans and agents. C= picks the
# components; ARGS= forwards anything else to the script.
#
-# make up api + web
-# make up C=api,web,daemon add the agent daemon
+# make up api + collab + web
+# make up C=api,collab,web,daemon add the agent daemon
# make up C=desktop Electron against this environment's backend
# make up C=desktop ARGS=--cdp ...signed in, with a DevTools port for Playwright
# make up ARGS=--ephemeral agent-owned, expires, collected by `make gc`
-# make down C=daemon stop only the daemon; api and web keep running
+# make down C=daemon stop only the daemon; everything else keeps running
-up: ## Start this checkout's environment (C=api,web,daemon,desktop; default api,web)
+up: ## Start this checkout's environment (C=api,collab,web,daemon,desktop; default api,collab,web)
@bash scripts/dev-env.sh up $(if $(C),--components $(C)) $(ARGS)
down: ## Stop this environment's processes, keeping its database and profile (C=daemon,...; default all)
@@ -199,6 +199,9 @@ api-dev: ## Run only the Go backend for the current env file
web-dev: ## Run only the Next.js dev server for the current env file
pnpm dev:web
+collab-dev: ## Run only the live doc co-editing service (needs COLLAB_SECRET, MULTICA_API_URL)
+ pnpm dev:collab
+
desktop-dev: ## Run only the Electron desktop app for the current env file
pnpm dev:desktop
diff --git a/SELF_HOSTING.md b/SELF_HOSTING.md
index 785f341a1e..7ffd62821d 100644
--- a/SELF_HOSTING.md
+++ b/SELF_HOSTING.md
@@ -9,6 +9,7 @@ Deploy Multica on your own infrastructure in minutes.
| **Backend** | REST API + WebSocket server | Go (single binary) |
| **Frontend** | Web application | Next.js 16 |
| **Database** | Primary data store | PostgreSQL 17 (`pgcrypto` + `pg_trgm`) |
+| **Collab** (optional) | Live co-editing for Docs | Node.js (Hocuspocus + Yjs) |
Each user who runs AI agents locally also installs the **`multica` CLI** and runs the **agent daemon** on their own machine.
@@ -94,6 +95,8 @@ Once ready:
> **Note:** If you prefer to run the Docker Compose steps manually, see [Manual Docker Compose Setup](#manual-docker-compose-setup) below.
+> **Live doc co-editing (optional):** Docs are off until `FF_DOCS_V1=true` is set in `.env`, and then save through the API on their own. To let everyone in a doc edit it together in real time, add `COLLAB_SECRET=<output of openssl rand -hex 32>` and `COMPOSE_PROFILES=collab` to `.env` and run `make selfhost` again; this starts the `collab` service. Set both together. See [Advanced Configuration → Live Doc Co-editing](SELF_HOSTING_ADVANCED.md#live-doc-co-editing-optional).
+
### Step 2 — Log In
Open http://localhost:3000 in your browser. The Docker self-host stack defaults to `APP_ENV=production` (set in `docker-compose.selfhost.yml`), and there is no fixed verification code by default. Pick one of the following to log in:
@@ -190,6 +193,7 @@ The chart creates the following resources in the target namespace:
- `multica-postgres` — `pgvector/pgvector:pg17` backed by a 10Gi PVC
- `multica-backend` — Go API/WS server. Backed by a 5Gi `ReadWriteOnce` uploads PVC by default; set `backend.uploads.persistence.enabled=false` when you have configured S3 (`backend.config.s3Bucket`) and don't want the chart to declare the PVC at all.
- `multica-frontend` — Next.js standalone server
+- `multica-collab` — live doc co-editing, only when `collab.enabled=true` (see [Live doc co-editing](#live-doc-co-editing-optional))
- Two `Ingress` resources: one for the web host, one for the backend host
- `multica-config` ConfigMap (rendered from `values.yaml`)
@@ -267,6 +271,21 @@ helm install multica deploy/helm/multica -n multica
If the backend has to reach services whose certificates come from an internal CA, such as a self-hosted Gitea, set `backend.extraCACerts.configMap`. See [Advanced Configuration → Private CA Certificates](SELF_HOSTING_ADVANCED.md#private-ca-certificates-optional).
+#### Live doc co-editing (optional)
+
+`collab.enabled` is off by default, and the chart then renders exactly what it did before. Turning it on runs one `multica-collab` pod and points the backend at it. Add the shared secret to `multica-secrets` first, then upgrade:
+
+```bash
+kubectl -n multica patch secret multica-secrets --type=merge \
+ -p "{\"stringData\":{\"COLLAB_SECRET\":\"$(openssl rand -hex 32)\"}}"
+helm upgrade multica oci://ghcr.io/multica-ai/charts/multica \
+ --version <chart-version> \
+ -n multica \
+ -f my-values.yaml --set collab.enabled=true
+```
+
+The Ingress needs nothing new: editors open `/collab` on the backend host, which the backend forwards to collab, with the same WebSocket settings as `/ws`. Collab always runs as exactly one replica and is replaced with `Recreate`, because each open doc lives in that one process's memory. `collab.config.cdnDomain` is derived from the backend's storage settings; set it only if links to uploaded files stop turning into file cards in live docs.
+
Watch the pods come up:
```bash
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index 66ad3e522c..42c9680ed8 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -207,6 +207,28 @@ rewrite configuration. Its backend fallback therefore accepts
`BACKEND_PORT` → `API_PORT` → `SERVER_PORT` → `8080`, while an explicit
`REMOTE_API_URL` or `NEXT_PUBLIC_API_URL` still takes priority.
+### Live Doc Co-editing (Optional)
+
+Docs (`FF_DOCS_V1=true`) work without it: every edit saves through the API. The `collab` service adds live co-editing, where everyone in a doc sees each other's cursors and changes as they type, and the editor shows **Live**. Editors never connect to it directly. They open a WebSocket to `/collab` on the backend, the same way they reach `/ws`, and the backend forwards it.
+
+| Variable | Service | Description |
+|----------|---------|-------------|
+| `COLLAB_SECRET` | backend, collab | Shared secret that signs editor tickets and authenticates the backend and collab to each other. Generate with `openssl rand -hex 32`. In `docker-compose.selfhost.yml`, setting it is also what points the backend at the collab service. |
+| `COMPOSE_PROFILES` | Compose | Add `collab` to start the collab service (`COMPOSE_PROFILES=collab`). |
+| `COLLAB_INTERNAL_URL` | backend | Where the backend reaches collab. Compose derives `http://collab:8095` from `COLLAB_SECRET`; set it only when collab runs elsewhere. Live editing is off whenever this or `COLLAB_SECRET` is empty. |
+| `MULTICA_API_URL` | collab | Where collab reaches the backend to load and store docs. Compose sets `http://backend:8080`. |
+| `MULTICA_CDN_DOMAIN` | collab | Must equal the CDN domain the backend reports, so links to uploaded files become the same nodes the editor makes. That is `CLOUDFRONT_DOMAIN` with S3 storage, and the host of `LOCAL_UPLOAD_BASE_URL` with local uploads (empty when that is unset). Compose fills it from `CLOUDFRONT_DOMAIN`. |
+| `MULTICA_COLLAB_IMAGE` | Compose | Image repository; the tag follows `MULTICA_IMAGE_TAG`. |
+
+Turn it on with both lines in `.env`, then `make selfhost` (or `docker compose -f docker-compose.selfhost.yml up -d`):
+
+```bash
+COLLAB_SECRET=<openssl rand -hex 32>
+COMPOSE_PROFILES=collab
+```
+
+Set them together. A secret with no running collab service leaves every editor waiting 8 seconds before it falls back to saving through the API. Run exactly one collab instance: each open doc lives in that one process's memory. A reverse proxy needs a `/collab` route next to `/ws` (see [Reverse Proxy](#reverse-proxy)).
+
### Private CA Certificates (Optional)
The backend checks the TLS certificates of the HTTPS services it calls against
@@ -531,7 +553,7 @@ In production, put a reverse proxy in front of both the backend and frontend to
```
multica.example.com {
# WebSocket route — must come before the catch-all
- @multica_ws path /ws /ws/*
+ @multica_ws path /ws /ws/* /collab
handle @multica_ws {
reverse_proxy localhost:8080 {
flush_interval -1
@@ -553,7 +575,7 @@ app.example.com {
}
api.example.com {
- @multica_ws path /ws /ws/*
+ @multica_ws path /ws /ws/* /collab
handle @multica_ws {
reverse_proxy localhost:8080 {
flush_interval -1
@@ -564,7 +586,7 @@ api.example.com {
}
```
-Two non-obvious bits inside the `/ws` block are worth calling out — both are common reasons real-time updates "stop working" on a Caddy-fronted self-host:
+Two non-obvious bits inside the `/ws` block are worth calling out — both are common reasons real-time updates "stop working" on a Caddy-fronted self-host. `/collab` is the WebSocket for [live doc co-editing](#live-doc-co-editing-optional) and needs the same treatment; it is harmless when collab is off:
- **`path /ws /ws/*` (not `/ws*`)** — bare `handle /ws` is an exact match, so future path variants under `/ws/` fall through to the frontend block. The obvious shortcut `handle /ws*` overcorrects in the other direction: Caddy's `*` is a glob without a path-segment boundary, so it would also catch unrelated paths like `/ws-foo`, which is a legitimate workspace URL (only the exact slug `ws` is reserved). Listing `/ws` and `/ws/*` explicitly covers both real cases without overreach.
- **`flush_interval -1`** — disables response buffering so WebSocket frames are forwarded as soon as they arrive. Without it, frames can sit behind Caddy's default flush window, which looks like delayed comments, missing typing indicators, or "comments only appear after a page refresh."
@@ -614,6 +636,16 @@ server {
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
+
+ # Live doc co-editing (same WebSocket settings)
+ location /collab {
+ proxy_pass http://localhost:8080;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_read_timeout 86400;
+ }
}
```
@@ -664,7 +696,7 @@ NEXT_PUBLIC_WS_URL= # empty
REMOTE_API_URL=http://backend:8080 # upstream for /v1, /api, /auth and /health
```
-Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because the frontend forwards `/v1`, `/api`, `/auth` and `/health` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a `/ws` block to the frontend vhost that reaches the backend directly:
+Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because the frontend forwards `/v1`, `/api`, `/auth` and `/health` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a block for `/ws` and `/collab` to the frontend vhost that reaches the backend directly:
```nginx
# Add to the app.example.com server block above
@@ -676,6 +708,16 @@ location /ws {
proxy_set_header Host $host;
proxy_read_timeout 86400;
}
+
+# Live doc co-editing (same WebSocket settings)
+location /collab {
+ proxy_pass http://localhost:8080;
+ proxy_http_version 1.1;
+ proxy_set_header Upgrade $http_upgrade;
+ proxy_set_header Connection "upgrade";
+ proxy_set_header Host $host;
+ proxy_read_timeout 86400;
+}
```
See [WebSocket for LAN / Non-localhost Access](#websocket-for-lan--non-localhost-access) for why the rewrites cannot carry the `Upgrade` handshake.
diff --git a/apps/docs/content/docs/developers/contributing.fr.mdx b/apps/docs/content/docs/developers/contributing.fr.mdx
index 79bde6823c..e292b54f7c 100644
--- a/apps/docs/content/docs/developers/contributing.fr.mdx
+++ b/apps/docs/content/docs/developers/contributing.fr.mdx
@@ -70,7 +70,7 @@ Les différents worktrees partagent le conteneur PostgreSQL, pas la base de donn
### Workflow complet
```bash
-make up # Démarre l'environnement de ce checkout (C=api,web,daemon,desktop)
+make up # Démarre l'environnement de ce checkout (C=api,collab,web,daemon,desktop)
make status # Affiche ce qui tourne et prouve qu'il s'agit de cet environnement
make list # Liste tous les environnements de cette machine
make down # Arrête les processus, conserve la base de données
diff --git a/apps/docs/content/docs/developers/contributing.mdx b/apps/docs/content/docs/developers/contributing.mdx
index 438c1fa146..6e13c52a8a 100644
--- a/apps/docs/content/docs/developers/contributing.mdx
+++ b/apps/docs/content/docs/developers/contributing.mdx
@@ -70,7 +70,7 @@ Different worktrees share the PostgreSQL container, not the database. Do not sta
### Full workflow
```bash
-make up # Start this checkout's environment (C=api,web,daemon,desktop)
+make up # Start this checkout's environment (C=api,collab,web,daemon,desktop)
make status # Show what is running and prove it is this environment
make list # List every environment on this machine
make down # Stop the processes, keep the database
diff --git a/deploy/helm/multica/templates/_helpers.tpl b/deploy/helm/multica/templates/_helpers.tpl
index f83504c4f8..60fb2c2bbf 100644
--- a/deploy/helm/multica/templates/_helpers.tpl
+++ b/deploy/helm/multica/templates/_helpers.tpl
@@ -24,6 +24,33 @@ under the kustomize layout when installed as `helm install multica ...`.
{{ .Release.Name }}-postgres
{{- end -}}
+{{- define "multica.collab.fullname" -}}
+{{ .Release.Name }}-collab
+{{- end -}}
+
+{{/*
+"true" when the collab service is deployed, otherwise empty. `helm upgrade
+--reuse-values` from a chart without the collab section carries no such key.
+*/}}
+{{- define "multica.collab.enabled" -}}
+{{- if (default dict .Values.collab).enabled -}}true{{- end -}}
+{{- end -}}
+
+{{/*
+The CDN domain the backend reports (Storage.CdnDomain): CLOUDFRONT_DOMAIN with
+S3, otherwise the host of LOCAL_UPLOAD_BASE_URL.
+*/}}
+{{- define "multica.collab.cdnDomain" -}}
+{{- $config := default dict (default dict .Values.collab).config -}}
+{{- if $config.cdnDomain -}}
+{{ $config.cdnDomain }}
+{{- else if .Values.backend.config.s3Bucket -}}
+{{ .Values.backend.config.cloudfrontDomain }}
+{{- else if .Values.backend.config.localUploadBaseUrl -}}
+{{ (urlParse .Values.backend.config.localUploadBaseUrl).hostname }}
+{{- end -}}
+{{- end -}}
+
{{/*
DATABASE_URL pieced together from the postgres service + Secret values.
The $(VAR) syntax is resolved by the kubelet from the container's env, so
diff --git a/deploy/helm/multica/templates/backend.yaml b/deploy/helm/multica/templates/backend.yaml
index bf34da6977..9a8cab0dc7 100644
--- a/deploy/helm/multica/templates/backend.yaml
+++ b/deploy/helm/multica/templates/backend.yaml
@@ -1,6 +1,7 @@
{{- $backendImageTag := default .Chart.AppVersion .Values.images.backend.tag -}}
{{- /* `helm upgrade --reuse-values` from a chart without extraCACerts carries no such key. */ -}}
{{- $extraCACerts := (default dict .Values.backend.extraCACerts).configMap -}}
+{{- $collabEnabled := include "multica.collab.enabled" . -}}
{{- if .Values.backend.uploads.persistence.enabled -}}
apiVersion: v1
kind: PersistentVolumeClaim
@@ -74,7 +75,7 @@ spec:
name: {{ .Release.Name }}-config
- secretRef:
name: {{ .Values.existingSecret }}
- {{- if or (not .Values.postgres.external.enabled) $extraCACerts }}
+ {{- if or (not .Values.postgres.external.enabled) $extraCACerts $collabEnabled }}
env:
{{- if not .Values.postgres.external.enabled }}
- name: DATABASE_URL
@@ -87,6 +88,18 @@ spec:
- name: SSL_CERT_DIR
value: /etc/ssl/certs:/etc/multica/ca-certs
{{- end }}
+ {{- if $collabEnabled }}
+ - name: COLLAB_INTERNAL_URL
+ value: {{ printf "http://%s:8095" (include "multica.collab.fullname" .) | quote }}
+ # Optional so a missing key leaves live editing off instead of
+ # keeping the API from starting.
+ - name: COLLAB_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.existingSecret }}
+ key: COLLAB_SECRET
+ optional: true
+ {{- end }}
{{- end }}
{{- if or .Values.backend.uploads.persistence.enabled $extraCACerts }}
volumeMounts:
diff --git a/deploy/helm/multica/templates/collab.yaml b/deploy/helm/multica/templates/collab.yaml
new file mode 100644
index 0000000000..29e2f1208b
--- /dev/null
+++ b/deploy/helm/multica/templates/collab.yaml
@@ -0,0 +1,95 @@
+{{- if include "multica.collab.enabled" . -}}
+{{- $image := default dict .Values.images.collab -}}
+{{- $collabImageTag := default .Chart.AppVersion $image.tag -}}
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: {{ include "multica.collab.fullname" . }}
+ labels:
+ {{- include "multica.labels" . | nindent 4 }}
+ app.kubernetes.io/component: collab
+spec:
+ # Every open doc lives in this process's memory, so a second replica would
+ # hold its own copy of the same doc. Recreate keeps a rollout from running
+ # two at once.
+ replicas: 1
+ strategy:
+ type: Recreate
+ selector:
+ matchLabels:
+ app.kubernetes.io/name: multica
+ app.kubernetes.io/instance: {{ .Release.Name }}
+ app.kubernetes.io/component: collab
+ template:
+ metadata:
+ annotations:
+ # Same lookup as the backend: both must roll when COLLAB_SECRET rotates.
+ checksum/secret: {{ (lookup "v1" "Secret" .Release.Namespace .Values.existingSecret).data | toYaml | sha256sum }}
+ labels:
+ {{- include "multica.labels" . | nindent 8 }}
+ app.kubernetes.io/component: collab
+ spec:
+ # On SIGTERM the service takes up to 15s to store every open doc.
+ terminationGracePeriodSeconds: 30
+ containers:
+ - name: collab
+ image: "{{ default "ghcr.io/multica-ai/multica-collab" $image.repository }}:{{ $collabImageTag }}"
+ imagePullPolicy: {{ default "IfNotPresent" $image.pullPolicy }}
+ ports:
+ - containerPort: 8095
+ name: http
+ env:
+ - name: COLLAB_PORT
+ value: "8095"
+ - name: MULTICA_API_URL
+ value: {{ printf "http://%s:8080" (include "multica.backend.fullname" .) | quote }}
+ - name: MULTICA_CDN_DOMAIN
+ value: {{ include "multica.collab.cdnDomain" . | quote }}
+ - name: COLLAB_SECRET
+ valueFrom:
+ secretKeyRef:
+ name: {{ .Values.existingSecret }}
+ key: COLLAB_SECRET
+ readinessProbe:
+ httpGet:
+ path: /health
+ port: 8095
+ initialDelaySeconds: 5
+ periodSeconds: 10
+ livenessProbe:
+ httpGet:
+ path: /health
+ port: 8095
+ initialDelaySeconds: 30
+ periodSeconds: 30
+ {{- with .Values.collab.resources }}
+ resources:
+ {{- toYaml . | nindent 12 }}
+ {{- end }}
+ {{- with .Values.collab.affinity }}
+ affinity:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.collab.tolerations }}
+ tolerations:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "multica.collab.fullname" . }}
+ labels:
+ {{- include "multica.labels" . | nindent 4 }}
+ app.kubernetes.io/component: collab
+spec:
+ type: ClusterIP
+ selector:
+ app.kubernetes.io/name: multica
+ app.kubernetes.io/instance: {{ .Release.Name }}
+ app.kubernetes.io/component: collab
+ ports:
+ - port: 8095
+ targetPort: 8095
+ name: http
+{{- end }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index ca0fc258d9..99b3c1cf94 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -13,6 +13,12 @@ images:
# Empty defaults to Chart.appVersion. Set explicitly to override.
tag: ""
pullPolicy: IfNotPresent
+ # Only pulled when collab.enabled=true.
+ collab:
+ repository: ghcr.io/multica-ai/multica-collab
+ # Empty defaults to Chart.appVersion. Set explicitly to override.
+ tag: ""
+ pullPolicy: IfNotPresent
postgres:
repository: pgvector/pgvector
tag: pg17
@@ -226,6 +232,39 @@ frontend:
affinity: {}
tolerations: []
+# -----------------------------------------------------------------------------
+# Collab (live co-editing for Workspace Docs, apps/collab)
+# -----------------------------------------------------------------------------
+# Off by default. When off, docs are edited one save at a time through the API.
+#
+# Before enabling, add COLLAB_SECRET to existingSecret. The backend and the
+# collab service sign editor tickets and authenticate each other with it:
+# kubectl -n <namespace> patch secret multica-secrets --type merge \
+# -p "{\"stringData\":{\"COLLAB_SECRET\":\"$(openssl rand -hex 32)\"}}"
+#
+# Editors connect to /collab on the backend, which forwards the WebSocket to
+# this service, so ingress needs nothing beyond what /ws already uses.
+collab:
+ enabled: false
+ config:
+ # Must match the CDN domain the backend reports, or links to uploaded files
+ # in a doc render differently in the live editor. Empty derives it the way
+ # the backend does: backend.config.cloudfrontDomain when s3Bucket is set,
+ # otherwise the host of backend.config.localUploadBaseUrl.
+ cdnDomain: ""
+ # Always one replica: every open doc lives in this process's memory, so a
+ # second replica would hold its own copy of the same doc.
+ resources:
+ requests:
+ cpu: 50m
+ memory: 256Mi
+ limits:
+ cpu: 1000m
+ memory: 1Gi
+ # Standard Kubernetes scheduling constraints for the collab Deployment.
+ affinity: {}
+ tolerations: []
+
# -----------------------------------------------------------------------------
# Ingress
# -----------------------------------------------------------------------------
diff --git a/docker-compose.selfhost.build.yml b/docker-compose.selfhost.build.yml
index dd069256ef..632681b950 100644
--- a/docker-compose.selfhost.build.yml
+++ b/docker-compose.selfhost.build.yml
@@ -19,3 +19,9 @@ services:
dockerfile: Dockerfile.web
args:
NEXT_PUBLIC_APP_VERSION: dev
+
+ collab:
+ image: multica-collab:dev
+ build:
+ context: .
+ dockerfile: Dockerfile.collab
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 54d3688280..d5f0edb3ff 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -1,4 +1,6 @@
-# Self-hosting Docker Compose — starts PostgreSQL, backend, and frontend.
+# Self-hosting Docker Compose — starts PostgreSQL, backend, and frontend, plus
+# the optional collab service for live doc co-editing (COLLAB_SECRET and
+# COMPOSE_PROFILES=collab in .env; see .env.example).
#
# Services bind to 127.0.0.1 only. For cross-machine or public access, front
# them with a reverse proxy (Caddy / nginx / Cloudflare Tunnel) that terminates
@@ -240,6 +242,34 @@ services:
# Tool steps shown in the streamed reply: auto (default; details in
# private chats, kind of work in groups), off, summary or detail.
MULTICA_TELEGRAM_TOOL_PROGRESS: ${MULTICA_TELEGRAM_TOOL_PROGRESS:-}
+ # Workspace Docs is off until FF_DOCS_V1=true. Passed only when set: an
+ # empty FF_ value would pin the flag off instead of leaving the default.
+ FF_DOCS_V1:
+ # Live co-editing for Workspace Docs, served by the optional collab
+ # service below. Setting COLLAB_SECRET turns it on and points the API at
+ # that service; enable the service with COMPOSE_PROFILES=collab.
+ COLLAB_SECRET: ${COLLAB_SECRET:-}
+ COLLAB_INTERNAL_URL: ${COLLAB_INTERNAL_URL:-${COLLAB_SECRET:+http://collab:8095}}
+ restart: unless-stopped
+
+ # Optional: started only with COMPOSE_PROFILES=collab (or --profile collab),
+ # together with COLLAB_SECRET above. Editors reach it through the backend's
+ # /collab WebSocket, so it publishes no port. Every open doc lives in this
+ # process's memory: run exactly one.
+ collab:
+ image: ${MULTICA_COLLAB_IMAGE:-ghcr.io/multica-ai/multica-collab}:${MULTICA_IMAGE_TAG:-latest}
+ profiles: ["collab"]
+ depends_on:
+ - backend
+ environment:
+ COLLAB_SECRET: ${COLLAB_SECRET:-}
+ MULTICA_API_URL: http://backend:8080
+ COLLAB_PORT: "8095"
+ # Must match the CDN domain the backend reports: CLOUDFRONT_DOMAIN with
+ # S3 storage, empty with local uploads.
+ MULTICA_CDN_DOMAIN: ${MULTICA_CDN_DOMAIN:-${CLOUDFRONT_DOMAIN:-}}
+ # SIGTERM gives it up to 15s to store every open doc.
+ stop_grace_period: 30s
restart: unless-stopped
frontend:
diff --git a/package.json b/package.json
index 42074db696..670bc9cd03 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev:web": "turbo dev --filter=@multica/web",
+ "dev:collab": "pnpm --filter @multica/collab dev",
"dev:docs": "turbo dev --filter=@multica/docs",
"storybook": "pnpm -C apps/storybook storybook",
"dev:desktop": "turbo dev --filter=@multica/desktop",
diff --git a/scripts/agent-environment.sh b/scripts/agent-environment.sh
index a6b5e51cac..b776d7934a 100755
--- a/scripts/agent-environment.sh
+++ b/scripts/agent-environment.sh
@@ -173,7 +173,7 @@ cmd_start() {
trap "finish_start $component \$?" EXIT
[ -f "$BORROWED" ] || flags+=(--ttl "$DEV_ENV_TTL_HOURS")
- bash "$DEV_ENV" up --components "api,$component" ${flags[@]+"${flags[@]}"}
+ bash "$DEV_ENV" up --components "api,collab,$component" ${flags[@]+"${flags[@]}"}
status="$(bash "$DEV_ENV" status --json)"
node -e '
diff --git a/scripts/dev-env.sh b/scripts/dev-env.sh
index 25d9970f2c..bd360046d6 100755
--- a/scripts/dev-env.sh
+++ b/scripts/dev-env.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
# Local development environments as named, listable, deletable objects.
#
-# make up # start this checkout's environment (api + web)
+# make up # start this checkout's environment (api + collab + web)
# make up C=api,web,daemon # pick the components
# make status # what is running, and is it mine
# make list # every environment on this machine
@@ -40,8 +40,8 @@ DEV_CODE_DEFAULT=888888
WORKSPACE_NAME="${MULTICA_DEV_WORKSPACE_NAME:-Dev}"
WORKSPACE_SLUG="${MULTICA_DEV_WORKSPACE_SLUG:-dev}"
-ALL_COMPONENTS="api web daemon desktop"
-DEFAULT_COMPONENTS="api web"
+ALL_COMPONENTS="api collab web daemon desktop"
+DEFAULT_COMPONENTS="api collab web"
# An agent runs with TMPDIR=/tmp/multica-task-<id>, deleted when the run ends.
# Anything the Go toolchain builds there goes with it, so a binary started from
@@ -258,6 +258,10 @@ renderer_port_for_offset() {
printf '%s' "$port"
}
+collab_port_for_offset() {
+ printf '%s' $((14000 + $1))
+}
+
desktop_app_data_root() {
if [ -n "$DEV_DESKTOP_APP_DATA" ]; then
printf '%s' "$DEV_DESKTOP_APP_DATA"
@@ -339,17 +343,19 @@ EOF
# are actually free — the registry alone cannot see a process started before
# this tooling existed.
allocate_offset() {
- local dir=$1 self=${2:-} start i offset backend frontend renderer
+ local dir=$1 self=${2:-} start i offset backend frontend renderer collab
start="$(path_offset "$dir")"
for i in $(seq 0 999); do
offset=$(((start + i) % 1000))
backend=$((18080 + offset))
frontend=$((13000 + offset))
renderer="$(renderer_port_for_offset "$offset")"
+ collab="$(collab_port_for_offset "$offset")"
offset_registered "$offset" "$self" && continue
port_free "$backend" || continue
port_free "$frontend" || continue
port_free "$renderer" || continue
+ port_free "$collab" || continue
printf '%s' "$offset"
return 0
done
@@ -670,12 +676,56 @@ api_stale_reason() {
return 0
}
+# The API forwards editor WebSockets to collab and merges its own doc writes
+# through it, so it is pointed only at a collab this environment runs: one
+# that is down leaves every doc page waiting for a session before it gives up.
+# The API reads the setting once, at startup, so `start_api` records it in
+# api.collab and restarts an API launched with a different one.
+api_collab_file() { printf '%s/api.collab' "$STATE_DIR"; }
+
+api_collab_url() {
+ [ -n "${COLLAB_PORT:-}" ] || return 0
+ if component_selected collab || listener_belongs_to_component collab "$COLLAB_PORT"; then
+ printf 'http://localhost:%s' "$COLLAB_PORT"
+ fi
+ return 0
+}
+
+api_collab_reason() {
+ local recorded
+ recorded="$(cat "$(api_collab_file)" 2>/dev/null || true)"
+ [ "$recorded" != "$1" ] || return 0
+ if [ -n "$1" ]; then
+ printf 'is not connected to collab on :%s' "$COLLAB_PORT"
+ else
+ printf 'points at a collab service that is not running'
+ fi
+}
+
+# Signs editor tickets and authenticates the API and collab to each other.
+# Generated once per environment and kept with its state rather than in the env
+# file, where a self-hosted stack reading the same file would take it as the
+# switch that turns live editing on. A value set in the env file wins.
+collab_secret() {
+ local file="$STATE_DIR/collab.secret"
+ if [ -n "${COLLAB_SECRET:-}" ]; then
+ printf '%s' "$COLLAB_SECRET"
+ return 0
+ fi
+ if [ ! -s "$file" ]; then
+ (umask 077; node -e 'process.stdout.write(require("crypto").randomBytes(32).toString("hex"))' > "$file")
+ fi
+ cat "$file"
+}
+
start_api() {
- local launched_at health waited=0 expected_commit fingerprint reason
+ local launched_at health waited=0 expected_commit fingerprint reason collab_url
expected_commit="$(checkout_commit)"
+ collab_url="$(api_collab_url)"
if health="$(health_json)" && [ -n "$health" ] && component_pid api >/dev/null; then
if api_identity_matches "$health" "$expected_commit"; then
reason="$(api_stale_reason)"
+ [ -n "$reason" ] || reason="$(api_collab_reason "$collab_url")"
if [ -z "$reason" ]; then
record_component_listener api "$BACKEND_PORT" >/dev/null \
|| die "The API listener changed while its identity was being verified. Refusing to reuse it."
@@ -700,8 +750,14 @@ Run 'make down' here first — a leftover instance answers /health with 200 and
# Taken before the compile starts, so an edit made while it runs reads as
# stale next time instead of being assumed compiled in.
fingerprint="$(api_source_fingerprint)"
- launch_detached api make -C "$REPO_ROOT" -s api-dev ENV_FILE="$ENV_FILE"
+ if [ -n "$collab_url" ]; then
+ launch_detached api env COLLAB_INTERNAL_URL="$collab_url" COLLAB_SECRET="$(collab_secret)" \
+ make -C "$REPO_ROOT" -s api-dev ENV_FILE="$ENV_FILE"
+ else
+ launch_detached api env COLLAB_INTERNAL_URL= make -C "$REPO_ROOT" -s api-dev ENV_FILE="$ENV_FILE"
+ fi
printf '%s %s\n' "$(cat "$(pid_file api)")" "$fingerprint" > "$(api_build_file)"
+ printf '%s\n' "$collab_url" > "$(api_collab_file)"
info "api launching (pid $(cat "$(pid_file api)")), log: $(log_file api)"
while [ "$waited" -lt 300 ]; do
@@ -781,6 +837,60 @@ start_web() {
die "web never came up. Log: $(log_file web)"
}
+collab_healthy() {
+ curl -sf --max-time 3 "http://localhost:${COLLAB_PORT}/health" >/dev/null 2>&1
+}
+
+# The CDN domain the API reports (Storage.CdnDomain): CLOUDFRONT_DOMAIN with
+# S3, otherwise the host of LOCAL_UPLOAD_BASE_URL. Collab needs the same value
+# to turn links to uploaded files into the same nodes the editor makes.
+collab_cdn_domain() {
+ if [ -n "${S3_BUCKET:-}" ]; then
+ printf '%s' "${CLOUDFRONT_DOMAIN:-}"
+ return 0
+ fi
+ node -e 'try { process.stdout.write(new URL(process.argv[1]).hostname); } catch {}' \
+ "${LOCAL_UPLOAD_BASE_URL:-http://localhost:${BACKEND_PORT}}"
+}
+
+# `tsx watch` restarts the service on every source change, so a running collab
+# of this environment is always current and is reused as it is.
+start_collab() {
+ local waited=0 listener
+ if listener_belongs_to_component collab "$COLLAB_PORT"; then
+ if collab_healthy && listener="$(record_component_listener collab "$COLLAB_PORT")"; then
+ ok "collab already running on :$COLLAB_PORT (pid $listener)"
+ return 0
+ fi
+ warn "collab on :$COLLAB_PORT is ours but not answering /health; restarting it."
+ stop_component collab
+ fi
+ if ! port_free "$COLLAB_PORT"; then
+ die "Port $COLLAB_PORT is busy: $(describe_port_owner "$COLLAB_PORT"). Run 'make down' here first."
+ fi
+
+ launch_detached collab env COLLAB_PORT="$COLLAB_PORT" COLLAB_SECRET="$(collab_secret)" \
+ MULTICA_API_URL="http://localhost:${BACKEND_PORT}" MULTICA_CDN_DOMAIN="$(collab_cdn_domain)" \
+ make -C "$REPO_ROOT" -s collab-dev ENV_FILE="$ENV_FILE"
+ info "collab launching (pid $(cat "$(pid_file collab)")), log: $(log_file collab)"
+
+ while [ "$waited" -lt 120 ]; do
+ if collab_healthy; then
+ listener="$(record_component_listener collab "$COLLAB_PORT" || true)"
+ if [ -z "$listener" ]; then
+ stop_component collab
+ die "Collab on :$COLLAB_PORT is not descended from the process this environment launched."
+ fi
+ ok "collab serving ws://localhost:$COLLAB_PORT (pid $listener)"
+ return 0
+ fi
+ component_pid collab >/dev/null || { tail -20 "$(log_file collab)" | sed 's/^/ /' >&2; die "collab exited during startup. Log: $(log_file collab)"; }
+ sleep 2
+ waited=$((waited + 2))
+ done
+ die "collab never became healthy. Log: $(log_file collab)"
+}
+
# send-code once, verify-code once. Repeated verify attempts lock the code out
# and start returning 400 even when it is correct, so retrying is self-defeating.
write_profile_config() {
@@ -1178,6 +1288,7 @@ stop_component() {
case "$name" in
api) port="$BACKEND_PORT" ;;
+ collab) port="$COLLAB_PORT" ;;
web) port="$FRONTEND_PORT" ;;
desktop) port="$DESKTOP_RENDERER_PORT" ;;
esac
@@ -1295,6 +1406,20 @@ component_state() {
printf 'stopped|http://localhost:%s|' "$BACKEND_PORT"
fi
;;
+ collab)
+ local listener
+ listener="$(port_listener_pid "$COLLAB_PORT")"
+ if [ -z "$listener" ]; then
+ printf 'stopped|ws://localhost:%s|' "$COLLAB_PORT"
+ elif ! listener_pid_belongs_to_component collab "$listener"; then
+ printf 'mismatch|ws://localhost:%s|listener pid %s is not owned by this environment' \
+ "$COLLAB_PORT" "$listener"
+ elif collab_healthy; then
+ printf 'running|ws://localhost:%s|pid %s' "$COLLAB_PORT" "$listener"
+ else
+ printf 'busy|ws://localhost:%s|pid %s is ours but not answering /health' "$COLLAB_PORT" "$listener"
+ fi
+ ;;
web)
local listener
listener="$(port_listener_pid "$FRONTEND_PORT")"
@@ -1392,8 +1517,8 @@ print_status_json() {
printf '{"name":"%s","dir":"%s","owner":"%s","created_at":"%s","ttl_hours":%s,"expires_at":"%s",' \
"$(json_escape "$NAME")" "$(json_escape "$DIR")" "$(json_escape "$OWNER")" \
"$(json_escape "$CREATED_AT")" "${TTL_HOURS:-0}" "$(json_escape "$EXPIRES_AT")"
- printf '"backend_port":%s,"frontend_port":%s,"desktop_renderer_port":%s,"desktop_cdp_port":%s,"workspace_slug":"%s","database":"%s","profile":"%s","env_file":"%s","logs":"%s","components":{' \
- "$BACKEND_PORT" "$FRONTEND_PORT" "$DESKTOP_RENDERER_PORT" "${DESKTOP_CDP_PORT:-null}" \
+ printf '"backend_port":%s,"frontend_port":%s,"collab_port":%s,"desktop_renderer_port":%s,"desktop_cdp_port":%s,"workspace_slug":"%s","database":"%s","profile":"%s","env_file":"%s","logs":"%s","components":{' \
+ "$BACKEND_PORT" "$FRONTEND_PORT" "$COLLAB_PORT" "$DESKTOP_RENDERER_PORT" "${DESKTOP_CDP_PORT:-null}" \
"$(json_escape "$WORKSPACE_SLUG")" "$(json_escape "$DB_NAME")" "$(json_escape "$PROFILE")" \
"$(json_escape "$ENV_FILE")" "$(json_escape "$LOG_DIR")"
for comp in $ALL_COMPONENTS; do
@@ -1409,7 +1534,12 @@ print_status_json() {
}
print_handoff() {
- local entrypoint
+ local entrypoint live_docs
+ if [ -n "$(api_collab_url)" ]; then
+ live_docs="collab on :${COLLAB_PORT}, reached through the backend's /collab"
+ else
+ live_docs="off (collab is not running); docs save through the API"
+ fi
if component_selected web; then
entrypoint="Open http://localhost:${FRONTEND_PORT}/${WORKSPACE_SLUG}/issues"
elif component_selected desktop; then
@@ -1432,6 +1562,7 @@ ${C_GREEN}✓ Environment ready.${C_OFF}
Token profile ${PROFILE} (onboarded, workspace /${WORKSPACE_SLUG})
Fixtures make env-exec ARGS="-- node scripts/dev-fixtures.mjs all"
Backend http://localhost:${BACKEND_PORT} (GET /health reports pid + commit + started_at)
+ Live docs ${live_docs}
Commit $(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null || echo unknown)
Environment ${NAME}$( [ "${TTL_HOURS:-0}" != 0 ] && printf ' (expires %s)' "$EXPIRES_AT" )
@@ -1460,6 +1591,7 @@ bind_paths() {
PROFILE_DIR="$DEV_PROFILES_HOME/$PROFILE"
WORKSPACES_ROOT="${WORKSPACES_ROOT:-$DEV_WORKSPACES_PARENT/multica_workspaces_$PROFILE}"
DESKTOP_RENDERER_PORT="${DESKTOP_RENDERER_PORT:-$(renderer_port_for_offset "$OFFSET")}"
+ COLLAB_PORT="${COLLAB_PORT:-$(collab_port_for_offset "$OFFSET")}"
DESKTOP_APP_SUFFIX="${DESKTOP_APP_SUFFIX:-$NAME}"
DESKTOP_USER_DATA_DIR="${DESKTOP_USER_DATA_DIR:-$(desktop_user_data_dir "$DESKTOP_APP_SUFFIX")}"
DESKTOP_ENV_FILE="${DESKTOP_ENV_FILE:-$DIR/apps/desktop/.env.development.local}"
@@ -1484,6 +1616,7 @@ save_manifest() {
write_manifest_value OFFSET "$OFFSET"
write_manifest_value BACKEND_PORT "$BACKEND_PORT"
write_manifest_value FRONTEND_PORT "$FRONTEND_PORT"
+ write_manifest_value COLLAB_PORT "$COLLAB_PORT"
write_manifest_value DB_NAME "$DB_NAME"
write_manifest_value DATABASE_URL "$DATABASE_URL"
write_manifest_value PROFILE "$PROFILE"
@@ -1532,7 +1665,7 @@ cmd_up() {
*) [ -z "$cdp_request" ] \
|| die "--cdp, --remote-debugging-port and --no-cdp need the desktop component (C=desktop)." ;;
esac
- # web, daemon and desktop are all clients of the backend; selecting one
+ # collab, web, daemon and desktop are all clients of the backend; selecting one
# without api would produce an environment that cannot serve a single request.
case " $requested " in *" api "*) ;; *) requested="api $requested" ;; esac
COMPONENTS="$requested"
@@ -1545,7 +1678,7 @@ cmd_up() {
local missing=() tool needed="node go curl"
# pnpm is only required by the components that actually build JavaScript, so
# `up C=api` works on a checkout that has never run an install.
- if component_selected web || component_selected desktop; then needed="$needed pnpm"; fi
+ if component_selected web || component_selected desktop || component_selected collab; then needed="$needed pnpm"; fi
for tool in $needed; do
command -v "$tool" >/dev/null 2>&1 || missing+=("$tool")
done
@@ -1594,11 +1727,13 @@ cmd_up() {
# A slot is adopted only when the registry does not hold it and both ports
# are genuinely free; otherwise a fresh one is allocated and the env file is
# rewritten, which is the whole point of allocating instead of computing.
- local candidate_renderer
+ local candidate_renderer candidate_collab
candidate_renderer="$(renderer_port_for_offset "$offset")"
+ candidate_collab="$(collab_port_for_offset "$offset")"
if [ "$PORT" -lt 18080 ] || [ "$FRONTEND_PORT" -ne $((13000 + offset)) ] \
|| offset_registered "$offset" || ! port_free "$PORT" \
- || ! port_free "$FRONTEND_PORT" || ! port_free "$candidate_renderer"; then
+ || ! port_free "$FRONTEND_PORT" || ! port_free "$candidate_renderer" \
+ || ! port_free "$candidate_collab"; then
if [ "$PORT" -ge 18080 ] && { offset_registered "$offset" || ! port_free "$PORT"; }; then
warn "Slot $offset (port $PORT) is taken: $(describe_port_owner "$PORT"). Allocating another."
fi
@@ -1615,6 +1750,7 @@ cmd_up() {
PROFILE="dev-$(slugify "$(basename "$REPO_ROOT")")-${offset}"
WORKSPACES_ROOT="$DEV_WORKSPACES_PARENT/multica_workspaces_$PROFILE"
DESKTOP_RENDERER_PORT="$(renderer_port_for_offset "$offset")"
+ COLLAB_PORT="$(collab_port_for_offset "$offset")"
DESKTOP_APP_SUFFIX="$NAME"
DESKTOP_USER_DATA_DIR="$(desktop_user_data_dir "$DESKTOP_APP_SUFFIX")"
DESKTOP_ENV_FILE="$REPO_ROOT/apps/desktop/.env.development.local"
@@ -1666,7 +1802,7 @@ cmd_up() {
# sees the same values the registry recorded.
export PORT="$BACKEND_PORT" FRONTEND_PORT DATABASE_URL POSTGRES_DB="$DB_NAME"
- if [ ! -d "$REPO_ROOT/node_modules" ] && { component_selected web || component_selected desktop; }; then
+ if [ ! -d "$REPO_ROOT/node_modules" ] && { component_selected web || component_selected desktop || component_selected collab; }; then
step "Dependencies"
(cd "$REPO_ROOT" && pnpm install) || die "pnpm install failed."
fi
@@ -1680,6 +1816,7 @@ cmd_up() {
step "Components: $COMPONENTS"
component_selected api && start_api
+ component_selected collab && start_collab
seed_dev_workspace
component_selected web && start_web
component_selected daemon && start_daemon
@@ -1688,6 +1825,13 @@ cmd_up() {
print_handoff
}
+# collab saves open docs through the API on its way out, so it stops first.
+stop_order() {
+ local comp
+ for comp in "$@"; do [ "$comp" != collab ] || printf 'collab '; done
+ for comp in "$@"; do [ "$comp" = collab ] || printf '%s ' "$comp"; done
+}
+
cmd_down() {
local name="" requested="$ALL_COMPONENTS"
while [ $# -gt 0 ]; do
@@ -1704,6 +1848,8 @@ cmd_down() {
local comp
for comp in $requested; do
case " $ALL_COMPONENTS " in *" $comp "*) ;; *) die "Unknown component '$comp'. Valid: $ALL_COMPONENTS" ;; esac
+ done
+ for comp in $(stop_order $requested); do
stop_component "$comp"
done
if [ "$requested" = "$ALL_COMPONENTS" ]; then
@@ -1734,7 +1880,7 @@ cmd_destroy() {
export PORT="$BACKEND_PORT" FRONTEND_PORT DATABASE_URL POSTGRES_DB="$DB_NAME"
step "Destroying $NAME"
local comp desktop_stopped=1
- for comp in $ALL_COMPONENTS; do
+ for comp in $(stop_order $ALL_COMPONENTS); do
if ! stop_component "$comp"; then
failures=$((failures + 1))
[ "$comp" != desktop ] || desktop_stopped=0
@@ -1948,7 +2094,7 @@ usage() {
cat <<'EOF'
Local development environments: named, listable, deletable.
- dev-env.sh up [--components api,web,daemon,desktop] [--all]
+ dev-env.sh up [--components api,collab,web,daemon,desktop] [--all]
[--name N] [--ephemeral] [--ttl HOURS]
[--cdp | --remote-debugging-port N | --no-cdp]
dev-env.sh status [name] [--json]
@@ -1958,8 +2104,10 @@ Local development environments: named, listable, deletable.
dev-env.sh gc [--dry-run]
dev-env.sh exec [name] -- <command> [args...]
-Components: api (Go backend), web (Next.js), daemon (agent daemon),
-desktop (Electron). Anything selected implies api.
+Components: api (Go backend), collab (live doc co-editing), web (Next.js),
+daemon (agent daemon), desktop (Electron). Anything selected implies api.
+The default is api,collab,web. Without a running collab, docs save through
+the API instead of being edited live.
Every environment has an onboarded workspace with two issues, signed in
through its CLI profile; scripts/dev-fixtures.mjs adds chat, Agent Builder,
diff --git a/scripts/dev-env.test.sh b/scripts/dev-env.test.sh
index 51f79f3acd..016c31f6bd 100644
--- a/scripts/dev-env.test.sh
+++ b/scripts/dev-env.test.sh
@@ -185,6 +185,7 @@ assert_component_state() {
mkdir -p "$STATE_DIR"
BACKEND_PORT=18080
FRONTEND_PORT=13000
+ COLLAB_PORT=14000
TEST_LISTENER=$listener
TEST_COMMIT=$reported_commit
TEST_PROBE_OK=$probe_ok
@@ -315,6 +316,140 @@ assert_start_api() {
)
}
+# The same current api as above, with `components` selected and collab's
+# listener running or not. `recorded` is the collab URL the api was launched
+# with ("-" for an api started before collab existed).
+assert_start_api_collab() {
+ local case_name=$1 components=$2 collab_running=$3 recorded=$4 expected_output=$5
+ local expected_events=$6 expected_recorded=$7
+ (
+ # shellcheck disable=SC1090
+ source "$root_dir/scripts/dev-env.sh"
+ STATE_DIR="$tmp_dir/start-api-collab-$case_name"
+ LOG_DIR="$STATE_DIR"
+ mkdir -p "$STATE_DIR"
+ BACKEND_PORT=18080
+ COLLAB_PORT=14000
+ COMPONENTS="$components"
+ ENV_FILE=.env.example
+ COLLAB_SECRET=test-secret
+ local events="$STATE_DIR/events"
+ : > "$events"
+ printf '100\n' > "$(pid_file api)"
+ printf '100 fp-now\n' > "$(api_build_file)"
+ [ "$recorded" = - ] || printf '%s\n' "$recorded" > "$(api_collab_file)"
+ TEST_COLLAB_RUNNING=$collab_running
+
+ eval "original_$(declare -f listener_belongs_to_component)"
+ listener_belongs_to_component() {
+ if [ "$1" = collab ]; then [ "$TEST_COLLAB_RUNNING" = 1 ]; else original_listener_belongs_to_component "$@"; fi
+ }
+ component_pid() { cat "$(pid_file api)"; }
+ port_listener_pid() { printf '200'; }
+ port_free() { :; }
+ process_group_id() { [ "$1" = 200 ] && component_pid api || printf '%s' "$1"; }
+ process_parent_id() { printf '1'; }
+ checkout_commit() { printf 'bbb2222'; }
+ api_source_fingerprint() { printf 'fp-now'; }
+ health_json() {
+ printf '{"pid":200,"commit":"bbb2222","started_at":"2026-01-01T00:00:00Z"}'
+ }
+ now_epoch() { printf '1000'; }
+ sleep() { :; }
+ stop_component() { printf 'stop %s\n' "$1" >> "$events"; }
+ launch_detached() {
+ local arg wiring=""
+ for arg in "$@"; do
+ case "$arg" in COLLAB_INTERNAL_URL=*) wiring="$arg" ;; esac
+ done
+ printf 'launch %s %s\n' "$1" "$wiring" >> "$events"
+ printf '101\n' > "$(pid_file api)"
+ }
+
+ local status=0
+ ( start_api ) > "$out" 2>&1 || status=$?
+ [ "$status" = 0 ] \
+ || { sed 's/^/ /' "$out" >&2; fail "$case_name start_api exited $status"; }
+ require_contains "$out" "$expected_output"
+ [ "$(cat "$events")" = "$expected_events" ] \
+ || fail "$case_name events = $(cat "$events"), want $expected_events"
+ [ "$(cat "$(api_collab_file)" 2>/dev/null)" = "$expected_recorded" ] \
+ || fail "$case_name recorded collab URL = '$(cat "$(api_collab_file)" 2>/dev/null)', want '$expected_recorded'"
+ )
+}
+
+# The generated secret is created once, private, and reused; one set in the env
+# file wins over it.
+assert_collab_secret() (
+ # shellcheck disable=SC1090
+ source "$root_dir/scripts/dev-env.sh"
+ STATE_DIR="$tmp_dir/collab-secret"
+ mkdir -p "$STATE_DIR"
+ unset COLLAB_SECRET
+ local first second
+ first="$(collab_secret)"
+ second="$(collab_secret)"
+ [ "${#first}" = 64 ] || fail "generated collab secret has ${#first} characters, want 64"
+ [ "$first" = "$second" ] || fail "collab secret changed between calls"
+ case "$(ls -l "$STATE_DIR/collab.secret")" in
+ -rw-------*) ;;
+ *) fail "collab secret file is readable by others: $(ls -l "$STATE_DIR/collab.secret")" ;;
+ esac
+ [ "$(COLLAB_SECRET=from-env-file collab_secret)" = from-env-file ] \
+ || fail "a COLLAB_SECRET from the env file did not win"
+)
+
+# Launcher 100 owns listener 200; listener 999 is someone else's ("" for a free
+# port). /health answers when `healthy` is 1.
+assert_start_collab() {
+ local case_name=$1 listener=$2 healthy=$3 expected_status=$4
+ local expected_output=$5 expected_events=$6
+ (
+ # shellcheck disable=SC1090
+ source "$root_dir/scripts/dev-env.sh"
+ STATE_DIR="$tmp_dir/start-collab-$case_name"
+ LOG_DIR="$STATE_DIR"
+ mkdir -p "$STATE_DIR"
+ BACKEND_PORT=18080
+ COLLAB_PORT=14000
+ ENV_FILE=.env.example
+ COLLAB_SECRET=test-secret
+ local events="$STATE_DIR/events"
+ printf '%s' "$listener" > "$STATE_DIR/listener"
+ printf '%s' "$healthy" > "$STATE_DIR/healthy"
+ : > "$events"
+
+ component_pid() { printf '100'; }
+ port_listener_pid() { cat "$STATE_DIR/listener"; }
+ port_free() { [ -z "$(port_listener_pid)" ]; }
+ process_group_id() { [ "$1" = 200 ] && printf '100' || printf '%s' "$1"; }
+ process_parent_id() { printf '1'; }
+ describe_port_owner() { printf 'pid %s' "$(port_listener_pid "$1")"; }
+ collab_healthy() { [ "$(cat "$STATE_DIR/healthy")" = 1 ]; }
+ collab_cdn_domain() { printf 'localhost'; }
+ sleep() { :; }
+ stop_component() { printf 'stop %s\n' "$1" >> "$events"; : > "$STATE_DIR/listener"; }
+ launch_detached() {
+ local arg wiring=""
+ for arg in "$@"; do
+ case "$arg" in COLLAB_PORT=*|MULTICA_API_URL=*) wiring="$wiring $arg" ;; esac
+ done
+ printf 'launch %s%s\n' "$1" "$wiring" >> "$events"
+ printf '100\n' > "$(pid_file collab)"
+ printf '200' > "$STATE_DIR/listener"
+ printf '1' > "$STATE_DIR/healthy"
+ }
+
+ local status=0
+ ( start_collab ) > "$out" 2>&1 || status=$?
+ [ "$status" = "$expected_status" ] \
+ || { sed 's/^/ /' "$out" >&2; fail "$case_name start_collab exited $status, want $expected_status"; }
+ require_contains "$out" "$expected_output"
+ [ "$(cat "$events")" = "$expected_events" ] \
+ || fail "$case_name events = $(cat "$events"), want $expected_events"
+ )
+}
+
# The fingerprint follows server/'s uncommitted state in a real repository:
# tracked edits, staged edits and untracked files count, ignored files and
# changes outside server/ do not, and undoing an edit restores it.
@@ -428,7 +563,9 @@ node -e '
if (payload.backend_port !== 18981) throw new Error("backend_port = " + payload.backend_port);
if (payload.desktop_cdp_port !== null) throw new Error("desktop_cdp_port = " + payload.desktop_cdp_port);
if (payload.workspace_slug !== "dev") throw new Error("workspace_slug = " + payload.workspace_slug);
- for (const key of ["api", "web", "daemon", "desktop"]) {
+ // Manifests written before collab existed derive its port from the offset.
+ if (payload.collab_port !== 14901) throw new Error("collab_port = " + payload.collab_port);
+ for (const key of ["api", "collab", "web", "daemon", "desktop"]) {
if (!payload.components[key]) throw new Error("missing component " + key);
if (payload.components[key].state !== "stopped") {
throw new Error(key + " state = " + payload.components[key].state);
@@ -545,6 +682,38 @@ assert_start_api dirty bbb2222 "100 fp-old" "was compiled before server/ changed
assert_start_api unrecorded bbb2222 - "has no recorded source fingerprint" $'stop api\nlaunch api' "101 fp-now"
assert_start_api old-commit aaa1111 "100 fp-now" "is ours but not commit bbb2222; restarting it" $'stop api\nlaunch api' "101 fp-now"
+# The api is wired to collab only when collab is selected or already running,
+# so a doc page never waits on a collab that is not there, and `make up`
+# restarts an api whose wiring no longer matches.
+assert_start_api_collab selected-new "api collab web" 0 - \
+ "is not connected to collab on :14000; restarting it" \
+ $'stop api\nlaunch api COLLAB_INTERNAL_URL=http://localhost:14000' "http://localhost:14000"
+assert_start_api_collab selected-wired "api collab web" 0 "http://localhost:14000" \
+ "api already running on :18080" "" "http://localhost:14000"
+assert_start_api_collab running-unselected "api web" 1 "" \
+ "is not connected to collab on :14000; restarting it" \
+ $'stop api\nlaunch api COLLAB_INTERNAL_URL=http://localhost:14000' "http://localhost:14000"
+assert_start_api_collab gone "api web" 0 "http://localhost:14000" \
+ "points at a collab service that is not running; restarting it" \
+ $'stop api\nlaunch api COLLAB_INTERNAL_URL=' ""
+assert_start_api_collab never-wired "api web" 0 - \
+ "api already running on :18080" "" ""
+
+stopped_in="$(bash -c 'source "$1"; stop_order api collab web daemon' _ "$root_dir/scripts/dev-env.sh")"
+[ "$stopped_in" = "collab api web daemon " ] \
+ || fail "down must stop collab before the api it saves docs through, got: $stopped_in"
+
+assert_collab_secret
+assert_start_collab running 200 1 0 "collab already running on :14000 (pid 200)" ""
+assert_start_collab hung 200 0 0 "is ours but not answering /health; restarting it" \
+ $'stop collab\nlaunch collab COLLAB_PORT=14000 MULTICA_API_URL=http://localhost:18080'
+assert_start_collab fresh "" 1 0 "collab serving ws://localhost:14000 (pid 200)" \
+ $'launch collab COLLAB_PORT=14000 MULTICA_API_URL=http://localhost:18080'
+assert_start_collab foreign 999 1 1 "Port 14000 is busy: pid 999" ""
+assert_component_state collab-running collab 200 - 1 running "pid 200"
+assert_component_state collab-busy collab 200 - 0 busy "not answering /health"
+assert_component_state collab-foreign collab 999 - 1 mismatch "listener pid 999 is not owned"
+
# ---------------------------------------------------------------------------
# Daemon: `daemon start` is a no-op while one is running, so `make up` has to
# restart a daemon that is not running this checkout's current build itself.
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 2e560b8d9c..2a3aefe970 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -88,6 +88,40 @@ disabled_config="$(
)"
require_rendered_value "$disabled_config" 'MULTICA_VCS_INTEGRATION_ENABLED: "false"'
+# Live co-editing is off by default and then renders nothing: no collab
+# workload, and no backend setting that would point the API at one.
+default_all="$(helm template multica "$CHART_DIR")"
+reject_rendered_value "$default_all" 'multica-collab'
+reject_rendered_value "$default_all" 'COLLAB_'
+
+collab_all="$(helm template multica "$CHART_DIR" --set collab.enabled=true)"
+require_rendered_value "$collab_all" 'name: multica-collab'
+require_rendered_value "$collab_all" 'image: "ghcr.io/multica-ai/multica-collab:'
+require_rendered_value "$collab_all" 'value: "http://multica-backend:8080"'
+collab_deployment="$(helm template multica "$CHART_DIR" --set collab.enabled=true --show-only templates/collab.yaml | sed -n '/kind: Deployment/,$p')"
+require_rendered_value "$collab_deployment" 'replicas: 1'
+require_rendered_value "$collab_deployment" 'type: Recreate'
+require_rendered_value "$collab_deployment" 'terminationGracePeriodSeconds: 30'
+require_rendered_value "$collab_deployment" 'path: /health'
+require_rendered_value "$collab_deployment" 'key: COLLAB_SECRET'
+# The backend reports the host of LOCAL_UPLOAD_BASE_URL as its CDN domain
+# without S3, and CLOUDFRONT_DOMAIN with it; collab must agree.
+require_rendered_value "$collab_deployment" 'value: "api.multica.dev.lan"'
+collab_s3="$(helm template multica "$CHART_DIR" --set collab.enabled=true \
+ --set backend.config.s3Bucket=bucket --set backend.config.cloudfrontDomain=cdn.example.com \
+ --show-only templates/collab.yaml)"
+require_rendered_value "$collab_s3" 'value: "cdn.example.com"'
+
+collab_backend="$(helm template multica "$CHART_DIR" --set collab.enabled=true --show-only templates/backend.yaml)"
+require_rendered_value "$collab_backend" 'value: "http://multica-collab:8095"'
+require_rendered_value "$collab_backend" 'key: COLLAB_SECRET'
+require_rendered_value "$collab_backend" 'optional: true'
+# External postgres and no extra CAs leave the backend env block otherwise empty.
+collab_backend_external="$(helm template multica "$CHART_DIR" --set collab.enabled=true \
+ --set postgres.external.enabled=true --show-only templates/backend.yaml)"
+require_rendered_value "$collab_backend_external" 'name: COLLAB_INTERNAL_URL'
+reject_rendered_value "$collab_backend_external" 'name: DATABASE_URL'
+
capacity_config="$(
helm template multica "$CHART_DIR" \
--show-only templates/configmap.yaml \
diff --git a/scripts/selfhost-config.test.sh b/scripts/selfhost-config.test.sh
index 24c709ae96..b1795f5b1f 100755
--- a/scripts/selfhost-config.test.sh
+++ b/scripts/selfhost-config.test.sh
@@ -70,6 +70,52 @@ require_config "$config" 'DATABASE_REPLICA_URL: postgres://reader:secret@replica
require_config "$config" 'DATABASE_REPLICA_MAX_CONNS: "12"'
require_config "$config" 'DATABASE_REPLICA_MIN_CONNS: "1"'
+# Live doc co-editing is opt-in. Out of the box there is no collab service and
+# the backend has no collab URL, so docs save through the API instead of
+# waiting on a service that is not there. The two commented lines in
+# .env.example are the whole switch: the secret wires the backend, and the
+# profile starts the service.
+if grep -q '^ collab:' <<<"$config"; then
+ echo "The collab service must stay behind its profile by default"
+ exit 1
+fi
+require_config "$config" 'COLLAB_INTERNAL_URL: ""'
+collab_env="$tmp_dir/.env.collab"
+sed 's/^# COLLAB_SECRET=$/COLLAB_SECRET=collab-secret-from-env/;s/^# COMPOSE_PROFILES=collab$/COMPOSE_PROFILES=collab/;s/^# FF_DOCS_V1=true$/FF_DOCS_V1=true/' \
+ "$tmp_env" >"$collab_env"
+# Docs is off by default, and an empty FF_DOCS_V1 would pin it off, so the
+# backend must not receive the variable at all until it is set.
+docs_flag="$(env -u FF_DOCS_V1 docker compose --env-file "$tmp_env" -f docker-compose.selfhost.yml config --format json |
+ node -e '
+let raw = "";
+process.stdin.on("data", (chunk) => (raw += chunk));
+process.stdin.on("end", () => {
+ process.stdout.write(String(JSON.parse(raw).services.backend.environment.FF_DOCS_V1 ?? "unset"));
+});
+')"
+if [ "$docs_flag" != unset ]; then
+ echo "The backend must not receive FF_DOCS_V1 unless it is set, got: $docs_flag"
+ exit 1
+fi
+collab_config="$(env -u COLLAB_SECRET -u COLLAB_INTERNAL_URL -u COMPOSE_PROFILES -u FF_DOCS_V1 \
+ docker compose --env-file "$collab_env" -f docker-compose.selfhost.yml config --format json)"
+node -e '
+ const config = JSON.parse(process.argv[1]);
+ const backend = config.services.backend.environment;
+ const collab = config.services.collab;
+ if (!collab) throw new Error("COMPOSE_PROFILES=collab did not start the collab service");
+ const want = (label, actual, expected) => {
+ if (actual !== expected) throw new Error(`${label} = ${JSON.stringify(actual)}, want ${JSON.stringify(expected)}`);
+ };
+ want("backend COLLAB_INTERNAL_URL", backend.COLLAB_INTERNAL_URL, "http://collab:8095");
+ want("backend COLLAB_SECRET", backend.COLLAB_SECRET, "collab-secret-from-env");
+ want("collab COLLAB_SECRET", collab.environment.COLLAB_SECRET, "collab-secret-from-env");
+ want("collab MULTICA_API_URL", collab.environment.MULTICA_API_URL, "http://backend:8080");
+ want("collab image", collab.image, "ghcr.io/multica-ai/multica-collab:latest");
+ want("backend FF_DOCS_V1", backend.FF_DOCS_V1, "true");
+ if (collab.ports && collab.ports.length) throw new Error("collab must not publish a port; editors reach it through the backend");
+' "$collab_config"
+
# The backend environment is an explicit allowlist, so a variable documented in
# .env.example but missing here silently never reaches the container: the
# operator configures it, the server never sees it, and nothing reports the gap.
diff --git a/scripts/selfhost-wait.sh b/scripts/selfhost-wait.sh
index e0444065c8..180016859f 100755
--- a/scripts/selfhost-wait.sh
+++ b/scripts/selfhost-wait.sh
@@ -87,6 +87,9 @@ else
echo "Images: ${MULTICA_BACKEND_IMAGE:-ghcr.io/multica-ai/multica-backend}:${MULTICA_IMAGE_TAG:-latest}"
echo " ${MULTICA_WEB_IMAGE:-ghcr.io/multica-ai/multica-web}:${MULTICA_IMAGE_TAG:-latest}"
fi
+case ",${COMPOSE_PROFILES:-}," in
+ *,collab,*) echo "Live doc co-editing: on (collab service)" ;;
+esac
echo ""
echo "Log in: configure RESEND_API_KEY in .env for email codes,"
echo " or read the generated code from backend logs when Resend is unset."