Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Give self-hosted servers a stable channel and an update with a way back
milind-soni407636c5e6ee
diff --git a/.github/workflows/promote-stable.yml b/.github/workflows/promote-stable.ymlnew file mode 100644index 0000000000..02e6e2a723--- /dev/null+++ b/.github/workflows/promote-stable.yml@@ -0,0 +1,161 @@+name: Promote to stable++# Makes one released version the `stable` channel that self-hosted servers follow. Run by hand, after our own Clouds+# have run the version for 48 hours. Nothing is built: the `stable` tags of the server image (linux/amd64 and+# linux/arm64) and of the Cloud home image move to the digests the release already published, and stable.json on the+# `channels` branch records them. A server reads that file over plain HTTPS (server/update-check.ts,+# deploy/update.sh). `latest` keeps following main and is not touched.+on:+ workflow_dispatch:+ inputs:+ version:+ description: "Released version to make stable (X.Y.Z)"+ required: true+ type: string+ soaked:+ description: "Our own Clouds have run this version for 48 hours"+ required: true+ type: boolean+ default: false+ urgent:+ description: "A fix that cannot wait: skip the 48 hours since the release"+ required: false+ type: boolean+ default: false+ allow_older:+ description: "Allow moving stable back to an older version"+ required: false+ type: boolean+ default: false++permissions:+ contents: read++concurrency:+ group: promote-stable+ cancel-in-progress: false++jobs:+ promote:+ name: Point stable at the release+ runs-on: ubuntu-24.04+ timeout-minutes: 15+ permissions:+ contents: write+ packages: write+ env:+ GH_TOKEN: ${{ github.token }}+ VERSION_INPUT: ${{ inputs.version }}+ SOAKED: ${{ inputs.soaked }}+ URGENT: ${{ inputs.urgent }}+ ALLOW_OLDER: ${{ inputs.allow_older }}+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: main++ - name: Refuse anything but a published, soaked release+ id: release+ run: |+ set -euo pipefail+ if [ "$SOAKED" != "true" ] && [ "$URGENT" != "true" ]; then+ echo "::error::Tick the box that says our own Clouds have run this version for 48 hours."+ exit 1+ fi+ version=$(node scripts/stable-channel.mjs version "$VERSION_INPUT")+ if ! gh release view "v$version" --repo "$GITHUB_REPOSITORY" --json tagName,isDraft,isPrerelease,publishedAt,url > "$RUNNER_TEMP/release.json"; then+ echo "::error::v$version is not a release of $GITHUB_REPOSITORY. Stable only takes a version that was released."+ exit 1+ fi+ node scripts/stable-channel.mjs check-release --version "$version" --release "$RUNNER_TEMP/release.json" $([ "$URGENT" = "true" ] && echo --urgent)+ echo "version=$version" >> "$GITHUB_OUTPUT"+ # Image references must be lowercase; the repository name is not.+ echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"++ - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4.3.0+ - uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0+ with:+ registry: ghcr.io+ username: ${{ github.actor }}+ password: ${{ secrets.GITHUB_TOKEN }}++ - name: Find the images the release published+ id: images+ env:+ VERSION: ${{ steps.release.outputs.version }}+ IMAGE: ${{ steps.release.outputs.image }}+ run: |+ set -euo pipefail+ digest_of() { docker buildx imagetools inspect "$1" --format '{{json .Manifest}}' | jq -er .digest; }+ docker buildx imagetools inspect --raw "$IMAGE:v$VERSION" > "$RUNNER_TEMP/server-index.json"+ docker buildx imagetools inspect --raw "$IMAGE-cloud-home:v$VERSION" > "$RUNNER_TEMP/home-index.json"+ node scripts/stable-channel.mjs check-image --index "$RUNNER_TEMP/server-index.json" --platforms linux/amd64,linux/arm64 --name "$IMAGE:v$VERSION"+ node scripts/stable-channel.mjs check-image --index "$RUNNER_TEMP/home-index.json" --platforms linux/amd64 --name "$IMAGE-cloud-home:v$VERSION"+ echo "server=$IMAGE@$(digest_of "$IMAGE:v$VERSION")" >> "$GITHUB_OUTPUT"+ echo "home=$IMAGE-cloud-home@$(digest_of "$IMAGE-cloud-home:v$VERSION")" >> "$GITHUB_OUTPUT"++ - name: Write the record, refusing to move stable back+ env:+ VERSION: ${{ steps.release.outputs.version }}+ SERVER: ${{ steps.images.outputs.server }}+ HOME_IMAGE: ${{ steps.images.outputs.home }}+ run: |+ set -euo pipefail+ current=()+ if git fetch --depth 1 origin channels 2>/dev/null && git show FETCH_HEAD:stable.json > "$RUNNER_TEMP/current.json" 2>/dev/null; then+ current=(--current "$RUNNER_TEMP/current.json")+ fi+ node scripts/stable-channel.mjs record --version "$VERSION" --image "$SERVER" --cloud-home "$HOME_IMAGE" \+ --release "$RUNNER_TEMP/release.json" "${current[@]}" $([ "$ALLOW_OLDER" = "true" ] && echo --allow-older) > "$RUNNER_TEMP/stable.json"+ cat "$RUNNER_TEMP/stable.json"++ # The tags move before the record does: a server follows the record, and the record never names a digest the+ # `stable` tag did not reach. Running this again with the same version repairs a run that stopped in between.+ - name: Move the stable tags, without building+ env:+ IMAGE: ${{ steps.release.outputs.image }}+ SERVER: ${{ steps.images.outputs.server }}+ HOME_IMAGE: ${{ steps.images.outputs.home }}+ run: |+ set -euo pipefail+ digest_of() { docker buildx imagetools inspect "$1" --format '{{json .Manifest}}' | jq -er .digest; }+ docker buildx imagetools create --tag "$IMAGE:stable" "$SERVER"+ docker buildx imagetools create --tag "$IMAGE-cloud-home:stable" "$HOME_IMAGE"+ test "$IMAGE@$(digest_of "$IMAGE:stable")" = "$SERVER"+ test "$IMAGE-cloud-home@$(digest_of "$IMAGE-cloud-home:stable")" = "$HOME_IMAGE"++ - name: Publish the record on the channels branch+ env:+ VERSION: ${{ steps.release.outputs.version }}+ run: |+ set -euo pipefail+ work="$RUNNER_TEMP/channels"+ if git fetch --depth 1 origin channels 2>/dev/null; then+ git worktree add --detach "$work" FETCH_HEAD+ else+ git worktree add --detach "$work"+ git -C "$work" checkout --orphan channels+ git -C "$work" rm -rfq .+ printf '%s\n' "# Channels" "" "\`stable.json\` names the released version self-hosted servers follow. \`.github/workflows/promote-stable.yml\` on main writes it; do not edit it by hand." > "$work/README.md"+ fi+ cp "$RUNNER_TEMP/stable.json" "$work/stable.json"+ git -C "$work" add -A+ if git -C "$work" diff --cached --quiet; then+ echo "stable.json already says $VERSION."+ else+ git -C "$work" -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" commit -q -m "stable: $VERSION"+ git -C "$work" push origin HEAD:refs/heads/channels+ fi++ - name: Summary+ env:+ VERSION: ${{ steps.release.outputs.version }}+ SERVER: ${{ steps.images.outputs.server }}+ HOME_IMAGE: ${{ steps.images.outputs.home }}+ run: |+ {+ echo "### Stable is now $VERSION"+ echo "- Server image: \`$SERVER\`"+ echo "- Cloud home image: \`$HOME_IMAGE\`"+ echo "- Record: https://raw.githubusercontent.com/$GITHUB_REPOSITORY/channels/stable.json"+ } >> "$GITHUB_STEP_SUMMARY"diff --git a/.github/workflows/server-update-e2e.yml b/.github/workflows/server-update-e2e.ymlnew file mode 100644index 0000000000..6a1c38fc63--- /dev/null+++ b/.github/workflows/server-update-e2e.yml@@ -0,0 +1,48 @@+name: Server update e2e++# deploy/update.sh on a stock ubuntu-24.04 runner, as a server's owner runs it: two published server images, an update+# to a stable record, a rollback on request, a new version that never answers and damages the data (rolled back, every+# file as it was), and an update killed half-way (deploy/e2e/update.sh), on both install layouts. It talks to no+# production service and publishes nothing.+on:+ pull_request:+ paths:+ - deploy/update.sh+ - deploy/e2e/update.sh+ - deploy/docker-compose.yml+ - .github/workflows/server-update-e2e.yml+ workflow_dispatch:++permissions:+ contents: read++concurrency:+ group: server-update-e2e-${{ github.ref }}+ cancel-in-progress: true++jobs:+ e2e:+ name: update, roll back and recover (${{ matrix.layout }})+ runs-on: ubuntu-24.04+ timeout-minutes: 40+ strategy:+ fail-fast: false+ matrix:+ layout: [installer, checkout]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - name: Update, roll back and recover+ env:+ LAYOUT: ${{ matrix.layout }}+ run: sudo env LAYOUT="$LAYOUT" OUT="$RUNNER_TEMP/evidence" bash deploy/e2e/update.sh+ - name: Keep what the script said+ if: always()+ run: sudo chmod -R a+rX "$RUNNER_TEMP/evidence" || true+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ if: always()+ with:+ name: server-update-e2e-${{ matrix.layout }}+ path: ${{ runner.temp }}/evidence+ if-no-files-found: ignorediff --git a/.gitignore b/.gitignoreindex 3888b9b2e4..0c17a74e7c 100644--- a/.gitignore+++ b/.gitignore@@ -36,6 +36,8 @@ cloudflare/control-plane/worker-configuration.d.ts# per-tenant deploy settings (see deploy/.env.example)deploy/.env+# update.sh's journal, log and the settings it keeps for a rollback+deploy/.update/deploy/podman/.envdeploy/podman/.env.*!deploy/podman/.env.examplediff --git a/apps/docs/content/docs/self-hosting/deploy-vps.mdx b/apps/docs/content/docs/self-hosting/deploy-vps.mdxindex 41b94bd3dd..db756d3421 100644--- a/apps/docs/content/docs/self-hosting/deploy-vps.mdx+++ b/apps/docs/content/docs/self-hosting/deploy-vps.mdx@@ -117,6 +117,7 @@ One container for the server plus Caddy for HTTPS at `https://maus.example.com`.```shdocker compose pull omb && docker compose up -d+ ./update.sh # move to the stable version (see "Update")docker compose ps # omb "healthy", caddy "running"```@@ -278,19 +279,120 @@ same release without an npm install prompt or an implicit upgrade.## Update-- **Paths A and C with the service above:** choose the new published version,- then run these commands from the administrator shell, replacing `X.Y.Z`:+A self-hosted server follows the **stable** channel: a released version that+MausBot's own Clouds have run for 48 hours first. The image tag `stable` and+[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)+name it. The tag `latest` follows every change on `main`; it is for trying+things out, not for a server you rely on. **Check for updates** in the app+compares your server with the stable version. To hear of every release as soon+as it is published instead, set `OMB_UPDATE_CHANNEL=newest` in the server's+environment.- ```sh- sudo systemctl stop openmausbot- sudo -iu maus npm install --global --prefix /home/maus/.local [email protected]- sudo systemctl start openmausbot- ```+### Path B (Docker): one command, with a way back- Check that installation succeeded before starting. A service restart by itself- does not update the installed package. For foreground `npx` usage, specify the- desired release as `npx --yes [email protected] serve --tunnel`.-- **Path B:** `cd OpenMausBot/deploy && docker compose pull omb && docker compose up -d`.+From `OpenMausBot/deploy`:++```sh+git pull && ./update.sh+```++`git pull` brings the current `update.sh` and `docker-compose.yml`; the server+image comes from the stable channel, not from your checkout. An install that+has no checkout, with its `compose.yaml`, `.env` and `data/` in one folder such+as `/opt/openmausbot`, runs the same script on that folder:++```sh+curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/update.sh -o update.sh+sudo bash update.sh --dir /opt/openmausbot+```++The data may be a Docker volume or a folder on the server; the copy keeps+every file's owner and mode either way. The script then:++1. Downloads the stable image, by its digest. If that fails it stops, and+ nothing has changed.+2. Checks there is room for a copy of your data, stops the server, and copies+ everything under `/data` into a Docker volume+ (`deploy_data-before-update`; `openmausbot_data-before-update` for+ `/opt/openmausbot`). The server is down from here until step 4;+ how long depends on how much data there is.+3. Writes the image into `.env` (`OMB_IMAGE=ghcr.io/milind-soni/openmausbot@sha256:…`)+ and starts it.+4. Waits, up to five minutes, until the new server answers `/api/health`+ steadily, says it is the new version, can still start a bot if it could+ before (`openmausbot doctor`: an engine is ready), and Caddy runs again.+5. If any of that fails: puts back `.env`, the data from the copy and the old+ image, starts the old version, and tells you what went wrong. Your server+ is as it was before step 1.++It is safe to interrupt and to run twice. Each step is written to+`deploy/.update/journal` before it starts, so after Ctrl-C, a closed terminal or+a reboot, the next `./update.sh` first finishes what was cut short: it keeps+the new version if that is up and healthy, and otherwise puts the old one+back. Run again after a finished update, it says there is nothing to do. Two+runs at once are refused.++```sh+./update.sh --check # what would change; changes nothing+./update.sh --version 0.1.151 # one released version instead of the stable one+./update.sh --rollback # the version and the data from before the last update+```++`--rollback` is for an update that passed its checks and still turned out+wrong. It asks first, because everything made since the update (chats, files,+settings) is replaced by the copy. The copy is kept until the next update+replaces it. The script's own log is `deploy/.update/update.log`.++| The script ends with | Meaning |+| --- | --- |+| `0` | Updated, or already on that version |+| `1` | The update failed; the old version and its data are back |+| `2` | The update failed and the old version did not come back healthy; read the last lines it printed |+| `3` | Another update is running |+| `4` | Nothing was changed (could not download, not enough disk, refused) |++If you built the image yourself (`docker compose up -d --build`, with+`ENGINES` baked in), `update.sh` refuses to replace it without being told to:+keep updating with `git pull && docker compose up -d --build`, or move to the+published image with `./update.sh --replace-local-build`. Engines you install+from **Settings → Engines** live on the data volume and survive either way.++### Paths A and C (npm with the service above): the same steps by hand++There is no one-command updater for an npm install yet. Do what the script+does: copy the data first, install one named version, check it, and keep the+way back. Take the stable version number from+[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)+(`"version"`), and note the one you run now (`openmausbot --version`). From+the administrator shell, replacing `X.Y.Z`:++```sh+sudo systemctl stop openmausbot+sudo -iu maus sh -c 'umask 077; tar czf ~/openmausbot-before-update.tgz -C ~ .openmausbot'+sudo -iu maus npm install --global --prefix /home/maus/.local [email protected]+sudo systemctl start openmausbot+curl -sf http://127.0.0.1:8799/api/health && sudo -iu maus openmausbot doctor+```++If the install fails, or the last line does not end with the server answering+and an engine ready, go back (replace `OLD` with the version you noted):++```sh+sudo systemctl stop openmausbot+sudo -iu maus npm install --global --prefix /home/maus/.local openmausbot@OLD+sudo -iu maus sh -c 'mv ~/.openmausbot ~/.openmausbot-failed-update && tar xzf ~/openmausbot-before-update.tgz -C ~'+sudo systemctl start openmausbot+```++A service restart by itself does not update the installed package. For+foreground `npx` usage, name the release: `npx --yes [email protected] serve --tunnel`.++### How far behind a server may fall++The desktop and phone apps are built to work with any server version that was+the stable one within the last 90 days. An older server keeps running, but the+app tells you it is behind, and newer features may not work until you update+it. Update at least every 90 days.Routines and queued work survive a restart; a turn running at that moment does not, so update between runs.diff --git a/deploy/.env.example b/deploy/.env.exampleindex 4ead3a93aa..12656bd5c3 100644--- a/deploy/.env.example+++ b/deploy/.env.example@@ -17,3 +17,7 @@ OMB_SIGNIN_MEMBER_EMAILS=# (docs/self-hosting.md). FROM defaults to the user name when it is an address.OMB_SIGNIN_SMTP_URL=OMB_SIGNIN_SMTP_FROM=++# The server image this install runs. `./update.sh` writes this line: the stable+# version, pinned by digest. Leave it out to follow `latest` (every main push).+# OMB_IMAGE=diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.ymlindex 8876a0dd94..b34dcb4e5b 100644--- a/deploy/docker-compose.yml+++ b/deploy/docker-compose.yml@@ -7,14 +7,16 @@# cp .env.example .env # set DOMAIN# docker compose pull omb && docker compose up -d # prebuilt image# docker compose up -d --build # or build from source+# ./update.sh # later: the stable version, with a way backservices:omb:build:context: ..args:ENGINES: ${ENGINES:-}- # prebuilt on every main push; `docker compose up --build` builds from source instead- image: ghcr.io/milind-soni/openmausbot:latest+ # update.sh pins OMB_IMAGE in .env to the stable version's digest. Without it: `latest`, prebuilt on every main+ # push; `docker compose up --build` builds from source instead.+ image: ${OMB_IMAGE:-ghcr.io/milind-soni/openmausbot:latest}restart: unless-stopped# The bots' browsers (docs/browser-packaging.md, "Process hygiene"): an# init collects the browser processes whose parents exit, and Chromediff --git a/deploy/e2e/update.sh b/deploy/e2e/update.shnew file mode 100755index 0000000000..9e39fcfe5f--- /dev/null+++ b/deploy/e2e/update.sh@@ -0,0 +1,171 @@+#!/usr/bin/env bash+# deploy/update.sh for real, on a host with Docker and nothing else running in it (CI, or a private docker:dind):+# a server on one released version, then --check, an update to a stable record naming the next release by digest, the+# same again (nothing to do), --rollback, an update to an image that never answers and damages the data (it must roll+# back and leave every file as it was), and an update killed with SIGKILL while it waits, finished by the next run.+# LAYOUT=installer /opt/openmausbot with compose.yaml and a ./data folder, as deploy/install.sh lays it out+# LAYOUT=checkout a copy of deploy/ with docker-compose.yml and the named volume `data`+# OUT=<evidence folder> LAYOUT=installer bash deploy/e2e/update.sh+# It removes whatever is in its install folder first. Nothing reaches a real server: the domain is made up.+set -uo pipefail+ROOT=$(cd "$(dirname "$0")/../.." && pwd)+OUT=${OUT:-$(mktemp -d)}+LAYOUT=${LAYOUT:-installer}+REPO=ghcr.io/milind-soni/openmausbot+FROM=${FROM_VERSION:-0.1.150}+TO=${TO_VERSION:-0.1.151}+mkdir -p "$OUT"+if [ "$LAYOUT" = installer ]; then DIR=/opt/openmausbot DATA=/opt/openmausbot/data COPY=openmausbot_data-before-update+else DIR=/srv/openmausbot-e2e/deploy DATA=deploy_data COPY=deploy_data-before-update; fi+UPDATE=(bash "$ROOT/deploy/update.sh" --dir "$DIR")++step() { printf '\n== %s\n' "$*"; }+fail() {+ printf 'FAILED: %s\n' "$*"+ (cd "$DIR" && docker compose logs --tail 40 omb) >"$OUT/omb.log" 2>&1+ exit 1+}+running_image() { docker inspect -f '{{.Image}}' "$(cd "$DIR" && docker compose ps -q omb)"; }+version() { (cd "$DIR" && docker compose exec -T omb curl -sf http://127.0.0.1:8799/.well-known/openmausbot/environment) | sed -n 's/.*"version":"\([^"]*\)".*/\1/p'; }+wait_version() { for _ in $(seq 1 60); do [ "$(version)" = "$1" ] && return 0; sleep 3; done; return 1; }+in_data() { docker run --rm --network none --user 0:0 -v "$DATA:/d" --entrypoint sh "$REPO:v$FROM" -c "$1"; }+# Every file of the data with its owner, mode and checksum. Read while the server is stopped.+manifest() { docker run --rm --network none --user 0:0 -v "$1:/d:ro" --entrypoint sh "$REPO:v$FROM" -c 'cd /d && find . -type f -print0 | sort -z | xargs -0 -r stat -c "%u:%g %a %n"; find . -type f -print0 | sort -z | xargs -0 -r sha256sum'; }++step "a $LAYOUT install on $FROM"+for old in /opt/openmausbot /srv/openmausbot-e2e/deploy; do+ if [ -d "$old" ]; then (cd "$old" && docker compose down -v) >/dev/null 2>&1; fi+done+docker volume rm -f "$COPY" >/dev/null 2>&1+rm -rf "$DIR" && mkdir -p "$DIR"+docker pull -q "$REPO:v$FROM" >/dev/null && docker pull -q "$REPO:v$TO" >/dev/null || fail "could not pull the two releases"+if [ "$LAYOUT" = installer ]; then+ mkdir -p "$DIR/caddy/data" "$DIR/caddy/config"+ cp "$ROOT/deploy/Caddyfile" "$DIR/Caddyfile"+ cat >"$DIR/compose.yaml" <<'COMPOSE'+name: openmausbot+services:+ omb:+ image: ${OMB_IMAGE:?run the installer again}+ restart: unless-stopped+ init: true+ shm_size: 512m+ volumes:+ - ./data:/data+ ports:+ - "80:80"+ - "443:443"+ environment:+ OMB_PORT: "8799"+ OMB_WEBHOOK_PORT: "8800"+ OMB_PUBLIC_URL: https://${DOMAIN}+ healthcheck:+ test: ["CMD-SHELL", "curl -sf http://127.0.0.1:8799/api/health | grep -q openmausbot"]+ interval: 30s+ timeout: 5s+ retries: 3+ caddy:+ image: caddy:2+ restart: unless-stopped+ network_mode: "service:omb"+ depends_on:+ omb:+ condition: service_healthy+ environment:+ DOMAIN: ${DOMAIN}+ volumes:+ - ./Caddyfile:/etc/caddy/Caddyfile:ro+ - ./caddy/data:/data+ - ./caddy/config:/config+COMPOSE+ owner=$(docker run --rm --network none --entrypoint id "$REPO:v$FROM" -u)+ mkdir -m 700 "$DIR/data" && chown "$owner:$owner" "$DIR/data"+else+ cp "$ROOT/deploy/docker-compose.yml" "$ROOT/deploy/Caddyfile" "$DIR/"+fi+printf '%s\n' '# settings' 'DOMAIN=update-e2e.invalid' "OMB_IMAGE=$REPO:v$FROM" >"$DIR/.env" && chmod 600 "$DIR/.env"+(cd "$DIR" && docker compose up -d --no-build) >/dev/null 2>&1 || fail "compose up"+wait_version "$FROM" || fail "$FROM did not come up"+(cd "$DIR" && docker compose exec -T omb sh -c "echo 'written under $FROM' > /data/.openmausbot/e2e-sentinel.txt")+OLD_ID=$(running_image)+cp "$DIR/.env" "$OUT/env.before"+STABLE=$(docker image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$REPO:v$TO" | grep "^$REPO@" | head -n 1)+printf '{\n "channel": "stable",\n "version": "%s",\n "image": "%s",\n "history": [{ "version": "%s", "promotedAt": "2026-11-12T00:00:00.000Z" }]\n}\n' "$TO" "$STABLE" "$TO" >"$OUT/stable.json"+export OMB_STABLE_URL="file://$OUT/stable.json"+echo "the stable record names $STABLE"++step "1. --check changes nothing"+"${UPDATE[@]}" --check | tee "$OUT/1-check.txt"+[ ! -e "$DIR/.update" ] || fail "--check wrote state"++step "2. update to the stable version"+"${UPDATE[@]}" | tee "$OUT/2-update.txt"+[ "${PIPESTATUS[0]}" = 0 ] || fail "the update did not exit 0"+[ "$(version)" = "$TO" ] || fail "the server says $(version)"+grep -qx "OMB_IMAGE=$STABLE" "$DIR/.env" || fail ".env is not pinned by digest"+[ "$(stat -c %a "$DIR/.env")" = 600 ] || fail ".env changed its mode"+in_data 'cat /d/.openmausbot/e2e-sentinel.txt' | grep -q "written under $FROM" || fail "the data did not carry over"+[ "$(cd "$DIR" && docker compose ps --status running --services | sort | tr '\n' ' ')" = "caddy omb " ] || fail "caddy or omb is not running"+docker volume inspect "$COPY" >/dev/null || fail "no copy of the data"++step "3. the same again: nothing to do"+"${UPDATE[@]}" | tee "$OUT/3-again.txt"+grep -q "Nothing to do" "$OUT/3-again.txt" || fail "the second run did something"++step "4. --rollback puts $FROM and its data back"+(cd "$DIR" && docker compose exec -T omb sh -c "echo 'written under $TO' > /data/.openmausbot/after-update.txt")+"${UPDATE[@]}" --rollback --yes | tee "$OUT/4-rollback.txt"+[ "${PIPESTATUS[0]}" = 0 ] || fail "--rollback did not exit 0"+[ "$(version)" = "$FROM" ] || fail "after --rollback the server says $(version)"+[ "$(running_image)" = "$OLD_ID" ] || fail "after --rollback another image runs"+cmp -s "$DIR/.env" "$OUT/env.before" || fail "after --rollback .env differs"+in_data 'test ! -e /d/.openmausbot/after-update.txt' || fail "data written after the update survived the rollback"++step "5. a new version that never answers and damages the data: rolled back, every file as it was"+docker build -q -t omb-e2e-broken:1 - >/dev/null <<DOCKERFILE+FROM $REPO:v$TO+CMD ["sh", "-c", "echo damaged > /data/.openmausbot/e2e-sentinel.txt; rm -f /data/.openmausbot/bots.json; echo x > /data/.openmausbot/left-by-the-broken-version; exec sleep 100000"]+DOCKERFILE+# From a stopped server, so the data the update copies aside is exactly this manifest.+(cd "$DIR" && docker compose stop) >/dev/null 2>&1+manifest "$DATA" >"$OUT/5-data-before.txt"+echo "files before: $(($(wc -l <"$OUT/5-data-before.txt") / 2))"+OMB_UPDATE_WAIT_S=45 "${UPDATE[@]}" --image omb-e2e-broken:1 | tee "$OUT/5-failed-update.txt"+[ "${PIPESTATUS[0]}" = 1 ] || fail "the failed update did not exit 1"+grep -q "did not work: it did not answer within 45 seconds" "$OUT/5-failed-update.txt" || fail "no plain reason"+grep -q "Your server runs $FROM again, with its data as it was before the update." "$OUT/5-failed-update.txt" || fail "no plain outcome"+[ "$(running_image)" = "$OLD_ID" ] || fail "after the rollback another image runs"+cmp -s "$DIR/.env" "$OUT/env.before" || fail "after the rollback .env differs"+manifest "$COPY" >"$OUT/5-copy.txt"+diff "$OUT/5-data-before.txt" "$OUT/5-copy.txt" >"$OUT/5-copy-vs-before.diff" || fail "the copy differs from the data before the update"+(cd "$DIR" && docker compose stop) >/dev/null 2>&1+manifest "$DATA" >"$OUT/5-data-after.txt"+diff "$OUT/5-data-before.txt" "$OUT/5-data-after.txt" >"$OUT/5-after-vs-before.diff"+echo "lines that differ once the old server has run again: $(grep -c '^[<>]' "$OUT/5-after-vs-before.diff")"+in_data 'grep -q "written under" /d/.openmausbot/e2e-sentinel.txt && test ! -e /d/.openmausbot/left-by-the-broken-version' || fail "the damage was not undone"+(cd "$DIR" && docker compose start) >/dev/null 2>&1+wait_version "$FROM" || fail "$FROM does not answer after the rollback"++step "6. an update killed while it waits is finished by the next run"+OMB_UPDATE_WAIT_S=120 "${UPDATE[@]}" --image omb-e2e-broken:1 >"$OUT/6-killed.txt" 2>&1 &+pid=$!+for _ in $(seq 1 180); do grep -q "^phase=wait" "$DIR/.update/journal" 2>/dev/null && break; sleep 1; done+grep -q "^phase=wait" "$DIR/.update/journal" || fail "the update never reached its wait"+sleep 3+kill -9 "$pid"+wait "$pid" 2>/dev/null+cat "$OUT/6-killed.txt"+[ -f "$DIR/.update/journal" ] || fail "no journal after the kill"+in_data 'grep -qx damaged /d/.openmausbot/e2e-sentinel.txt && test -e /d/.openmausbot/left-by-the-broken-version' || fail "the broken version did not damage the data, so this proves nothing"+echo "the killed update left the broken version running on damaged data"+OMB_UPDATE_WAIT_S=45 "${UPDATE[@]}" | tee "$OUT/6-next-run.txt"+grep -q "Your server runs $FROM again, with its data as it was before the update." "$OUT/6-next-run.txt" || fail "the next run did not put the old version back"+[ "$(running_image)" = "$OLD_ID" ] || fail "after the recovery another image runs"+in_data 'grep -q "written under" /d/.openmausbot/e2e-sentinel.txt' || fail "after the recovery the data is damaged"+cmp -s "$DIR/.env" "$OUT/env.before" || fail "after the recovery .env differs"+cp "$DIR/.update/update.log" "$OUT/update.log"++(cd "$DIR" && docker compose down -v) >/dev/null 2>&1+docker volume rm -f "$COPY" >/dev/null 2>&1+docker image rm -f omb-e2e-broken:1 openmausbot-before-update:local >/dev/null 2>&1+step "ALL PASSED ($LAYOUT)"diff --git a/deploy/update.sh b/deploy/update.shnew file mode 100755index 0000000000..2d765b786a--- /dev/null+++ b/deploy/update.sh@@ -0,0 +1,414 @@+#!/usr/bin/env bash+# Updates this Docker Compose install to the stable version, with a way back:+#+# ./update.sh the stable version+# ./update.sh --version X.Y.Z one released version+# ./update.sh --check say what would change, and change nothing+# ./update.sh --rollback put back the version and the data from before the last update+# ./update.sh --dir PATH the install's folder, when it is not this one (the installer's: /opt/openmausbot)+#+# It runs on the server itself, beside docker-compose.yml, because a server cannot replace its own container. The steps+# are the ones the MausBot connector runs for a connected server (connector/src/home.ts `update`): download the new+# image by digest, stop the server, copy its data aside, start the new image, and wait until it answers and can still+# start bots. When it does not, the old image and the copy are put back. Each step is written to .update/journal+# before it starts, so an update that was interrupted (Ctrl-C, a closed terminal, a reboot) is finished safely by+# the next run, and a second run of a finished update changes nothing.+#+# Exit codes: 0 done or nothing to do, 1 the update failed and the old version is back, 2 the old version could not be+# brought back either, 3 another update is running, 4 nothing was changed (refused, or could not download).+set -uo pipefail++REPO="ghcr.io/milind-soni/openmausbot"+PINNED="^ghcr\.io/milind-soni/openmausbot@sha256:[0-9a-f]{64}$"+STABLE_URL=${OMB_STABLE_URL:-https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json}+SERVICE=${OMB_UPDATE_SERVICE:-omb}+WAIT_S=${OMB_UPDATE_WAIT_S:-300}+POLL_S=${OMB_UPDATE_POLL_S:-5}+KEEP_TAG="openmausbot-before-update:local"++# The install: --dir, else the folder this script is in when that holds a Compose file, else where the installer+# (deploy/install.sh) puts one.+DIR=${OMB_INSTALL_DIR:-}+want_dir=no+for arg in "$@"; do+ if [ "$want_dir" = yes ]; then DIR=$arg; want_dir=no; elif [ "$arg" = --dir ]; then want_dir=yes; fi+done+if [ -z "$DIR" ]; then+ DIR=$(cd "$(dirname "$0")" && pwd)+ if [ ! -f "$DIR/docker-compose.yml" ] && [ ! -f "$DIR/compose.yaml" ] && [ -f /opt/openmausbot/compose.yaml ]; then DIR=/opt/openmausbot; fi+fi+STATE="$DIR/.update"+JOURNAL="$STATE/journal"+LAST="$STATE/last"+LOCK="$STATE/lock"+LOG="$STATE/update.log"+cd "$DIR" 2>/dev/null || { printf '%s\n' "There is no folder $DIR."; exit 4; }+# The pin is read from .env, never from the shell that happens to run this.+unset OMB_IMAGE++# A step interrupted while its output goes to the log still speaks to the terminal.+exec 3>&1+say() {+ printf '%s\n' "$*" >&3+ if [ -d "$STATE" ]; then printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"$LOG"; fi+}+refuse() {+ say "$*"+ exit 4+}+compose() { docker compose "$@"; }+container() { compose ps -aq "$SERVICE" 2>/dev/null | head -n 1; }+inspect() { docker inspect -f "$1" "$2" 2>/dev/null; }+image_id() { docker image inspect -f '{{.Id}}' "$1" 2>/dev/null; }+published_ref() { docker image inspect -f '{{range .RepoDigests}}{{println .}}{{end}}' "$1" 2>/dev/null | grep "^$REPO@" | head -n 1; }+image_version() { docker image inspect -f '{{index .Config.Labels "org.opencontainers.image.version"}}' "$1" 2>/dev/null | sed -n 's/^v\{0,1\}\([0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\)$/\1/p'; }+name_of() { if [ -n "${2:-}" ]; then printf '%s' "$2"; else printf '%s' "$1" | sed 's/^.*sha256:\(.\{12\}\).*$/image \1/'; fi; }+old_name() { name_of "${J_previous:-$J_previous_id}" "$J_previous_version"; }+new_name() { name_of "$J_target" "$J_version"; }++# The journal: one `key=value` per line, written whole and renamed into place.+J_phase="" J_target="" J_target_id="" J_version="" J_previous="" J_previous_id="" J_previous_version=""+J_data="" J_backup="" J_engine="" J_caddy="" J_running=""+JOURNAL_KEYS="phase target target_id version previous previous_id previous_version data backup engine caddy running"+write_record() {+ local file=$1 key+ for key in $JOURNAL_KEYS; do eval "printf '%s=%s\n' \"$key\" \"\$J_$key\""; done >"$file.tmp" && mv "$file.tmp" "$file"+}+read_record() {+ local file=$1 key value+ [ -f "$file" ] || return 1+ while IFS='=' read -r key value; do+ case " $JOURNAL_KEYS " in *" $key "*) eval "J_$key=\$value" ;; esac+ done <"$file"+}+phase() {+ J_phase=$1+ write_record "$JOURNAL"+}++take_lock() {+ mkdir -p "$STATE" && chmod 700 "$STATE"+ if ! mkdir "$LOCK" 2>/dev/null; then+ local other+ other=$(cat "$LOCK/pid" 2>/dev/null || true)+ if [ -n "$other" ] && kill -0 "$other" 2>/dev/null; then+ printf '%s\n' "An update is already running here (process $other). Wait for it to finish."+ exit 3+ fi+ rm -rf "$LOCK"+ mkdir "$LOCK" || exit 3+ fi+ echo $$ >"$LOCK/pid"+ trap 'rm -rf "$LOCK"' EXIT+}++# The copies run in a short-lived container from the server's own image, as root and without a network.+copy_aside() { # data backup image+ docker volume rm -f "$2" >/dev/null 2>&1+ docker volume create --label com.mausbot.role=update-backup --label "com.mausbot.image=$3" "$2" >/dev/null || return 1+ docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint cp "$3" -a /from/. /to/+}+put_back() { # backup data image+ docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" -v "$2:/to" --entrypoint sh "$3" \+ -c 'find /to -mindepth 1 -delete && cp -a /from/. /to/'+}+room_for_copy() { # data image → 0 when there is room, or when it cannot be measured+ local sizes used free+ sizes=$(docker run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v "$1:/from:ro" --entrypoint sh "$2" \+ -c 'du -sk /from | cut -f1; df -Pk /from | tail -n 1 | tr -s " " | cut -d" " -f4' 2>/dev/null) || return 0+ used=$(printf '%s\n' "$sizes" | sed -n 1p)+ free=$(printf '%s\n' "$sizes" | sed -n 2p)+ case "$used$free" in '' | *[!0-9]*) return 0 ;; esac+ NEEDED_MB=$(((used + used / 10) / 1024 + 1024))+ FREE_MB=$((free / 1024))+ [ "$FREE_MB" -ge "$NEEDED_MB" ]+}++pin_image() { # writes OMB_IMAGE=<ref> into .env, keeping every other line and the file's mode+ local tmp="$DIR/.env.update.tmp"+ if [ -f .env ]; then cp -p .env "$tmp" && grep -v '^OMB_IMAGE=' .env >"$tmp"; else : >"$tmp" && chmod 600 "$tmp"; fi+ printf 'OMB_IMAGE=%s\n' "$1" >>"$tmp" && mv "$tmp" .env+}+keep_env() {+ rm -f "$STATE/env.before" "$STATE/env.absent"+ if [ -f .env ]; then cp -p .env "$STATE/env.before" && chmod 600 "$STATE/env.before"; else : >"$STATE/env.absent"; fi+}+restore_env() {+ if [ -f "$STATE/env.before" ]; then cp -p "$STATE/env.before" "$DIR/.env.update.tmp" && mv "$DIR/.env.update.tmp" .env+ elif [ -f "$STATE/env.absent" ]; then rm -f .env; fi+}++answers() { compose exec -T "$SERVICE" sh -c 'curl -sf --max-time 5 "http://127.0.0.1:${OMB_PORT:-8799}/api/health"' 2>/dev/null | grep -q openmausbot; }+reported_version() {+ compose exec -T "$SERVICE" sh -c 'curl -sf --max-time 5 "http://127.0.0.1:${OMB_PORT:-8799}/.well-known/openmausbot/environment"' 2>/dev/null \+ | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'+}+# `openmausbot doctor`: the server answers and at least one engine can start a bot.+engine_ready() { compose exec -T "$SERVICE" openmausbot doctor ${1:+--wait "$1"} >/dev/null 2>&1; }+caddy_runs() { compose ps --status running --services 2>/dev/null | grep -qx caddy; }+last_words() { compose logs --no-color --no-log-prefix --tail 40 "$SERVICE" 2>/dev/null | grep -v '^[[:space:]]*$' | tail -n 1 | cut -c 1-300; }++# The server runs image $1, answers /api/health three times in a row, and (with $2) says it is version $2. Sets WHY.+wait_healthy() {+ local want=$1 version=${2:-} deadline=$(($(date +%s) + WAIT_S)) streak=0 cid state status restarts image said+ WHY=""+ while :; do+ cid=$(container)+ if [ -z "$cid" ]; then WHY="its container is gone"; return 1; fi+ state=$(inspect '{{.State.Status}} {{.RestartCount}} {{.Image}}' "$cid")+ status=${state%% *}+ restarts=$(printf '%s' "$state" | cut -d' ' -f2)+ image=${state##* }+ if [ "$image" != "$want" ]; then WHY="the server is not running the image it should"; return 1; fi+ case "$status" in+ exited | dead) WHY="it stopped as it started ($(last_words))"; return 1 ;;+ esac+ if [ "${restarts:-0}" -ge 3 ] 2>/dev/null; then WHY="it kept stopping as it started ($(last_words))"; return 1; fi+ if [ "$status" = running ] && answers; then streak=$((streak + 1)); else streak=0; fi+ [ "$streak" -ge 3 ] && break+ if [ "$(date +%s)" -ge "$deadline" ]; then WHY="it did not answer within $WAIT_S seconds"; return 1; fi+ sleep "$POLL_S"+ done+ if [ -n "$version" ]; then+ said=$(reported_version)+ if [ "$said" != "$version" ]; then WHY="it says it is version ${said:-unknown}, not $version"; return 1; fi+ fi+}+# What worked before the update still works: an engine that could start a bot, and Caddy in front.+wait_whole() {+ local tries=0+ if [ "$J_engine" = ready ] && ! engine_ready 2m; then WHY="no engine can start a bot on it, and one could before"; return 1; fi+ if [ "$J_caddy" = running ]; then+ until caddy_runs; do+ tries=$((tries + 1))+ if [ "$tries" -ge 12 ]; then WHY="Caddy, which serves it to the internet, did not start again"; return 1; fi+ sleep "$POLL_S"+ done+ fi+}++finish() {+ cp "$JOURNAL" "$LAST.tmp" && mv "$LAST.tmp" "$LAST"+ rm -f "$JOURNAL"+ say "Updated from $(old_name) to $(new_name)."+ say "The data from before the update is kept in the Docker volume $J_backup until the next update."+ say "To go back to it: ./update.sh --rollback"+}++# Puts back the settings, the data and the image from before the update, then says what happened and exits.+roll_back() { # why, exit code when the old version is back+ local why=$1 code=$2 helper_image=$J_previous_id restored=yes back=no+ trap '' INT TERM+ phase rollback+ say "$why"+ say "Putting back the version and the data from before the update…"+ compose stop >/dev/null 2>&1+ restore_env+ if docker volume inspect "$J_backup" >/dev/null 2>&1; then+ put_back "$J_backup" "$J_data" "$helper_image" >>"$LOG" 2>&1 || restored=no+ else+ restored=missing+ fi+ compose up -d --no-build >>"$LOG" 2>&1+ if [ "$(inspect '{{.Image}}' "$(container)")" != "$J_previous_id" ]; then+ # .env named a tag that has moved since: the image kept aside at the swap is the one that ran.+ pin_image "$KEEP_TAG"+ compose up -d --no-build >>"$LOG" 2>&1+ fi+ if wait_healthy "$J_previous_id"; then back=yes; fi+ rm -f "$JOURNAL" "$LAST"+ if [ "$restored" = missing ]; then+ say "The copy of the data from before the update ($J_backup) is missing, so the data was left as it is. The server runs $(old_name) again."+ exit 2+ fi+ if [ "$restored" = no ]; then+ say "The data could not be put back from the Docker volume $J_backup (see $LOG). That volume still holds it. Do not run another update before the data is back."+ exit 2+ fi+ if [ "$back" = no ]; then+ say "$(old_name) and its data are back, but it did not become healthy either ($WHY). See: docker compose logs $SERVICE"+ exit 2+ fi+ say "Your server runs $(old_name) again, with its data as it was before the update."+ exit "$code"+}++# Finishes an update that was cut short. `signal`: this run was interrupted; otherwise an earlier one was.+recover() {+ local how=${1:-}+ read_record "$JOURNAL" || return 0+ case "$J_phase" in+ pull)+ rm -f "$JOURNAL"+ [ -n "$how" ] && say "Stopped before anything was changed."+ ;;+ backup)+ docker volume rm -f "$J_backup" >/dev/null 2>&1+ [ "$J_running" = yes ] && compose up -d --no-build >>"$LOG" 2>&1+ rm -f "$JOURNAL"+ say "The update stopped while it copied the data aside. Nothing was changed, and the server was started again."+ ;;+ wait)+ if [ -z "$how" ] && WAIT_S=60 wait_healthy "$J_target_id" "$J_version" && wait_whole; then+ say "The last update was interrupted after the new version had started, and it is healthy."+ finish+ return 0+ fi+ roll_back "The update to $(new_name) was interrupted before the new version proved healthy." 1+ ;;+ swap | rollback)+ roll_back "The update to $(new_name) was interrupted." 1+ ;;+ *) rm -f "$JOURNAL" ;;+ esac+}+interrupted() {+ trap '' INT TERM+ say ""+ say "Interrupted."+ recover signal+ exit 130+}++usage() {+ sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'+ exit "${1:-0}"+}++MODE=update WANT_VERSION="" WANT_IMAGE="" ASSUME_YES=no REPLACE_BUILD=no+while [ $# -gt 0 ]; do+ case "$1" in+ --version) [ $# -ge 2 ] || usage 4; WANT_VERSION=${2#v}; shift ;;+ --image) [ $# -ge 2 ] || usage 4; WANT_IMAGE=$2; shift ;;+ --dir) [ $# -ge 2 ] || usage 4; shift ;;+ --check) MODE=check ;;+ --rollback) MODE=rollback ;;+ --yes | -y) ASSUME_YES=yes ;;+ --replace-local-build) REPLACE_BUILD=yes ;;+ -h | --help) usage 0 ;;+ *) printf 'Unknown option: %s\n\n' "$1"; usage 4 ;;+ esac+ shift+done+if [ -n "$WANT_VERSION" ] && ! printf '%s' "$WANT_VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then refuse "--version takes a released version such as 0.1.151."; fi++docker compose version >/dev/null 2>&1 || refuse "This needs Docker with the Compose plugin (docker compose version)."+[ -f docker-compose.yml ] || [ -f compose.yaml ] || [ -n "${COMPOSE_FILE:-}" ] || refuse "There is no docker-compose.yml or compose.yaml in $DIR. Name the install's folder: ./update.sh --dir PATH"++if [ "$MODE" != check ]; then+ take_lock+ trap interrupted INT TERM+ recover+fi++if [ "$MODE" = rollback ]; then+ read_record "$LAST" || refuse "There is no earlier update to go back from."+ if [ "$ASSUME_YES" != yes ]; then+ printf '%s\n' "This puts back $(old_name) and the data as it was before the last update."+ printf '%s' "Everything made since then (chats, files, settings) is lost. Type yes to go on: "+ read -r answer+ [ "$answer" = yes ] || refuse "Nothing was changed."+ fi+ roll_back "Going back, as asked." 0+fi++CID=$(container)+[ -n "$CID" ] || refuse "This install has no server yet. Start it once first: docker compose up -d"+J_previous_id=$(inspect '{{.Image}}' "$CID")+J_previous=$(published_ref "$J_previous_id")+J_previous_version=$(image_version "$J_previous_id")+J_data=$(inspect '{{range .Mounts}}{{if eq .Destination "/data"}}{{if eq .Type "volume"}}{{.Name}}{{else}}{{.Source}}{{end}}{{end}}{{end}}' "$CID")+PROJECT=$(inspect '{{index .Config.Labels "com.docker.compose.project"}}' "$CID")+J_backup="${PROJECT:-deploy}_data-before-update"+[ -n "$J_data" ] || refuse "The server's container has no /data volume, so its data cannot be copied aside. Nothing was changed."+if [ "$(inspect '{{.State.Running}}' "$CID")" = true ]; then J_running=yes; else J_running=no; fi++if [ -n "$WANT_IMAGE" ]; then+ J_target=$WANT_IMAGE+ J_version=""+elif [ -n "$WANT_VERSION" ]; then+ J_target="$REPO:v$WANT_VERSION"+ J_version=$WANT_VERSION+else+ if command -v curl >/dev/null 2>&1; then RECORD=$(curl -fsSL --max-time 20 "$STABLE_URL" 2>/dev/null)+ else RECORD=$(wget -qO- -T 20 "$STABLE_URL" 2>/dev/null); fi+ [ -n "${RECORD:-}" ] || refuse "Could not read the stable channel ($STABLE_URL). Nothing was changed. To name a version yourself: ./update.sh --version X.Y.Z"+ RECORD=$(printf '%s' "$RECORD" | tr -d '\n\r')+ J_target=$(printf '%s' "$RECORD" | sed -n 's/.*"image"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')+ J_version=$(printf '%s' "$RECORD" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([0-9][0-9.]*\)".*/\1/p')+ printf '%s' "$J_target" | grep -Eq "$PINNED" || refuse "The stable channel names no image this script accepts. Nothing was changed."+fi++if [ "$MODE" = check ]; then+ printf '%s\n' "This server runs $(old_name)."+ if [ -n "$J_previous" ] && [ "$J_previous" = "$J_target" ]; then printf '%s\n' "That is the version asked for. Nothing to do."+ else printf '%s\n' "./update.sh would update it to $(new_name)."; fi+ exit 0+fi++if [ -z "$J_previous" ] && [ "$REPLACE_BUILD" != yes ]; then+ refuse "This server runs an image built on this machine (docker compose up --build), with whatever ENGINES you baked into it. To stay on your own build: git pull && docker compose up -d --build. To move to the published image instead: ./update.sh --replace-local-build"+fi++phase pull+say "Downloading $(new_name)…"+if ! docker pull -q "$J_target" >>"$LOG" 2>&1 && [ -z "$(image_id "$J_target")" ]; then+ rm -f "$JOURNAL"+ refuse "Could not download $J_target (see $LOG). Nothing was changed."+fi+J_target_id=$(image_id "$J_target")+case "$J_target" in+ *@sha256:*) ;;+ *) PUBLISHED=$(published_ref "$J_target_id"); [ -n "$PUBLISHED" ] && J_target=$PUBLISHED ;;+esac+[ -n "$J_version" ] || J_version=$(image_version "$J_target_id")++if [ "$J_target_id" = "$J_previous_id" ]; then+ rm -f "$JOURNAL"+ say "This server already runs $(new_name). Nothing to do."+ exit 0+fi+if ! OMB_IMAGE="$J_target" docker compose config 2>/dev/null | grep -qF "image: $J_target"; then+ rm -f "$JOURNAL"+ refuse "The Compose file in $DIR does not take its image from OMB_IMAGE. Get the current one (git pull, or run the installer again), then run this again. Nothing was changed."+fi+if ! room_for_copy "$J_data" "$J_previous_id"; then+ rm -f "$JOURNAL"+ refuse "There is not enough free disk for a copy of the data: it needs about $NEEDED_MB MB and $FREE_MB MB are free. Free some space, then run this again. Nothing was changed."+fi++J_engine=unknown+J_caddy=stopped+if [ "$J_running" = yes ]; then+ engine_ready && J_engine=ready+ caddy_runs && J_caddy=running+fi++phase backup+say "Stopping the server and copying its data aside…"+rm -f "$LAST"+compose stop >>"$LOG" 2>&1+if ! copy_aside "$J_data" "$J_backup" "$J_previous_id" >>"$LOG" 2>&1; then+ docker volume rm -f "$J_backup" >/dev/null 2>&1+ [ "$J_running" = yes ] && compose up -d --no-build >>"$LOG" 2>&1+ rm -f "$JOURNAL"+ refuse "Copying the data aside failed (see $LOG). Nothing was changed, and the server was started again."+fi+keep_env+docker tag "$J_previous_id" "$KEEP_TAG" >/dev/null 2>&1++phase swap+say "Starting $(new_name)…"+pin_image "$J_target"+# Where Caddy waits for a healthy server, `up` itself fails when the new version never gets there; the wait below+# then says why.+if ! compose up -d --no-build >>"$LOG" 2>&1 && [ "$(inspect '{{.Image}}' "$(container)")" != "$J_target_id" ]; then+ roll_back "Docker could not start $(new_name) (see $LOG)." 1+fi++phase wait+say "Waiting for it to answer and to be able to start bots…"+if ! wait_healthy "$J_target_id" "$J_version" || ! wait_whole; then+ roll_back "The update to $(new_name) did not work: $WHY." 1+fi+finishdiff --git a/docs/deploy-vps.md b/docs/deploy-vps.mdindex 4ec5e9eb25..4f3b13079c 100644--- a/docs/deploy-vps.md+++ b/docs/deploy-vps.md@@ -114,6 +114,7 @@ One container for the server plus Caddy for HTTPS at `https://maus.example.com`.```shdocker compose pull omb && docker compose up -d+ ./update.sh # move to the stable version (see "Update")docker compose ps # omb "healthy", caddy "running"```@@ -258,19 +259,120 @@ same release without an npm install prompt or an implicit upgrade.## Update-- **Paths A and C with the service above:** choose the new published version,- then run these commands from the administrator shell, replacing `X.Y.Z`:+A self-hosted server follows the **stable** channel: a released version that+MausBot's own Clouds have run for 48 hours first. The image tag `stable` and+[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)+name it. The tag `latest` follows every change on `main`; it is for trying+things out, not for a server you rely on. **Check for updates** in the app+compares your server with the stable version. To hear of every release as soon+as it is published instead, set `OMB_UPDATE_CHANNEL=newest` in the server's+environment.- ```sh- sudo systemctl stop openmausbot- sudo -iu maus npm install --global --prefix /home/maus/.local [email protected]- sudo systemctl start openmausbot- ```+### Path B (Docker): one command, with a way back- Check that installation succeeded before starting. A service restart by itself- does not update the installed package. For foreground `npx` usage, specify the- desired release as `npx --yes [email protected] serve --tunnel`.-- **Path B:** `cd OpenMausBot/deploy && docker compose pull omb && docker compose up -d`.+From `OpenMausBot/deploy`:++```sh+git pull && ./update.sh+```++`git pull` brings the current `update.sh` and `docker-compose.yml`; the server+image comes from the stable channel, not from your checkout. An install that+has no checkout, with its `compose.yaml`, `.env` and `data/` in one folder such+as `/opt/openmausbot`, runs the same script on that folder:++```sh+curl -fsSL https://raw.githubusercontent.com/milind-soni/OpenMausBot/main/deploy/update.sh -o update.sh+sudo bash update.sh --dir /opt/openmausbot+```++The data may be a Docker volume or a folder on the server; the copy keeps+every file's owner and mode either way. The script then:++1. Downloads the stable image, by its digest. If that fails it stops, and+ nothing has changed.+2. Checks there is room for a copy of your data, stops the server, and copies+ everything under `/data` into a Docker volume+ (`deploy_data-before-update`; `openmausbot_data-before-update` for+ `/opt/openmausbot`). The server is down from here until step 4;+ how long depends on how much data there is.+3. Writes the image into `.env` (`OMB_IMAGE=ghcr.io/milind-soni/openmausbot@sha256:…`)+ and starts it.+4. Waits, up to five minutes, until the new server answers `/api/health`+ steadily, says it is the new version, can still start a bot if it could+ before (`openmausbot doctor`: an engine is ready), and Caddy runs again.+5. If any of that fails: puts back `.env`, the data from the copy and the old+ image, starts the old version, and tells you what went wrong. Your server+ is as it was before step 1.++It is safe to interrupt and to run twice. Each step is written to+`deploy/.update/journal` before it starts, so after Ctrl-C, a closed terminal or+a reboot, the next `./update.sh` first finishes what was cut short: it keeps+the new version if that is up and healthy, and otherwise puts the old one+back. Run again after a finished update, it says there is nothing to do. Two+runs at once are refused.++```sh+./update.sh --check # what would change; changes nothing+./update.sh --version 0.1.151 # one released version instead of the stable one+./update.sh --rollback # the version and the data from before the last update+```++`--rollback` is for an update that passed its checks and still turned out+wrong. It asks first, because everything made since the update (chats, files,+settings) is replaced by the copy. The copy is kept until the next update+replaces it. The script's own log is `deploy/.update/update.log`.++| The script ends with | Meaning |+| --- | --- |+| `0` | Updated, or already on that version |+| `1` | The update failed; the old version and its data are back |+| `2` | The update failed and the old version did not come back healthy; read the last lines it printed |+| `3` | Another update is running |+| `4` | Nothing was changed (could not download, not enough disk, refused) |++If you built the image yourself (`docker compose up -d --build`, with+`ENGINES` baked in), `update.sh` refuses to replace it without being told to:+keep updating with `git pull && docker compose up -d --build`, or move to the+published image with `./update.sh --replace-local-build`. Engines you install+from **Settings → Engines** live on the data volume and survive either way.++### Paths A and C (npm with the service above): the same steps by hand++There is no one-command updater for an npm install yet. Do what the script+does: copy the data first, install one named version, check it, and keep the+way back. Take the stable version number from+[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json)+(`"version"`), and note the one you run now (`openmausbot --version`). From+the administrator shell, replacing `X.Y.Z`:++```sh+sudo systemctl stop openmausbot+sudo -iu maus sh -c 'umask 077; tar czf ~/openmausbot-before-update.tgz -C ~ .openmausbot'+sudo -iu maus npm install --global --prefix /home/maus/.local [email protected]+sudo systemctl start openmausbot+curl -sf http://127.0.0.1:8799/api/health && sudo -iu maus openmausbot doctor+```++If the install fails, or the last line does not end with the server answering+and an engine ready, go back (replace `OLD` with the version you noted):++```sh+sudo systemctl stop openmausbot+sudo -iu maus npm install --global --prefix /home/maus/.local openmausbot@OLD+sudo -iu maus sh -c 'mv ~/.openmausbot ~/.openmausbot-failed-update && tar xzf ~/openmausbot-before-update.tgz -C ~'+sudo systemctl start openmausbot+```++A service restart by itself does not update the installed package. For+foreground `npx` usage, name the release: `npx --yes [email protected] serve --tunnel`.++### How far behind a server may fall++The desktop and phone apps are built to work with any server version that was+the stable one within the last 90 days. An older server keeps running, but the+app tells you it is behind, and newer features may not work until you update+it. Update at least every 90 days.Routines and queued work survive a restart. A teammate turn running at that moment runs again once at the next start, told to check what it already did, and the bot that asked for it is told. A person's own turn and a running routine are not run again: the conversation says it was interrupted. Update between runs where you can.diff --git a/docs/releasing.md b/docs/releasing.mdindex 70485641d9..8439f4b999 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -47,6 +47,61 @@ Configure the optional Vercel hook below to rebuild the docs immediately afterpublication; otherwise the live cache or the next normal docs deploymentrefreshes it.+## Promote a release to stable++Self-hosted servers do not follow the newest release: they follow `stable`.+A release becomes stable only after our own Clouds have run it for 48 hours.+Then run **Actions → Promote to stable → Run workflow** with the version+(`X.Y.Z`) and tick that the 48 hours are done.++The workflow builds nothing. It:++1. refuses a version that is not a published, full release, or that was+ published less than 48 hours ago (`urgent` skips the wait, for a fix that+ cannot wait);+2. checks that the release's server image has `linux/amd64` and `linux/arm64`,+ and reads its digest and the Cloud home image's;+3. refuses to move stable back to an older version unless `allow_older` is+ ticked;+4. moves the `stable` tag of `ghcr.io/milind-soni/openmausbot` and of+ `ghcr.io/milind-soni/openmausbot-cloud-home` to those digests;+5. commits `stable.json` (version, both images by digest, and every version+ that was stable in the last 90 days) to the `channels` branch.++Servers read+`https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json`:+the update check (`server/update-check.ts`) for the version, and+`deploy/update.sh` for the image to pull. `latest` still follows `main` and is+never moved by this workflow. Running it again with the same version changes+nothing, and repairs a run that stopped between the tag and the record. The+`channels` branch is written only by this workflow; do not edit it by hand.+The checks live in `scripts/stable-channel.mjs`.++### How a server takes an update++One routine, in the two places that can run it. A server cannot replace its+own container, so neither is the server process: a connected server's update+is the connector's `update` job, and a standalone Docker Compose install's is+`deploy/update.sh`, run on the host by its owner. They are two programs (the+connector drives a container it made itself through the Docker API and has no+shell; a Compose install has to be swapped by `docker compose` on the host),+held to the same steps and the same promises:++| Step | Connector (`connector/src/home.ts`) | Standalone (`deploy/update.sh`) |+| --- | --- | --- |+| Image by digest, before anything stops | `ensureImage`, `checkImage` | `docker pull` of the record's `…@sha256:…` |+| Room for the copy | `ensureRoomForCopy` | `room_for_copy` |+| Stop, copy `/data` aside | `stopAndCopy` → volume `mausbot-snapshot` | `copy_aside` → volume `<project>_data-before-update` |+| Start the new image | `createContainer`, `startHome` | `OMB_IMAGE` in `.env`, `docker compose up -d` |+| Healthy, and bots can start | signed health report names the image; the bot box still passes every check it passed before | `/api/health` three times running, the version it reports, `openmausbot doctor` if it passed before, Caddy |+| On failure | `rollBack`: old image and the copy, reply `update_rolled_back` | `roll_back`: `.env`, the copy and the old image, exit 1 with the reason |+| Interrupted | the operation in `home.json`; `recover` at the next start | `.update/journal`; the next run, or the signal handler |+| Run twice | a job id is answered again, never run again | "already runs …, nothing to do" |++`connector/test/home.test.ts` and `connector/e2e/run.sh` hold the connector to+this; `scripts/testing/deploy-update.test.ts` holds the script to it. A change+to one side's steps belongs in the other too.+## Updater migration invariant`app-update.yml` is baked into every packaged desktop app. Builds throughdiff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex 4d795a1a89..0ba0e37b12 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -340,9 +340,11 @@ cp .env.example .env # set DOMAINdocker compose pull omb && docker compose up -d```-That uses the image CI publishes on every `main` push-(`ghcr.io/milind-soni/openmausbot`, tagged `latest`, `sha-…` and `v…`).-To build from your checkout instead: `docker compose up -d --build`.+That starts the image CI publishes on every `main` push+(`ghcr.io/milind-soni/openmausbot:latest`; each release is also tagged `v…`,+and the one our own Clouds have run for 48 hours is `stable`). Move to the+stable version right away with `./update.sh`, which pins it by digest in+`.env`. To build from your checkout instead: `docker compose up -d --build`.Then sign the engine CLIs in **inside the container** (their logins live onthe `data` volume, so they survive restarts and image upgrades) and mint a@@ -373,9 +375,12 @@ What the stack does, so you can adapt it:own pairing is the login. A shared-password `basic_auth` block is there,commented out, if you want a second wall in front of pairing.-Upgrade with `docker compose pull omb && docker compose up -d` (or-`git pull && docker compose up -d --build`). State (chats, routines,-engine logins, paired sessions) is on the `data` volume; back that up.+Update with `git pull && ./update.sh`: it copies the data aside, starts the+stable version, and puts the old version and the data back if the new one+does not come up healthy ([what it does, step by step](deploy-vps.md#update)).+A build from source updates with `git pull && docker compose up -d --build`.+State (chats, routines, engine logins, paired sessions) is on the `data`+volume; back that up.The published image installs the current Chrome for Testing whenever a newStable ships. A build from source keeps the Chrome (and any `ENGINES`) it@@ -1436,16 +1441,35 @@ settings do not change it.## Updating-For the npm service, [install the chosen new version](deploy-vps.md#update)-as the service user while the server is stopped, then start it again.-For a foreground invocation, `npx --yes [email protected] serve --tunnel`-selects a particular published release; replace `X.Y.Z` with that version.+Self-hosted servers follow the **stable** channel: a released version that our+own Clouds have run for 48 hours, named by the image tag `stable` and by+[`stable.json`](https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json).+`latest` follows `main` and is not for a server you rely on. The update check+(`GET /api/updates/check`, **Check for updates** in the app) compares the+server with the stable version; `OMB_UPDATE_CHANNEL=newest` makes it follow+every release instead.```sh-docker compose -f deploy/docker-compose.yml pull omb && docker compose -f deploy/docker-compose.yml up -d # Docker+cd deploy && git pull && ./update.sh # Docker: copy the data, update, roll back on failuregit pull && pnpm install && sudo systemctl restart openmausbot # from source```+`deploy/update.sh` is the whole routine for a Docker Compose install: the+stable image by digest, a copy of `/data` first, a health check that includes+"an engine can still start a bot", and the old image and the copy put back+when the check fails. It is safe to interrupt and to run twice.+[Every step, the rollback and the exit codes](deploy-vps.md#update).++For the npm service there is no one-command updater yet:+[do the same steps by hand](deploy-vps.md#paths-a-and-c-npm-with-the-service-above-the-same-steps-by-hand),+as the service user while the server is stopped. For a foreground invocation,+`npx --yes [email protected] serve --tunnel` selects a particular published+release; replace `X.Y.Z` with that version.++The desktop and phone apps work with any server version that was the stable+one within the last 90 days. An older server keeps running, but the app says+it is behind, and newer features may not work until it is updated.+Routines and queued work survive restarts. A teammate turn in flight runsagain once at the next start, told to check what it already did, and the botthat asked for it is told. A person's own turn and a running routine are notdiff --git a/scripts/stable-channel.mjs b/scripts/stable-channel.mjsnew file mode 100644index 0000000000..83973e3fc0--- /dev/null+++ b/scripts/stable-channel.mjs@@ -0,0 +1,113 @@+// The checks and the record behind .github/workflows/promote-stable.yml: which released version the `stable` channel+// names. The record is stable.json on the `channels` branch, which a self-hosted server reads over plain HTTPS+// (server/update-check.ts, deploy/update.sh): no registry API, no token.+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++/** How long our own Clouds run a release before it may be promoted. */+export const SOAK_MS = 48 * 60 * 60_000;+/** Apps work with any server that was the stable one within this long; the record keeps that much history. */+export const SKEW_DAYS = 90;+const DAY_MS = 24 * 60 * 60_000;++/** "v0.1.151" or "0.1.151" → "0.1.151"; anything else, a prerelease included, is refused. */+export function stableVersion(input) {+ const match = /^v?(\d+\.\d+\.\d+)$/.exec(String(input ?? "").trim());+ if (!match) throw new Error(`"${input}" is not a released version: give it as X.Y.Z, such as 0.1.151`);+ return match[1];+}++const parts = (version) => version.split(".").map(Number);+/** Negative when `a` is older than `b`. */+export function compareVersions(a, b) {+ const [x, y] = [parts(a), parts(b)];+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] - y[i];+ return 0;+}++/** `release`: `gh release view --json tagName,isDraft,isPrerelease,publishedAt,url`. Throws unless it is published and soaked. */+export function checkRelease(release, version, { now, urgent = false }) {+ if (release?.tagName !== `v${version}`) throw new Error(`v${version} is not a release of this repository`);+ if (release.isDraft) throw new Error(`v${version} is still a draft: publish it first`);+ if (release.isPrerelease) throw new Error(`v${version} is a prerelease, and stable only takes full releases`);+ const published = Date.parse(release.publishedAt ?? "");+ if (!Number.isFinite(published)) throw new Error(`v${version} has no publish date`);+ const waited = now - published;+ if (waited < SOAK_MS && !urgent) {+ throw new Error(`v${version} was published ${Math.floor(waited / 3_600_000)} hours ago; stable takes a version our Clouds have run for 48 hours. For a fix that cannot wait, run this again with "urgent" ticked.`);+ }+}++/** `index`: the tag's raw manifest. Throws unless it is an image index with every platform of `platforms` ("linux/amd64"). */+export function checkIndex(index, platforms, name) {+ if (!Array.isArray(index?.manifests)) throw new Error(`${name} is not a multi-platform image`);+ const has = new Set(index.manifests.map((manifest) => `${manifest.platform?.os}/${manifest.platform?.architecture}`));+ const missing = platforms.filter((platform) => !has.has(platform));+ if (missing.length) throw new Error(`${name} has no image for ${missing.join(" or ")}`);+}++const DIGEST = /^sha256:[0-9a-f]{64}$/;++/**+ * The next stable.json. `current` is the record it replaces (null for the first). Throws when `version` is older than+ * the current one, unless `allowOlder`. Promoting the current version again changes nothing but the images, if those moved.+ */+export function stableRecord({ version, image, cloudHomeImage, release, current, now, allowOlder = false }) {+ for (const ref of [image, cloudHomeImage]) if (!DIGEST.test(ref.split("@")[1] ?? "")) throw new Error(`${ref} is not pinned by digest`);+ if (current && compareVersions(version, current.version) < 0 && !allowOlder) {+ throw new Error(`stable is ${current.version}, which is newer than ${version}. To move stable back, run this again with "allow older" ticked.`);+ }+ const promotedAt = current?.version === version ? current.promotedAt : new Date(now).toISOString();+ const earlier = (current?.history ?? []).filter((entry) => entry.version !== version);+ // Everything that was stable within the skew window: the newest entry older than the window was stable at its start.+ const cutoff = now - SKEW_DAYS * DAY_MS;+ const kept = earlier.filter((entry, at) => Date.parse(entry.promotedAt) >= cutoff || at === 0 || Date.parse(earlier[at - 1].promotedAt) >= cutoff);+ return {+ channel: "stable",+ version,+ image,+ cloudHomeImage,+ platforms: ["linux/amd64", "linux/arm64"],+ releaseUrl: release.url,+ releasedAt: release.publishedAt,+ promotedAt,+ history: [{ version, promotedAt }, ...kept],+ };+}++function flags(argv) {+ const found = {};+ for (let i = 0; i < argv.length; i++) {+ if (!argv[i].startsWith("--")) throw new Error(`unexpected argument ${argv[i]}`);+ const name = argv[i].slice(2);+ if (name === "urgent" || name === "allow-older") found[name] = true;+ else found[name] = argv[++i];+ }+ return found;+}++const readJson = (file) => JSON.parse(readFileSync(file, "utf8"));++function main([command, ...rest]) {+ if (command === "version") return console.log(stableVersion(rest[0]));+ const options = flags(rest);+ if (command === "check-release") return checkRelease(readJson(options.release), stableVersion(options.version), { now: Date.now(), urgent: options.urgent === true });+ if (command === "check-image") return checkIndex(readJson(options.index), options.platforms.split(","), options.name);+ if (command === "record") {+ const record = stableRecord({+ version: stableVersion(options.version), image: options.image, cloudHomeImage: options["cloud-home"], release: readJson(options.release),+ current: options.current ? readJson(options.current) : null, now: Date.now(), allowOlder: options["allow-older"] === true,+ });+ return console.log(JSON.stringify(record, null, 2));+ }+ throw new Error("usage: stable-channel.mjs version <X.Y.Z> | check-release | check-image | record");+}++if (process.argv[1] === fileURLToPath(import.meta.url)) {+ try {+ main(process.argv.slice(2));+ } catch (error) {+ console.error(`::error::${error.message}`);+ process.exit(1);+ }+}diff --git a/scripts/testing/deploy-update.test.ts b/scripts/testing/deploy-update.test.tsnew file mode 100644index 0000000000..6c603e264f--- /dev/null+++ b/scripts/testing/deploy-update.test.ts@@ -0,0 +1,325 @@+import { spawnSync } from "node:child_process";+import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++const SCRIPT = join(import.meta.dirname, "..", "..", "deploy", "update.sh");+const FAKE = join(import.meta.dirname, "fake-compose-docker.mjs");+const REPO = "ghcr.io/milind-soni/openmausbot";+const posix = process.platform !== "win32";++const id = (letter: string) => `sha256:${letter.repeat(64)}`;+const OLD = { id: id("a"), refs: [`${REPO}:latest`, `${REPO}@${id("1")}`], version: "0.1.150", local: true, engine: true };+const NEW = { id: id("b"), refs: [`${REPO}@${id("2")}`, `${REPO}:v0.1.151`], version: "0.1.151", local: false, engine: true };+const ENV = "DOMAIN=maus.example.test\[email protected]\n";++const dirs: string[] = [];+afterEach(() => {+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/** Every file under `dir` with its content: what "the data as it was" means. */+function tree(dir: string, prefix = ""): Record<string, string> {+ const files: Record<string, string> = {};+ for (const name of readdirSync(dir).sort()) {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) Object.assign(files, tree(path, `${prefix}${name}/`));+ else files[`${prefix}${name}`] = readFileSync(path, "utf8");+ }+ return files;+}++/** A Compose install on version 0.1.150 with some data, and a stable channel that names `target`. */+function install(target: Record<string, unknown> = {}, extra: Record<string, unknown> = {}) {+ const root = mkdtempSync(join(tmpdir(), "omb-update-"));+ dirs.push(root);+ const deploy = join(root, "deploy");+ const fake = join(root, "fake");+ const data = join(fake, "volumes", "deploy_data");+ mkdirSync(join(root, "bin"));+ mkdirSync(deploy);+ mkdirSync(join(data, ".openmausbot"), { recursive: true });+ writeFileSync(join(data, ".openmausbot", "bots.json"), '[{"name":"Mira"}]');+ writeFileSync(join(data, "started-by.txt"), "0.1.150\n");+ copyFileSync(SCRIPT, join(deploy, "update.sh"));+ writeFileSync(join(deploy, "docker-compose.yml"), "services: {}\n");+ writeFileSync(join(deploy, ".env"), ENV);+ writeFileSync(join(root, "bin", "docker"), `#!/bin/sh\nexec "${process.execPath}" "${FAKE}" "$@"\n`);+ chmodSync(join(root, "bin", "docker"), 0o755);+ const next = { ...NEW, ...target };+ // A version that never answers is waited for; two seconds of that is enough here.+ const wait = next.behaviour === "silent" ? { OMB_UPDATE_WAIT_S: "2" } : {};+ writeFileSync(join(fake, "state.json"), JSON.stringify({+ serial: 1, composeReadsPin: true, defaultImage: `${REPO}:latest`, dataVolume: "deploy_data", images: [OLD, next],+ containers: { omb: { id: "omb-1", image: OLD.id, status: "running", restarts: 0 }, caddy: { id: "caddy-1", status: "running" } },+ ...extra,+ }));+ writeFileSync(join(root, "stable.json"), JSON.stringify({ channel: "stable", version: next.version, image: next.refs[0], history: [{ version: next.version, promotedAt: "2026-11-10T00:00:00Z" }] }, null, 2));+ const state = () => JSON.parse(readFileSync(join(fake, "state.json"), "utf8"));+ const run = (args: string[] = [], options: { input?: string; env?: Record<string, string> } = {}) => {+ const result = spawnSync("bash", [join(deploy, "update.sh"), ...args], {+ encoding: "utf8", input: options.input ?? "", timeout: 60_000,+ env: {+ PATH: `${join(root, "bin")}:/usr/bin:/bin`, HOME: root, FAKE_DOCKER_DIR: fake, OMB_STABLE_URL: `file://${join(root, "stable.json")}`,+ OMB_UPDATE_POLL_S: "0", OMB_UPDATE_WAIT_S: "120", ...wait, ...options.env,+ },+ });+ return { ...result, said: result.stdout.trim().split("\n") };+ };+ const calls = () => (existsSync(join(fake, "calls.log")) ? readFileSync(join(fake, "calls.log"), "utf8").trim().split("\n") : []);+ return {+ root, deploy, fake, data, state, run, calls,+ setState: (patch: Record<string, unknown>) => writeFileSync(join(fake, "state.json"), JSON.stringify({ ...state(), ...patch })),+ env: () => readFileSync(join(deploy, ".env"), "utf8"),+ backup: () => join(fake, "volumes", "deploy_data-before-update"),+ journal: () => existsSync(join(deploy, ".update", "journal")),+ };+}++describe.skipIf(!posix)("deploy/update.sh", () => {+ it("is valid bash", () => {+ expect(spawnSync("bash", ["-n", SCRIPT]).status).toBe(0);+ });++ it("copies the data aside, pins the stable image by digest, and waits until the new version answers and can start bots", () => {+ const box = install();+ const before = tree(box.data);+ const done = box.run();+ expect(done.status, done.stdout + done.stderr).toBe(0);+ expect(done.said).toEqual([+ "Downloading 0.1.151…",+ "Stopping the server and copying its data aside…",+ "Starting 0.1.151…",+ "Waiting for it to answer and to be able to start bots…",+ "Updated from 0.1.150 to 0.1.151.",+ "The data from before the update is kept in the Docker volume deploy_data-before-update until the next update.",+ "To go back to it: ./update.sh --rollback",+ ]);+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);+ expect(box.state().containers.omb).toMatchObject({ image: NEW.id, status: "running" });+ expect(tree(box.backup())).toEqual(before);+ expect(tree(box.data)["started-by.txt"]).toBe("0.1.150\n0.1.151\n");+ expect(box.journal()).toBe(false);+ const calls = box.calls();+ const order = [+ calls.findIndex((call) => call.startsWith("pull")), calls.indexOf("compose stop"), calls.findIndex((call) => call.includes("--entrypoint cp")),+ calls.findIndex((call) => call.startsWith("compose up")), calls.findLastIndex((call) => call.includes("/api/health")),+ ];+ expect(order.every((at) => at >= 0)).toBe(true);+ expect(order).toEqual([...order].sort((a, b) => a - b));+ expect(calls.find((call) => call.includes("--entrypoint cp"))).toBe(+ `run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v deploy_data:/from:ro -v deploy_data-before-update:/to --entrypoint cp ${OLD.id} -a /from/. /to/`,+ );+ });++ it("changes nothing when it is run again", () => {+ const box = install();+ expect(box.run().status).toBe(0);+ const calls = box.calls().length;+ const again = box.run();+ expect(again.status).toBe(0);+ expect(again.said).toEqual(["Downloading 0.1.151…", "This server already runs 0.1.151. Nothing to do."]);+ expect(box.calls().slice(calls).some((call) => /^(compose (stop|up)|run|volume)/.test(call))).toBe(false);+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);+ });++ it("puts back the old image, its settings and the data when the new version never answers", () => {+ const box = install({ behaviour: "silent" });+ const before = tree(box.data);+ const failed = box.run();+ expect(failed.status).toBe(1);+ expect(failed.said.slice(-3)).toEqual([+ "The update to 0.1.151 did not work: it did not answer within 2 seconds.",+ "Putting back the version and the data from before the update…",+ "Your server runs 0.1.150 again, with its data as it was before the update.",+ ]);+ expect(box.env()).toBe(ENV);+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });+ expect(box.state().containers.caddy.status).toBe("running");+ expect(box.journal()).toBe(false);+ });++ it("says why in the server's own last words when the new version stops as it starts", () => {+ const box = install({ behaviour: "crashes", lastWords: "This data was written by a newer MausBot." });+ const failed = box.run();+ expect(failed.status).toBe(1);+ expect(failed.stdout).toContain("The update to 0.1.151 did not work: it kept stopping as it started (This data was written by a newer MausBot.).");+ expect(failed.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ expect(tree(box.data)["started-by.txt"]).toBe("0.1.150\n0.1.150\n");+ });++ it.each([+ [{ engine: false }, "no engine can start a bot on it, and one could before"],+ [{ behaviour: "no-caddy" }, "Caddy, which serves it to the internet, did not start again"],+ [{ serves: "0.1.149" }, "it says it is version 0.1.149, not 0.1.151"],+ ])("rolls back a version that answers but lost what worked before: %j", (target, why) => {+ const box = install(target);+ const failed = box.run();+ expect(failed.status, failed.stdout).toBe(1);+ expect(failed.stdout).toContain(`The update to 0.1.151 did not work: ${why}.`);+ expect(box.state().containers.omb.image).toBe(OLD.id);+ expect(box.env()).toBe(ENV);+ });++ it("does not hold a missing engine against the new version when none worked before", () => {+ const box = install({ engine: false });+ box.setState({ images: [{ ...OLD, engine: false }, { ...NEW, engine: false }] });+ expect(box.run().status).toBe(0);+ });++ it("stops before touching the server when the image cannot be downloaded, the disk is short, or the Compose file is an old one", () => {+ for (const [extra, words] of [+ [{ failPull: true }, `Could not download ${NEW.refs[0]}`],+ [{ dataKb: 4_000_000, freeKb: 3_000_000 }, "There is not enough free disk for a copy of the data: it needs about 5320 MB and 2929 MB are free."],+ [{ composeReadsPin: false }, "does not take its image from OMB_IMAGE"],+ ] as const) {+ const box = install({}, extra);+ const refused = box.run();+ expect(refused.status, words).toBe(4);+ expect(refused.stdout).toContain(words);+ expect(refused.stdout).toContain("Nothing was changed.");+ expect(box.calls().some((call) => /^compose (stop|up)/.test(call))).toBe(false);+ expect(box.env()).toBe(ENV);+ expect(box.journal()).toBe(false);+ }+ });++ it("starts the server again as it was when the copy of the data fails", () => {+ const box = install({}, { failCopy: true });+ const before = tree(box.data);+ const refused = box.run();+ expect(refused.status).toBe(4);+ expect(refused.said.at(-1)).toMatch(/^Copying the data aside failed .* Nothing was changed, and the server was started again\.$/);+ expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });+ expect(existsSync(box.backup())).toBe(false);+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ });++ it("refuses a second update while one runs, an image built on the machine, and a channel record that names no pinned image", () => {+ const busy = install();+ mkdirSync(join(busy.deploy, ".update", "lock"), { recursive: true });+ writeFileSync(join(busy.deploy, ".update", "lock", "pid"), String(process.pid));+ const second = busy.run();+ expect(second.status).toBe(3);+ expect(second.stdout).toContain(`An update is already running here (process ${process.pid}).`);+ expect(existsSync(join(busy.deploy, ".update", "lock"))).toBe(true);++ const built = install();+ built.setState({ images: [{ ...OLD, refs: [`${REPO}:latest`] }, NEW] });+ const refused = built.run();+ expect(refused.status).toBe(4);+ expect(refused.stdout).toContain("runs an image built on this machine");+ expect(built.run(["--replace-local-build"]).status).toBe(0);++ const unpinned = install();+ writeFileSync(join(unpinned.root, "stable.json"), JSON.stringify({ version: "0.1.151", image: `${REPO}:latest` }));+ expect(unpinned.run().stdout).toContain("The stable channel names no image this script accepts. Nothing was changed.");+ });++ it("takes over a lock whose update is gone", () => {+ const box = install();+ mkdirSync(join(box.deploy, ".update", "lock"), { recursive: true });+ writeFileSync(join(box.deploy, ".update", "lock", "pid"), "999999");+ const done = box.run();+ expect(done.status, done.stdout + done.stderr).toBe(0);+ });++ it("finishes an update that was killed while the new version started: the next run puts the old one back", () => {+ const box = install({ behaviour: "silent" }, { signalOn: { step: "compose up", signal: "SIGKILL" } });+ const before = tree(box.data);+ const killed = box.run();+ expect(killed.signal).toBe("SIGKILL");+ expect(box.journal()).toBe(true);+ expect(box.env()).toContain("OMB_IMAGE=");+ const next = box.run(["--check"]);+ expect(next.status).toBe(0);+ expect(box.journal()).toBe(true);+ const repaired = box.run();+ expect(repaired.said.slice(0, 3)).toEqual([+ "The update to 0.1.151 was interrupted.",+ "Putting back the version and the data from before the update…",+ "Your server runs 0.1.150 again, with its data as it was before the update.",+ ]);+ expect(repaired.status).toBe(1);+ expect(box.env()).toBe(ENV);+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ expect(box.state().containers.omb.image).toBe(OLD.id);+ });++ it("keeps a new version that turned out healthy when the update was killed while waiting for it", () => {+ const box = install({}, { signalOn: { step: "compose exec -T omb sh", signal: "SIGKILL" } });+ expect(box.run().signal).toBe("SIGKILL");+ const next = box.run();+ expect(next.status).toBe(0);+ expect(next.said.slice(0, 2)).toEqual(["The last update was interrupted after the new version had started, and it is healthy.", "Updated from 0.1.150 to 0.1.151."]);+ expect(next.said.at(-1)).toBe("This server already runs 0.1.151. Nothing to do.");+ expect(box.state().containers.omb.image).toBe(NEW.id);+ });++ it("on Ctrl-C while copying, starts the server again with nothing changed; while waiting, puts the old version back", () => {+ const copying = install({}, { signalOn: { step: "run --rm --network none --user 0:0 --label com.mausbot.role=update-helper -v deploy_data:/from:ro -v deploy_data-before-update:/to", signal: "SIGINT" } });+ const stopped = copying.run();+ expect(stopped.status).toBe(130);+ expect(stopped.stdout).toContain("The update stopped while it copied the data aside. Nothing was changed, and the server was started again.");+ expect(copying.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });+ expect(copying.env()).toBe(ENV);+ expect(copying.journal()).toBe(false);++ const waiting = install({}, { signalOn: { step: "compose exec -T omb sh", signal: "SIGTERM" } });+ const before = tree(waiting.data);+ const back = waiting.run();+ expect(back.status).toBe(1);+ expect(back.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ expect(waiting.env()).toBe(ENV);+ expect(tree(waiting.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ });++ it("goes back on request after a good update, once, and only after a typed yes", () => {+ const box = install();+ const before = tree(box.data);+ expect(box.run().status).toBe(0);+ writeFileSync(join(box.data, ".openmausbot", "bots.json"), "[]");+ const declined = box.run(["--rollback"], { input: "no\n" });+ expect(declined.status).toBe(4);+ expect(box.state().containers.omb.image).toBe(NEW.id);+ const back = box.run(["--rollback"], { input: "yes\n" });+ expect(back.status, back.stdout).toBe(0);+ expect(back.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ expect(tree(box.data)).toEqual({ ...before, "started-by.txt": "0.1.150\n0.1.150\n" });+ expect(box.env()).toBe(ENV);+ expect(box.run(["--rollback", "--yes"]).stdout).toContain("There is no earlier update to go back from.");+ });++ it("puts the old version back when Docker cannot start the new one at all", () => {+ const box = install({}, { failUp: NEW.id });+ const failed = box.run();+ expect(failed.status).toBe(1);+ expect(failed.stdout).toContain("Docker could not start 0.1.151");+ expect(failed.said.at(-1)).toBe("Your server runs 0.1.150 again, with its data as it was before the update.");+ expect(box.state().containers.omb).toMatchObject({ image: OLD.id, status: "running" });+ expect(box.env()).toBe(ENV);+ });++ it("says so, and leaves the copy alone, when the data cannot be put back", () => {+ const box = install({ behaviour: "silent" }, { failRestore: true });+ const before = tree(box.data);+ const failed = box.run();+ expect(failed.status).toBe(2);+ expect(failed.said.at(-1)).toContain("The data could not be put back from the Docker volume deploy_data-before-update");+ expect(tree(box.backup())).toEqual(before);+ });++ it("updates to a named version, and --check changes nothing", () => {+ const box = install();+ const check = box.run(["--check"]);+ expect(check.said).toEqual(["This server runs 0.1.150.", "./update.sh would update it to 0.1.151."]);+ expect(box.calls().some((call) => /^(pull|compose (stop|up)|run|volume)/.test(call))).toBe(false);+ expect(existsSync(join(box.deploy, ".update"))).toBe(false);+ const done = box.run(["--version", "v0.1.151"]);+ expect(done.status, done.stdout).toBe(0);+ expect(box.calls()).toContain(`pull -q ${REPO}:v0.1.151`);+ expect(box.env()).toBe(`${ENV}OMB_IMAGE=${NEW.refs[0]}\n`);+ });+});diff --git a/scripts/testing/fake-compose-docker.mjs b/scripts/testing/fake-compose-docker.mjsnew file mode 100644index 0000000000..3fa1adf70a--- /dev/null+++ b/scripts/testing/fake-compose-docker.mjs@@ -0,0 +1,136 @@+#!/usr/bin/env node+// A stand-in for the `docker` CLI that deploy/update.sh drives: one Compose project (omb and caddy) whose state is a+// JSON file, and whose volumes are real folders, so a copy or a restore moves real files. FAKE_DOCKER_DIR holds it all.+import { spawnSync } from "node:child_process";+import { appendFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";++const dir = process.env.FAKE_DOCKER_DIR;+const stateFile = join(dir, "state.json");+const state = JSON.parse(readFileSync(stateFile, "utf8"));+const save = () => writeFileSync(stateFile, JSON.stringify(state, null, 1));+const args = process.argv.slice(2);+const line = args.join(" ");+appendFileSync(join(dir, "calls.log"), `${line}\n`);++const out = (text) => process.stdout.write(`${text}\n`);+const fail = (text, code = 1) => {+ process.stderr.write(`${text}\n`);+ save();+ process.exit(code);+};+const volume = (name) => join(dir, "volumes", name.replaceAll("/", "_"));+/** An image by any name it has: its id, a tag, or a digest reference. */+const image = (ref) => state.images.find((candidate) => candidate.local && (candidate.id === ref || candidate.refs.includes(ref)));+const envFile = () => (existsSync(join(process.cwd(), ".env")) ? readFileSync(join(process.cwd(), ".env"), "utf8") : "");+const pinned = () => process.env.OMB_IMAGE ?? /^OMB_IMAGE=(.*)$/m.exec(envFile())?.[1] ?? null;+const composeImage = () => (state.composeReadsPin && pinned()) || state.defaultImage;++/** `{step: "compose up", signal: "SIGKILL"}`: the update script is signalled as this call starts, once. */+const trip = state.signalOn;+if (trip && line.startsWith(trip.step)) {+ delete state.signalOn;+ save();+ process.kill(Number(readFileSync(join(process.cwd(), ".update", "lock", "pid"), "utf8")), trip.signal);+ if (trip.signal === "SIGKILL") process.exit(137);+}++function composeUp() {+ const wanted = image(composeImage());+ if (!wanted) fail(`pull access denied for ${composeImage()}`);+ if (state.failUp === wanted.id) fail("Error response from daemon: driver failed programming external connectivity");+ const crashes = wanted.behaviour === "crashes";+ state.containers.omb = { id: `omb-${++state.serial}`, image: wanted.id, status: crashes ? "restarting" : "running", restarts: crashes ? 5 : 0 };+ state.containers.caddy = { id: `caddy-${state.serial}`, status: wanted.behaviour === "no-caddy" ? "exited" : "running" };+ // A server that starts writes to its data, as a new version's migrations do.+ if (!crashes) appendFileSync(join(volume(state.dataVolume), "started-by.txt"), `${wanted.version}\n`);+}++function compose(rest) {+ const [verb, ...more] = rest;+ const omb = state.containers.omb;+ if (verb === "version") return out("Docker Compose version v2.40.0");+ if (verb === "config") return out(`services:\n omb:\n image: ${composeImage()}`);+ if (verb === "ps" && more.includes("-aq")) return omb ? out(omb.id) : undefined;+ if (verb === "ps") return Object.entries(state.containers).filter(([, container]) => container?.status === "running").forEach(([name]) => out(name));+ if (verb === "stop") {+ for (const container of Object.values(state.containers)) if (container) Object.assign(container, { status: "exited" });+ return;+ }+ if (verb === "up") return composeUp();+ if (verb === "logs") return out(image(omb?.image)?.lastWords ?? "");+ if (verb === "exec") {+ const serving = image(omb?.image);+ if (omb?.status !== "running" || !serving) fail("service omb is not running");+ if (more.includes("openmausbot")) return serving.engine ? out("ready") : fail("no engine is available", 5);+ if (serving.behaviour === "silent") fail("", 7);+ if (line.includes("/api/health")) return out('{"app":"openmausbot"}');+ if (line.includes("/environment")) return out(JSON.stringify({ environmentId: "e", version: serving.serves ?? serving.version }));+ }+ fail(`fake docker: unknown compose command: ${line}`, 64);+}++function inspect(format, target) {+ const omb = state.containers.omb;+ if (!omb || omb.id !== target) fail(`No such object: ${target}`);+ if (format === "{{.Image}}") return out(omb.image);+ if (format === "{{.State.Running}}") return out(String(omb.status === "running"));+ if (format === "{{.State.Status}} {{.RestartCount}} {{.Image}}") return out(`${omb.status} ${omb.restarts} ${omb.image}`);+ if (format.includes(".Mounts")) return out(state.dataVolume);+ if (format.includes("com.docker.compose.project")) return out("deploy");+ fail(`fake docker: unknown inspect format: ${format}`, 64);+}++function imageInspect(format, ref) {+ const found = image(ref);+ if (!found) fail(`No such image: ${ref}`);+ if (format === "{{.Id}}") return out(found.id);+ if (format.includes(".RepoDigests")) return found.refs.filter((name) => name.includes("@sha256:")).forEach((name) => out(name));+ if (format.includes("image.version")) return out(found.version ? `v${found.version}` : "");+ fail(`fake docker: unknown image format: ${format}`, 64);+}++/** `run … -v a:/from:ro -v b:/to --entrypoint <cmd> <image> <args>`: the command really runs, on the volumes' folders. */+function run(rest) {+ const mounts = {};+ rest.forEach((arg, at) => {+ if (arg !== "-v") return;+ const [source, target] = rest[at + 1].split(":");+ mounts[target] = volume(source);+ });+ const entry = rest[rest.indexOf("--entrypoint") + 1];+ const tail = rest.slice(rest.indexOf("--entrypoint") + 3);+ if (state.failCopy && entry === "cp") fail("cp: error writing '/to/messages.db': No space left on device");+ if (state.failRestore && entry === "sh" && tail[1].includes("find /to")) fail("cp: cannot create regular file");+ if (Object.values(mounts).some((folder) => !folder.startsWith(join(dir, "volumes")))) fail("fake docker: a mount outside the fixture", 64);+ const inFolders = (text) => text.replace(/\/(from|to)(?=[/\s.]|$)/g, (_, name) => mounts[`/${name}`] ?? join(dir, "volumes", "unmounted"));+ if (entry === "sh" && tail[1].startsWith("du -sk")) return out(`${state.dataKb ?? 1024}\n${state.freeKb ?? 50_000_000}`);+ const done = spawnSync(entry, tail.map(inFolders), { stdio: "inherit" });+ if (done.status !== 0) fail(`helper exited ${done.status}`, done.status ?? 1);+}++function main() {+ const [verb, ...rest] = args;+ if (verb === "compose") return compose(rest);+ if (verb === "inspect") return inspect(rest[1], rest[2]);+ if (verb === "image" && rest[0] === "inspect") return imageInspect(rest[2], rest[3]);+ if (verb === "pull") {+ const ref = rest.at(-1);+ const found = state.images.find((candidate) => candidate.refs.includes(ref));+ if (!found || state.failPull) fail(`Error response from daemon: manifest for ${ref} not found`);+ found.local = true;+ return;+ }+ if (verb === "tag") return void image(rest[0])?.refs.push(rest[1]);+ if (verb === "run") return run(rest);+ if (verb === "volume") {+ const name = rest.at(-1);+ if (rest[0] === "rm") return rmSync(volume(name), { recursive: true, force: true });+ if (rest[0] === "create") return mkdirSync(volume(name), { recursive: true });+ if (rest[0] === "inspect") return existsSync(volume(name)) ? out(name) : fail(`no such volume: ${name}`);+ }+ fail(`fake docker: unknown command: ${line}`, 64);+}++main();+save();diff --git a/scripts/testing/stable-channel.test.ts b/scripts/testing/stable-channel.test.tsnew file mode 100644index 0000000000..174532cdb5--- /dev/null+++ b/scripts/testing/stable-channel.test.ts@@ -0,0 +1,77 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { checkIndex, checkRelease, SOAK_MS, stableRecord, stableVersion } from "../stable-channel.mjs";++const NOW = Date.parse("2026-11-12T12:00:00Z");+const release = (patch: Record<string, unknown> = {}) => ({+ tagName: "v0.1.151", isDraft: false, isPrerelease: false, publishedAt: "2026-11-09T22:56:49Z",+ url: "https://github.com/milind-soni/OpenMausBot/releases/tag/v0.1.151", ...patch,+});+const pinned = (name: string, letter: string) => `ghcr.io/milind-soni/${name}@sha256:${letter.repeat(64)}`;+const IMAGE = pinned("openmausbot", "a");+const HOME = pinned("openmausbot-cloud-home", "b");+const index = (...platforms: string[]) => ({+ mediaType: "application/vnd.oci.image.index.v1+json",+ manifests: [...platforms, "unknown/unknown"].map((platform) => ({ platform: { os: platform.split("/")[0], architecture: platform.split("/")[1] } })),+});++describe("the stable channel", () => {+ it("takes a released version number and nothing else", () => {+ expect(stableVersion("v0.1.151")).toBe("0.1.151");+ expect(stableVersion(" 0.1.151 ")).toBe("0.1.151");+ for (const bad of ["latest", "0.1", "0.1.151-rc.1", "main", "", "sha-abc"]) expect(() => stableVersion(bad), bad).toThrow("is not a released version");+ });++ it("refuses a version that is not a published release, or has not had its 48 hours", () => {+ expect(() => checkRelease(release(), "0.1.151", { now: NOW })).not.toThrow();+ expect(() => checkRelease(null, "0.1.151", { now: NOW })).toThrow("v0.1.151 is not a release of this repository");+ expect(() => checkRelease(release({ tagName: "v0.1.150" }), "0.1.151", { now: NOW })).toThrow("is not a release");+ expect(() => checkRelease(release({ isDraft: true }), "0.1.151", { now: NOW })).toThrow("still a draft");+ expect(() => checkRelease(release({ isPrerelease: true }), "0.1.151", { now: NOW })).toThrow("prerelease");+ const fresh = Date.parse(release().publishedAt) + SOAK_MS - 60_000;+ expect(() => checkRelease(release(), "0.1.151", { now: fresh })).toThrow("was published 47 hours ago");+ expect(() => checkRelease(release(), "0.1.151", { now: fresh, urgent: true })).not.toThrow();+ });++ it("refuses an image that lacks one of the platforms", () => {+ expect(() => checkIndex(index("linux/amd64", "linux/arm64"), ["linux/amd64", "linux/arm64"], "the server image")).not.toThrow();+ expect(() => checkIndex(index("linux/amd64"), ["linux/amd64", "linux/arm64"], "the server image")).toThrow("the server image has no image for linux/arm64");+ expect(() => checkIndex({ mediaType: "application/vnd.oci.image.manifest.v1+json" }, ["linux/amd64"], "the server image")).toThrow("not a multi-platform image");+ });++ it("records the version with both images by digest, in a shape update.sh reads without a JSON parser", () => {+ const record = stableRecord({ version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, release: release(), current: null, now: NOW });+ expect(record).toEqual({+ channel: "stable", version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, platforms: ["linux/amd64", "linux/arm64"],+ releaseUrl: release().url, releasedAt: release().publishedAt, promotedAt: "2026-11-12T12:00:00.000Z",+ history: [{ version: "0.1.151", promotedAt: "2026-11-12T12:00:00.000Z" }],+ });+ const text = JSON.stringify(record, null, 2).replace(/\n/g, "");+ // deploy/update.sh's two sed expressions+ expect(/.*"image"\s*:\s*"([^"]*)".*/.exec(text)?.[1]).toBe(IMAGE);+ expect(/.*"version"\s*:\s*"([0-9][0-9.]*)".*/.exec(text)?.[1]).toBe("0.1.151");+ const script = readFileSync(join(import.meta.dirname, "..", "..", "deploy", "update.sh"), "utf8");+ expect(script).toContain(String.raw`sed -n 's/.*"image"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p'`);+ expect(() => stableRecord({ version: "0.1.151", image: "ghcr.io/milind-soni/openmausbot:v0.1.151", cloudHomeImage: HOME, release: release(), current: null, now: NOW })).toThrow("is not pinned by digest");+ });++ it("will not move stable back unless told to, and promoting the same version again keeps its date", () => {+ const first = stableRecord({ version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, release: release(), current: null, now: NOW });+ expect(() => stableRecord({ version: "0.1.150", image: IMAGE, cloudHomeImage: HOME, release: release(), current: first, now: NOW })).toThrow("stable is 0.1.151, which is newer than 0.1.150");+ expect(stableRecord({ version: "0.1.150", image: IMAGE, cloudHomeImage: HOME, release: release(), current: first, now: NOW + 1000, allowOlder: true }).history.map((entry) => entry.version)).toEqual(["0.1.150", "0.1.151"]);+ expect(stableRecord({ version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, release: release(), current: first, now: NOW + 86_400_000 })).toEqual(first);+ });++ it("keeps every version that was stable in the last 90 days, which is what an app needs to judge a server's age", () => {+ const day = 86_400_000;+ let record = null;+ for (const [version, daysAgo] of [["0.1.100", 200], ["0.1.110", 120], ["0.1.120", 60], ["0.1.130", 10]] as const) {+ record = stableRecord({ version, image: IMAGE, cloudHomeImage: HOME, release: release(), current: record, now: NOW - daysAgo * day });+ }+ record = stableRecord({ version: "0.1.151", image: IMAGE, cloudHomeImage: HOME, release: release(), current: record, now: NOW });+ // 0.1.110 was still the stable one 90 days ago; 0.1.100 was replaced before that.+ expect(record.history.map((entry) => entry.version)).toEqual(["0.1.151", "0.1.130", "0.1.120", "0.1.110"]);+ });+});diff --git a/server/routes/update-check.ts b/server/routes/update-check.tsindex d078b8e9ef..3acba2ce30 100644--- a/server/routes/update-check.ts+++ b/server/routes/update-check.ts@@ -1,7 +1,7 @@-// GET /api/updates/check: whether a newer release exists, and how this install is updated. Read-only, so client sessions may ask.+// GET /api/updates/check: whether a newer version exists, and how this install is updated. Read-only, so client sessions may ask.import { serverVersion } from "../environment.ts";import { SERVER_ROOT } from "../proxy-paths.ts";-import { createUpdateChecker, installKind, type UpdateCheck } from "../update-check.ts";+import { createUpdateChecker, installKind, updateChannel, type UpdateCheck } from "../update-check.ts";import { PASS, type RouteHandler } from "./table.ts";export interface UpdateCheckRouteDeps {@@ -20,5 +20,5 @@ export function createUpdateCheckRoutes(deps: UpdateCheckRouteDeps): RouteHandle}export function serverUpdateChecker(where: { desktopManaged: boolean; managed: boolean }): () => Promise<UpdateCheck> {- return createUpdateChecker({ current: serverVersion(), install: installKind({ ...where, serverRoot: SERVER_ROOT }) });+ return createUpdateChecker({ current: serverVersion(), install: installKind({ ...where, serverRoot: SERVER_ROOT }), channel: updateChannel() });}diff --git a/server/update-check.test.ts b/server/update-check.test.tsindex 144dc8649b..d37b22da48 100644--- a/server/update-check.test.ts+++ b/server/update-check.test.ts@@ -1,11 +1,18 @@import { join, sep } from "node:path";import { describe, expect, it, vi } from "vitest";-import { createUpdateChecker, installKind, isNewerVersion, LATEST_RELEASE_URL } from "./update-check.ts";+import { createUpdateChecker, installKind, isNewerVersion, LATEST_RELEASE_URL, STABLE_CHANNEL_URL, updateChannel } from "./update-check.ts";const release = (tag: string) =>({ ok: true, status: 200, json: async () => ({ tag_name: tag, html_url: `https://github.com/milind-soni/OpenMausBot/releases/tag/${tag}` }) }) as Response;+const promoted = (version: string) =>+ ({ ok: true, status: 200, json: async () => ({ channel: "stable", version, image: `ghcr.io/milind-soni/openmausbot@sha256:${"a".repeat(64)}`, releaseUrl: `https://github.com/milind-soni/OpenMausBot/releases/tag/v${version}` }) }) as Response;+const missing = { ok: false, status: 404, json: async () => ({}) } as Response;+/** GitHub's newest release is `newest`; the stable channel names `stable`, or does not exist yet. */+const github = (newest: string, stable: string | null) => vi.fn(async (url: string | URL | Request) =>+ String(url) === STABLE_CHANNEL_URL ? (stable ? promoted(stable) : missing) : release(newest));+describe("server update check", () => {it("tells how this server was installed", () => {const none = () => false;@@ -38,26 +45,55 @@ describe("server update check", () => {expect(isNewerVersion("v0.1.93-rc.1.1", "0.1.93-rc.1")).toBe(true);});- it("reports a newer release with the update command for this install", async () => {- const fetch = vi.fn(async () => release("v0.1.93"));+ it("follows the stable channel, not the newest release, and gives the update command for this install", async () => {+ const fetch = github("v0.1.95", "0.1.93");const check = createUpdateChecker({ current: "0.1.92", install: "docker", fetch });expect(await check()).toEqual({current: "0.1.92",install: "docker",+ channel: "stable",latest: "0.1.93",available: true,releaseUrl: "https://github.com/milind-soni/OpenMausBot/releases/tag/v0.1.93",- command: "docker compose pull omb && docker compose up -d",+ command: "git pull && ./update.sh",restart: false,});- expect(fetch).toHaveBeenCalledWith(LATEST_RELEASE_URL, expect.anything());+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(fetch).toHaveBeenCalledWith(STABLE_CHANNEL_URL, expect.anything());+ expect(await createUpdateChecker({ current: "0.1.92", install: "npm", fetch })()).toMatchObject({ latest: "0.1.93", command: "npm install -g [email protected]", restart: true });+ });++ it("offers nothing to a server that is already on the stable version or past it", async () => {+ expect(await createUpdateChecker({ current: "0.1.93", install: "docker", fetch: github("v0.1.95", "0.1.93") })()).toMatchObject({ channel: "stable", latest: "0.1.93", available: false });+ expect(await createUpdateChecker({ current: "0.1.95", install: "docker", fetch: github("v0.1.95", "0.1.93") })()).toMatchObject({ available: false });+ });++ it("goes by the newest release until a first version has been promoted, or when the owner asked for every release", async () => {+ const unpromoted = github("v0.1.93", null);+ expect(await createUpdateChecker({ current: "0.1.92", install: "docker", fetch: unpromoted })()).toMatchObject({+ channel: "newest", latest: "0.1.93", available: true, command: "git pull && ./update.sh --version 0.1.93",+ });+ expect(unpromoted).toHaveBeenLastCalledWith(LATEST_RELEASE_URL, expect.anything());+ const fetch = github("v0.1.95", "0.1.93");+ expect(await createUpdateChecker({ current: "0.1.92", install: "docker", channel: "newest", fetch })()).toMatchObject({ channel: "newest", latest: "0.1.95" });+ expect(fetch).toHaveBeenCalledTimes(1);+ expect(updateChannel({})).toBe("stable");+ expect(updateChannel({ OMB_UPDATE_CHANNEL: " Newest " })).toBe("newest");+ expect(updateChannel({ OMB_UPDATE_CHANNEL: "latest" })).toBe("stable");+ });++ it("does not take a broken channel record for a version, or fall back past it", async () => {+ const fetch = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ version: "0.1.93-rc.1" }) }) as Response);+ await expect(createUpdateChecker({ current: "0.1.92", install: "docker", fetch })()).rejects.toThrow("The stable channel named no version");+ fetch.mockImplementation(async () => ({ ok: false, status: 500, json: async () => ({}) }) as Response);+ await expect(createUpdateChecker({ current: "0.1.92", install: "docker", fetch })()).rejects.toThrow("The stable channel answered 500");});- it("says up to date, and asks GitHub at most once an hour", async () => {+ it("says up to date, and asks at most once an hour", async () => {let now = 0;- const fetch = vi.fn(async () => release("v0.1.92"));+ const fetch = github("v0.1.92", "0.1.92");const check = createUpdateChecker({ current: "0.1.92", install: "npm", fetch, now: () => now });- expect(await check()).toMatchObject({ available: false, latest: "0.1.92", command: "npm install -g openmausbot@latest", restart: true });+ expect(await check()).toMatchObject({ available: false, latest: "0.1.92", command: "npm install -g [email protected]", restart: true });now = 59 * 60_000;await check();expect(fetch).toHaveBeenCalledTimes(1);@@ -76,7 +112,7 @@ describe("server update check", () => {it("fails clearly when GitHub cannot be reached, and tries again next time", async () => {const fetch = vi.fn(async () => ({ ok: false, status: 403, json: async () => ({}) }) as Response);- const check = createUpdateChecker({ current: "0.1.92", install: "git", fetch });+ const check = createUpdateChecker({ current: "0.1.92", install: "git", channel: "newest", fetch });await expect(check()).rejects.toThrow("GitHub answered 403");fetch.mockImplementation(async () => release("v0.1.93"));expect(await check()).toMatchObject({ available: true, command: "git pull && pnpm install", restart: true });diff --git a/server/update-check.ts b/server/update-check.tsindex 3316ad38a1..b52643bfb3 100644--- a/server/update-check.ts+++ b/server/update-check.ts@@ -1,20 +1,36 @@-// A self-hosted server cannot replace itself, so this only says whether a newer release exists and how this install is updated.+// A self-hosted server cannot replace itself, so this only says whether a newer version exists and how this install is updated.import { existsSync } from "node:fs";import { join, sep } from "node:path";export const LATEST_RELEASE_URL = "https://api.github.com/repos/milind-soni/OpenMausBot/releases/latest";+/** Written by .github/workflows/promote-stable.yml: the released version our own Clouds have run for 48 hours. */+export const STABLE_CHANNEL_URL = "https://raw.githubusercontent.com/milind-soni/OpenMausBot/channels/stable.json";const CACHE_MS = 60 * 60_000;/** "managed" is a hosted or Cloud server that is updated for its owner. */export type InstallKind = "desktop" | "managed" | "docker" | "podman" | "npm" | "git" | "unknown";-/** As docs/self-hosting.md and deploy/podman/README.md give them. */-export const UPDATE_COMMANDS: Partial<Record<InstallKind, { command: string; restart: boolean }>> = {- docker: { command: "docker compose pull omb && docker compose up -d", restart: false },- podman: { command: "git pull && cd deploy/podman && PODMAN_COMPOSE_PROVIDER=podman-compose podman compose --env-file .env -f compose.yaml up -d --build", restart: false },- npm: { command: "npm install -g openmausbot@latest", restart: true },- git: { command: "git pull && pnpm install", restart: true },-};+/** `stable` follows the promoted version; `newest` follows every release, as soon as it is published. */+export type UpdateChannel = "stable" | "newest";++/** OMB_UPDATE_CHANNEL: `newest` to hear of every release; anything else is `stable`. */+export function updateChannel(env: NodeJS.ProcessEnv = process.env): UpdateChannel {+ return env.OMB_UPDATE_CHANNEL?.trim().toLowerCase() === "newest" ? "newest" : "stable";+}++/**+ * As docs/self-hosting.md and deploy/podman/README.md give them. `version` is the one the channel names: an npm install+ * is pinned to it, and a Docker install passes it to deploy/update.sh unless that is the stable one update.sh takes anyway.+ */+export function updateCommand(install: InstallKind, target?: { version: string; stable: boolean }): { command: string; restart: boolean } | undefined {+ switch (install) {+ case "docker": return { command: target && !target.stable ? `git pull && ./update.sh --version ${target.version}` : "git pull && ./update.sh", restart: false };+ case "podman": return { command: "git pull && cd deploy/podman && PODMAN_COMPOSE_PROVIDER=podman-compose podman compose --env-file .env -f compose.yaml up -d --build", restart: false };+ case "npm": return { command: `npm install -g openmausbot@${target?.version ?? "latest"}`, restart: true };+ case "git": return { command: "git pull && pnpm install", restart: true };+ default: return undefined;+ }+}export function installKind(input: {desktopManaged: boolean;@@ -62,6 +78,8 @@ export function isNewerVersion(latest: string, current: string): boolean {export interface UpdateCheck {current: string;install: InstallKind;+ /** Where `latest` came from. `stable` falls back to `newest` until a first version has been promoted. */+ channel?: UpdateChannel;latest?: string;available: boolean;releaseUrl?: string;@@ -69,42 +87,64 @@ export interface UpdateCheck {restart?: boolean;}-/** One cached GitHub lookup an hour, shared by every caller. */+type Found = { version: string; releaseUrl?: string };++/** One cached lookup an hour, shared by every caller. */export function createUpdateChecker(options: {current: string;install: InstallKind;+ channel?: UpdateChannel;fetch?: typeof fetch;now?: () => number;}) {- const fetchRelease = options.fetch ?? fetch;+ const fetchJson = options.fetch ?? fetch;const now = options.now ?? Date.now;+ const channel = options.channel ?? "stable";let cached: { at: number; result: UpdateCheck } | undefined;let inflight: Promise<UpdateCheck> | undefined;const base = (): UpdateCheck => ({current: options.current,install: options.install,available: false,- ...UPDATE_COMMANDS[options.install],+ ...updateCommand(options.install),});+ const ask = (url: string) => fetchJson(url, {+ headers: { accept: "application/vnd.github+json", "user-agent": "openmausbot-update-check" },+ signal: AbortSignal.timeout(8_000),+ });++ /** Null until a first version has been promoted: the record does not exist yet. */+ async function stable(): Promise<Found | null> {+ const response = await ask(STABLE_CHANNEL_URL);+ if (response.status === 404) return null;+ if (!response.ok) throw new Error(`The stable channel answered ${response.status}`);+ const record = await response.json() as { version?: unknown; releaseUrl?: unknown };+ if (typeof record.version !== "string" || !/^\d+\.\d+\.\d+$/.test(record.version)) throw new Error("The stable channel named no version");+ return { version: record.version, ...(typeof record.releaseUrl === "string" ? { releaseUrl: record.releaseUrl } : {}) };+ }++ async function newest(): Promise<Found> {+ const response = await ask(LATEST_RELEASE_URL);+ if (!response.ok) throw new Error(`GitHub answered ${response.status}`);+ const release = await response.json() as { tag_name?: unknown; html_url?: unknown };+ if (typeof release.tag_name !== "string") throw new Error("GitHub sent no release tag");+ return { version: release.tag_name.replace(/^v/, ""), ...(typeof release.html_url === "string" ? { releaseUrl: release.html_url } : {}) };+ }return async function check(): Promise<UpdateCheck> {if (options.install === "desktop" || options.install === "managed") return base();if (cached && now() - cached.at < CACHE_MS) return cached.result;inflight ??= (async () => {try {- const response = await fetchRelease(LATEST_RELEASE_URL, {- headers: { accept: "application/vnd.github+json", "user-agent": "openmausbot-update-check" },- signal: AbortSignal.timeout(8_000),- });- if (!response.ok) throw new Error(`GitHub answered ${response.status}`);- const release = await response.json() as { tag_name?: unknown; html_url?: unknown };- if (typeof release.tag_name !== "string") throw new Error("GitHub sent no release tag");- const latest = release.tag_name.replace(/^v/, "");+ const promoted = channel === "stable" ? await stable() : null;+ const found = promoted ?? await newest();const result: UpdateCheck = {...base(),- latest,- available: isNewerVersion(latest, options.current),- ...(typeof release.html_url === "string" ? { releaseUrl: release.html_url } : {}),+ channel: promoted ? "stable" : "newest",+ latest: found.version,+ available: isNewerVersion(found.version, options.current),+ ...(found.releaseUrl ? { releaseUrl: found.releaseUrl } : {}),+ ...updateCommand(options.install, { version: found.version, stable: promoted !== null }),};cached = { at: now(), result };return result;diff --git a/src/components/ServerList.test.ts b/src/components/ServerList.test.tsindex 07ce2d2451..d14ac324dd 100644--- a/src/components/ServerList.test.ts+++ b/src/components/ServerList.test.ts@@ -72,7 +72,7 @@ it("the update note shows only for a server behind this app, with the command thexpect(notes[0]!.textContent).toContain("Copy update command");await click(buttonIn(notes[0]!, "Hide this note"));expect(host.querySelector("[data-server-behind]")).toBeNull();- expect(updateCommand("docker", "0.1.147")).toBe("docker compose pull && docker compose up -d");+ expect(updateCommand("docker", "0.1.147")).toBe("git pull && ./update.sh");expect(updateCommand("npx", "0.1.147")).toBe("npx [email protected] serve");expect(updateCommand(null, "0.1.147")).toBe("npx [email protected] serve");expect(updateCommand("global", "0.1.147")).toBe("npm install -g [email protected]");diff --git a/src/components/ServerList.tsx b/src/components/ServerList.tsxindex 10bd875116..6e45c79829 100644--- a/src/components/ServerList.tsx+++ b/src/components/ServerList.tsx@@ -24,7 +24,7 @@ const clock = (ms: number) => new Date(ms).toLocaleTimeString([], { hour: "2-dig/** The update command that fits how the server was installed, pinned to this app's version. */export function updateCommand(install: ServerInstall | null, version: string): string {- if (install === "docker") return "docker compose pull && docker compose up -d";+ if (install === "docker") return "git pull && ./update.sh";if (install === "global") return `npm install -g openmausbot@${version}`;if (install === "source") return "git pull && pnpm install";return `npx openmausbot@${version} serve`;diff --git a/src/lib/server-update.test.ts b/src/lib/server-update.test.tsindex e8fff5972b..67f6b95cbc 100644--- a/src/lib/server-update.test.ts+++ b/src/lib/server-update.test.ts@@ -17,10 +17,10 @@ describe("self-hosted update row", () => {});it("names the new version and how this install is updated", () => {- const docker = check({ available: true, latest: "0.1.93", command: "docker compose pull omb && docker compose up -d", restart: false });+ const docker = check({ available: true, latest: "0.1.93", command: "git pull && ./update.sh", restart: false });expect(serverUpdateRow("available", docker)).toEqual({label: "Version 0.1.93 available (release notes)",- subtitle: "Update with: docker compose pull omb && docker compose up -d",+ subtitle: "Update with: git pull && ./update.sh",});const npm = check({ install: "npm", available: true, latest: "0.1.93", command: "npm install -g openmausbot@latest", restart: true });expect(serverUpdateRow("available", npm).subtitle).toBe("Update with: npm install -g openmausbot@latest, then restart the app");@@ -73,9 +73,9 @@ describe("the update row for another server the app shows", () => {label: "Office Mac can update to 0.1.127",subtitle: "Whoever runs that server updates it with: npm install -g openmausbot@latest, then restarts it",});- const docker = check({ available: true, latest: "0.1.127", command: "docker compose pull omb && docker compose up -d", restart: false });+ const docker = check({ available: true, latest: "0.1.127", command: "git pull && ./update.sh", restart: false });expect(serverUpdateRow("available", docker, "0.1.116", "Office Mac").subtitle).toBe(- "Whoever runs that server updates it with: docker compose pull omb && docker compose up -d",+ "Whoever runs that server updates it with: git pull && ./update.sh",);expect(serverUpdateRow("up-to-date", check({ current: "0.1.127" }), "0.1.127", "Office Mac")).toEqual({label: "Office Mac is up to date",diff --git a/src/lib/server-update.ts b/src/lib/server-update.tsindex 7113d3d963..23e751e66b 100644--- a/src/lib/server-update.ts+++ b/src/lib/server-update.ts@@ -5,6 +5,7 @@ import { t } from "./i18n";export interface ServerUpdateCheck {current: string;install: "desktop" | "managed" | "docker" | "podman" | "npm" | "git" | "unknown";+ channel?: "stable" | "newest";latest?: string;available: boolean;releaseUrl?: string;