Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

kwant 0.7.6: recipe card, Get started, What's new, Linux one-line install, sign-in and installs without Node (#438)

Oleksandr Ivanchenkofbf1eb7a46db
diff --git a/.github/workflows/kwnt-linux.yml b/.github/workflows/kwnt-linux.yml
new file mode 100644
index 00000000..280dce62
--- /dev/null
+++ b/.github/workflows/kwnt-linux.yml
@@ -0,0 +1,203 @@
+name: kwnt-linux
+
+# The standalone kwnt for Linux servers (x86_64 and arm64, the web UI embedded), the one-line
+# installer that downloads it (site/install.sh, served at kwant.si/install.sh) and the kwnt
+# container image built from the same binaries.
+#
+# Pull requests and manual runs build kwnt-linux-<arch>.tar.gz (+ .sha256) as workflow artifacts,
+# start each binary and check /api/health, run install.sh in clean Ubuntu 22.04 and Debian 12
+# containers against a local mock release (scripts/test_install_sh.sh), and build the image for
+# amd64 and arm64 without pushing it.
+# A mac-v* tag runs this from mac.yml (workflow_call): its release job attaches the tarballs to the
+# same release as the Mac app, and its image job pushes ghcr.io/<owner>/kwnt after the release exists.
+#
+# Built on ubuntu-22.04 (and the arm runner of the same release) so it runs on glibc 2.35 or newer;
+# a check below fails if a newer glibc symbol slips in.
+on:
+ workflow_call:
+ workflow_dispatch:
+ pull_request:
+ paths:
+ - "Cargo.toml"
+ - "Cargo.lock"
+ - "src/main.rs"
+ - "src/serve.rs"
+ - "src/config.rs"
+ - "src/server/auth.rs"
+ - "src/server/signin.rs"
+ - "docker/kwnt.Dockerfile"
+ - "docker/kwnt-entrypoint.sh"
+ - "docker-compose.yml"
+ - ".dockerignore"
+ - "site/install.sh"
+ - "scripts/test_install_sh.sh"
+ - "scripts/test_install_sh.inner.sh"
+ - ".github/workflows/kwnt-linux.yml"
+
+permissions:
+ contents: read
+
+concurrency:
+ group: kwnt-linux-${{ github.ref }}
+ # never cancel a release half-way
+ cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') }}
+
+env:
+ CARGO_TERM_COLOR: always
+ CARGO_INCREMENTAL: 0
+
+jobs:
+ binary:
+ name: kwnt ${{ matrix.arch }}
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x86_64
+ runner: ubuntu-22.04
+ - arch: aarch64
+ runner: ubuntu-22.04-arm
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 60
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ # kwnt embeds frontend/dist, so the UI is built first
+ - name: Build the web UI
+ working-directory: frontend
+ run: npm ci && npm run build
+ - uses: dtolnay/rust-toolchain@b725eda525362e7cf34af9a7243cac1e3f01a7ec # stable
+ - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
+ - name: Build kwnt
+ run: cargo build --release --locked --bin kwnt
+ - name: Runs on glibc 2.35 (Ubuntu 22.04, Debian 12)
+ run: |
+ set -euo pipefail
+ ldd target/release/kwnt
+ newest=$(objdump -T target/release/kwnt | grep -o 'GLIBC_[0-9.]*' | sed 's/GLIBC_//' | sort -uV | tail -1)
+ echo "newest glibc symbol: $newest"
+ if [ "$(printf '%s\n2.35\n' "$newest" | sort -V | tail -1)" != "2.35" ]; then
+ echo "::error::kwnt needs glibc $newest, newer than Ubuntu 22.04's 2.35"
+ exit 1
+ fi
+ - name: Smoke test (--version, then /api/health)
+ run: |
+ set -euo pipefail
+ ./target/release/kwnt --version
+ tmp=$(mktemp -d)
+ HOME="$tmp" KWNT_DATA_DIR="$tmp/data" KWNT_LAYA_MANAGED=0 KWNT_PORT=18799 \
+ ./target/release/kwnt serve > "$tmp/serve.log" 2>&1 &
+ pid=$!
+ ok=""
+ for _ in $(seq 60); do
+ if curl -fsS --max-time 3 http://127.0.0.1:18799/api/health > "$tmp/health.json" 2>/dev/null \
+ && grep -q '"app":"kwnt"' "$tmp/health.json"; then ok=1; break; fi
+ sleep 1
+ done
+ kill "$pid" || true
+ if [ -z "$ok" ]; then tail -n 40 "$tmp/serve.log"; exit 1; fi
+ cat "$tmp/health.json"; echo
+ - name: Package
+ run: |
+ set -euo pipefail
+ name="kwnt-linux-${{ matrix.arch }}.tar.gz"
+ mkdir -p pkg out
+ cp target/release/kwnt pkg/kwnt
+ strip pkg/kwnt
+ chmod 755 pkg/kwnt
+ tar -czf "out/$name" -C pkg --owner=0 --group=0 kwnt
+ (cd out && sha256sum "$name" > "$name.sha256" && cat "$name.sha256")
+ - uses: actions/upload-artifact@v4
+ with:
+ name: kwnt-linux-${{ matrix.arch }}
+ path: out/
+ if-no-files-found: error
+ retention-days: 14
+
+ install-test:
+ name: install.sh ${{ matrix.arch }}
+ needs: binary
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - arch: x86_64
+ runner: ubuntu-22.04
+ - arch: aarch64
+ runner: ubuntu-22.04-arm
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 20
+ steps:
+ - uses: actions/checkout@v4
+ - name: shellcheck
+ run: shellcheck -s sh site/install.sh scripts/test_install_sh.sh scripts/test_install_sh.inner.sh
+ - uses: actions/download-artifact@v4
+ with:
+ name: kwnt-linux-${{ matrix.arch }}
+ path: dist
+ - name: install.sh in clean Ubuntu 22.04 and Debian 12
+ run: |
+ set -euo pipefail
+ (cd dist && sha256sum -c "kwnt-linux-${{ matrix.arch }}.tar.gz.sha256")
+ mkdir -p bin
+ tar -xzf "dist/kwnt-linux-${{ matrix.arch }}.tar.gz" -C bin
+ scripts/test_install_sh.sh bin/kwnt ubuntu:22.04 debian:12
+
+ image:
+ name: image (amd64 + arm64, not pushed)
+ needs: binary
+ runs-on: ubuntu-22.04
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: kwnt-linux-*
+ path: dist
+ - name: Binaries for the image (dist/docker/<docker arch>/kwnt)
+ run: |
+ set -euo pipefail
+ for pair in x86_64:amd64 aarch64:arm64; do
+ arch=${pair%%:*} darch=${pair#*:}
+ (cd "dist/kwnt-linux-$arch" && sha256sum -c "kwnt-linux-$arch.tar.gz.sha256")
+ mkdir -p "dist/docker/$darch"
+ tar -xzf "dist/kwnt-linux-$arch/kwnt-linux-$arch.tar.gz" -C "dist/docker/$darch"
+ done
+ ls -l dist/docker/*/kwnt
+ - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
+ - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
+ - name: Build for amd64 and arm64
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: .
+ file: docker/kwnt.Dockerfile
+ target: prebuilt
+ platforms: linux/amd64,linux/arm64
+ push: false
+ - name: Build amd64 into the local Docker
+ uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: .
+ file: docker/kwnt.Dockerfile
+ target: prebuilt
+ platforms: linux/amd64
+ load: true
+ tags: kwnt-ci:test
+ - name: The image starts and answers /api/health
+ run: |
+ set -euo pipefail
+ docker run -d --name kwnt-ci -p 127.0.0.1:18799:8799 kwnt-ci:test
+ ok=""
+ for _ in $(seq 60); do
+ if curl -fsS --max-time 3 http://127.0.0.1:18799/api/health > health.json 2>/dev/null \
+ && grep -q '"app":"kwnt"' health.json; then ok=1; break; fi
+ sleep 1
+ done
+ if [ -z "$ok" ]; then docker logs --tail 40 kwnt-ci; exit 1; fi
+ cat health.json; echo
+ docker run --rm --entrypoint kwnt kwnt-ci:test --version
+ docker rm -f kwnt-ci
diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml
index 8514af63..fa7bed4d 100644
--- a/.github/workflows/mac.yml
+++ b/.github/workflows/mac.yml
@@ -5,7 +5,8 @@ name: mac
# On pull requests and manual runs it is only a workflow artifact, proving the app builds and starts.
# Pushing a mac-v* tag (mac-v0.1.0, or mac-v0.2.0-rc.1 for a prerelease) also publishes a GitHub
# release with the .dmg as kwant_universal.dmg, which the site's "Download for Mac" links to via
-# releases/latest/download/kwant_universal.dmg. The tag must match apps/mac's version.
+# releases/latest/download/kwant_universal.dmg. The tag must match apps/mac's version and the root
+# Cargo.toml's (kwnt --version, /api/health).
#
# In-app updates: every build also makes the updater bundle (kwant.app.tar.gz + .sig). Tag builds
# sign it with the release key (secrets TAURI_SIGNING_PRIVATE_KEY / _PASSWORD) and a full release
@@ -18,6 +19,11 @@ name: mac
# carries them next to the Mac files, with linux-x86_64-* entries added after the darwin-* ones in
# the same latest.json. There is never a separate Linux release: it would become "latest" and hide
# the Mac latest.json from installed Macs.
+#
+# Own server: a tag also builds the standalone kwnt for Linux x86_64 and arm64 (kwnt-linux.yml) that
+# site/install.sh downloads; the release carries kwnt-linux-<arch>.tar.gz with a .sha256 each (and
+# kwant_universal.app.tar.gz.sha256 for the installer's Mac path), and once the release exists the
+# image job pushes the same binaries as ghcr.io/<owner>/kwnt:<version> (and :latest for a full release).
on:
workflow_dispatch:
pull_request:
@@ -54,7 +60,7 @@ jobs:
prerelease: ${{ steps.check.outputs.prerelease }}
steps:
- uses: actions/checkout@v4
- - name: Tag matches apps/mac version
+ - name: Tag matches apps/mac and kwnt versions
id: check
env:
TAG: ${{ github.ref_name }}
@@ -64,9 +70,11 @@ jobs:
base="${version%%-*}"
cargo=$(sed -n 's/^version = "\(.*\)"/\1/p' apps/mac/Cargo.toml | head -1)
tauri=$(python3 -c 'import json;print(json.load(open("apps/mac/tauri.conf.json"))["version"])')
- echo "tag $TAG -> $version (base $base); Cargo.toml $cargo; tauri.conf.json $tauri"
- if [ "$base" != "$cargo" ] || [ "$base" != "$tauri" ]; then
- echo "::error::tag $TAG doesn't match apps/mac version $cargo (tauri.conf.json $tauri)"
+ # kwnt --version and /api/health report the root crate's version: release them together
+ kwnt=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
+ echo "tag $TAG -> $version (base $base); Cargo.toml $cargo; tauri.conf.json $tauri; kwnt $kwnt"
+ if [ "$base" != "$cargo" ] || [ "$base" != "$tauri" ] || [ "$base" != "$kwnt" ]; then
+ echo "::error::tag $TAG doesn't match apps/mac version $cargo (tauri.conf.json $tauri, kwnt Cargo.toml $kwnt)"
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
@@ -439,9 +447,18 @@ jobs:
uses: ./.github/workflows/linux.yml
secrets: inherit
+ # The standalone kwnt for servers (no secrets: nothing in it is signed)
+ kwnt-linux:
+ name: kwnt-linux
+ needs: version
+ if: startsWith(github.ref, 'refs/tags/mac-v')
+ permissions:
+ contents: read
+ uses: ./.github/workflows/kwnt-linux.yml
+
release:
name: release
- needs: [version, dmg, linux]
+ needs: [version, dmg, linux, kwnt-linux]
if: startsWith(github.ref, 'refs/tags/mac-v')
runs-on: ubuntu-latest
timeout-minutes: 10
@@ -488,6 +505,18 @@ jobs:
cp "$zsync_file" kwant_x86_64.AppImage.zsync
test "$(sed -n 's/^SHA-1: //p' kwant_x86_64.AppImage.zsync | head -1)" = "$(sha1sum kwant_x86_64.AppImage | cut -d' ' -f1)"
assets+=(kwant_x86_64.AppImage.zsync)
+ # The one-line install (site/install.sh) checks each download against its .sha256: the
+ # Mac app's updater bundle, and the standalone kwnt for Linux servers (kwnt-linux.yml)
+ sha256sum kwant_universal.app.tar.gz > kwant_universal.app.tar.gz.sha256
+ assets+=(kwant_universal.app.tar.gz.sha256)
+ for arch in x86_64 aarch64; do
+ f="kwnt-linux-$arch.tar.gz"
+ test -f "dist/kwnt-linux-$arch/$f"
+ test -f "dist/kwnt-linux-$arch/$f.sha256"
+ cp "dist/kwnt-linux-$arch/$f" "dist/kwnt-linux-$arch/$f.sha256" .
+ sha256sum -c "$f.sha256"
+ assets+=("$f" "$f.sha256")
+ done
dl="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG"
# Installed apps read releases/latest/download/latest.json, which only ever resolves to the
# newest full release; a prerelease gets no latest.json, so it's never offered as an update
@@ -524,6 +553,14 @@ jobs:
\`kwant_amd64.deb\` for Ubuntu 22.04 or later and Debian 12 (\`sudo apt install ./kwant_amd64.deb\`), or \`kwant_x86_64.AppImage\` for other distros with a GTK desktop (\`chmod +x\` it and run it). Both update themselves in the app.
SHA-256: \`$(cut -d' ' -f1 kwant_amd64.deb.sha256)\` (.deb), \`$(cut -d' ' -f1 kwant_x86_64.AppImage.sha256)\` (AppImage)
+
+ ### Own server (Linux x86_64 or arm64)
+
+ One line, no sudo: \`curl -fsSL https://kwant.si/install.sh | sh\`. It checks the download, runs kwant as a service for your user and prints a one-time sign-in link. Running it again upgrades. Needs glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+).
+
+ With Docker: \`docker compose up -d\` in a clone of this repository (the kwnt image is \`ghcr.io/$GITHUB_REPOSITORY_OWNER/kwnt:$VERSION\`).
+
+ SHA-256: \`$(cut -d' ' -f1 kwnt-linux-x86_64.tar.gz.sha256)\` (x86_64), \`$(cut -d' ' -f1 kwnt-linux-aarch64.tar.gz.sha256)\` (arm64)
NOTES
sed -i 's/^ //' notes.md
flags=()
@@ -531,3 +568,57 @@ jobs:
gh release create "$TAG" -R "$GITHUB_REPOSITORY" --verify-tag \
--title "kwant $VERSION for Mac and Linux" --notes-file notes.md "${flags[@]}" \
"${assets[@]}"
+
+ # The kwnt image, from the binaries the release just published, for amd64 and arm64. After the
+ # release, so an image never points at a version that has no release.
+ image:
+ name: image
+ needs: [version, release]
+ if: startsWith(github.ref, 'refs/tags/mac-v')
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ packages: write
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/download-artifact@v4
+ with:
+ pattern: kwnt-linux-*
+ path: dist
+ - name: Binaries for the image (dist/docker/<docker arch>/kwnt)
+ run: |
+ set -euo pipefail
+ for pair in x86_64:amd64 aarch64:arm64; do
+ arch=${pair%%:*} darch=${pair#*:}
+ (cd "dist/kwnt-linux-$arch" && sha256sum -c "kwnt-linux-$arch.tar.gz.sha256")
+ mkdir -p "dist/docker/$darch"
+ tar -xzf "dist/kwnt-linux-$arch/kwnt-linux-$arch.tar.gz" -C "dist/docker/$darch"
+ done
+ - name: Tags
+ id: tags
+ env:
+ VERSION: ${{ needs.version.outputs.version }}
+ PRERELEASE: ${{ needs.version.outputs.prerelease }}
+ run: |
+ set -euo pipefail
+ image="ghcr.io/$(echo "$GITHUB_REPOSITORY_OWNER" | tr '[:upper:]' '[:lower:]')/kwnt"
+ tags="$image:$VERSION"
+ # a prerelease never moves :latest, as it never becomes the latest release
+ if [ "$PRERELEASE" != "true" ]; then tags="$tags,$image:latest"; fi
+ echo "tags=$tags" >> "$GITHUB_OUTPUT"
+ - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
+ - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
+ - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ github.token }}
+ - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
+ with:
+ context: .
+ file: docker/kwnt.Dockerfile
+ target: prebuilt
+ platforms: linux/amd64,linux/arm64
+ push: true
+ tags: ${{ steps.tags.outputs.tags }}
diff --git a/Cargo.lock b/Cargo.lock
index cad915b6..b852330d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1417,7 +1417,7 @@ dependencies = [
[[package]]
name = "kwnt"
-version = "0.1.0"
+version = "0.7.5"
dependencies = [
"aes",
"argon2",
diff --git a/Cargo.toml b/Cargo.toml
index 0d982fd9..d029e21d 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "kwnt"
-version = "0.1.0"
+version = "0.7.5"
edition = "2021"
description = "A self-hosted team of AI bots: spaces, multiple accounts, handoffs, approvals and routines, in one binary"
license = "AGPL-3.0-only"
diff --git a/apps/mac/Cargo.lock b/apps/mac/Cargo.lock
index c471b358..589a9dcb 100644
--- a/apps/mac/Cargo.lock
+++ b/apps/mac/Cargo.lock
@@ -2727,7 +2727,7 @@ dependencies = [
[[package]]
name = "kwnt"
-version = "0.1.0"
+version = "0.7.5"
dependencies = [
"aes",
"argon2",
diff --git a/apps/mac/README.md b/apps/mac/README.md
index 8819a192..775214a1 100644
--- a/apps/mac/README.md
+++ b/apps/mac/README.md
@@ -109,6 +109,11 @@ desktop file, the update information and the `.zsync`, the same checks the AppIm
## Releases and the updater key
+A release commit sets one version in `apps/mac/Cargo.toml`, `apps/mac/tauri.conf.json` and the
+root `Cargo.toml` (kwnt's own version, shown by `kwnt --version` and `/api/health`), with both
+`Cargo.lock` files. `tests/version_test.rs` fails when they disagree, and mac.yml refuses a
+`mac-v*` tag that doesn't match all three.
+
`mac.yml` signs the updater bundle on `mac-v*` tags with the repository secrets
`TAURI_SIGNING_PRIVATE_KEY` and `TAURI_SIGNING_PRIVATE_KEY_PASSWORD`, checks the signature
(`scripts/minisign_verify.py`) and, for a full release, publishes `latest.json` built by
diff --git a/docker-compose.yml b/docker-compose.yml
index 3d641ede..6290f272 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,8 +1,10 @@
-# kwant on a server, everything in one command: docker compose up -d --build
+# kwant on a server, everything in one command: docker compose up -d
# kwnt the app, UI on 127.0.0.1:8799 (KWNT_HOST_PORT to change; put HTTPS in front: see README "VPS in 5 minutes")
-# laya picks which bot answers (model baked into the image)
-# browser the bots' private Chromium, so VM mode works without the Docker socket
-# AI CLIs in the image: KWNT_CLIS=claude,codex,grok docker compose up -d --build
+# The released image (ghcr.io/alexsergivan/kwnt; KWNT_VERSION=0.7.6 to pin one), built here only if it can't be pulled
+# laya picks which bot answers (model baked into the image; built here on the first start)
+# browser the bots' private Chromium, so VM mode works without the Docker socket (built here too)
+# Upgrade: docker compose pull kwnt && docker compose up -d
+# AI CLIs in the image, or kwnt from this checkout: KWNT_CLIS=claude,codex,grok docker compose up -d --build
# Check what's missing: docker compose exec kwnt kwnt doctor
services:
laya:
@@ -36,7 +38,7 @@ services:
dockerfile: docker/kwnt.Dockerfile
args:
KWNT_CLIS: ${KWNT_CLIS:-}
- image: kwnt:latest
+ image: ghcr.io/alexsergivan/kwnt:${KWNT_VERSION:-latest}
restart: unless-stopped
ports:
- "127.0.0.1:${KWNT_HOST_PORT:-8799}:8799"
diff --git a/docker/kwnt.Dockerfile b/docker/kwnt.Dockerfile
index 7e51428e..f0fb03ed 100644
--- a/docker/kwnt.Dockerfile
+++ b/docker/kwnt.Dockerfile
@@ -1,6 +1,9 @@
# Kwant server: React UI embedded in a single Rust binary.
# AI CLIs are optional: --build-arg KWNT_CLIS=claude,codex,grok (any subset; default none).
# With Compose: KWNT_CLIS=claude,codex docker compose up -d --build
+# Needs BuildKit (the default in Docker 23+ and Compose v2). The last stage builds kwnt from source;
+# the `prebuilt` stage is the published ghcr.io image, made from the release's own binaries
+# (dist/docker/<amd64|arm64>/kwnt, unpacked from kwnt-linux-<arch>.tar.gz by the workflow).
FROM node:20-bookworm-slim AS web
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json ./
@@ -39,7 +42,7 @@ RUN set -eu; mkdir -p /opt/clis/bin; \
fi; \
ls /opt/clis/bin
-FROM debian:bookworm-slim
+FROM debian:bookworm-slim AS runtime
ARG KWNT_CLIS=""
# kwnt needs CA certificates, and git (2.31+) with ssh for Dev mode, which reads every watched repo
# with git; the CLIs' own tools want a few more basics.
@@ -50,7 +53,6 @@ RUN apt-get update \
&& useradd --uid 10001 --create-home --home-dir /home/kwnt --shell /bin/bash kwnt \
&& mkdir -p /data && chown kwnt:kwnt /data
COPY --from=clis /opt/clis /opt/clis
-COPY --from=build /app/target/release/kwnt /usr/local/bin/kwnt
COPY docker/kwnt-entrypoint.sh /usr/local/bin/kwnt-entrypoint
RUN chmod 755 /usr/local/bin/kwnt-entrypoint
ENV PATH=/opt/clis/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \
@@ -68,3 +70,15 @@ VOLUME /data
EXPOSE 8799
ENTRYPOINT ["/usr/local/bin/kwnt-entrypoint"]
CMD ["kwnt", "serve"]
+
+# The release image: the same kwnt the release ships for this architecture
+FROM runtime AS prebuilt
+ARG TARGETARCH
+LABEL org.opencontainers.image.source="https://github.com/alexsergivan/kwant" \
+ org.opencontainers.image.description="kwant server (kwnt serve), the web UI embedded" \
+ org.opencontainers.image.licenses="AGPL-3.0-only"
+COPY dist/docker/${TARGETARCH}/kwnt /usr/local/bin/kwnt
+
+# The default (docker compose build, docker build .): kwnt built from this checkout
+FROM runtime
+COPY --from=build /app/target/release/kwnt /usr/local/bin/kwnt
diff --git a/docs/smart-results.md b/docs/smart-results.md
index 73c20b09..49849f96 100644
--- a/docs/smart-results.md
+++ b/docs/smart-results.md
@@ -2,7 +2,7 @@
A bot's final reply can carry one typed block, `results`, that the chat draws in place of a table
or a list in the reply: a chart, a comparison, key numbers, findings, cards, steps (plain, checklist
-or timeline) or facts. The reply's
+or timeline), facts or a recipe. The reply's
text is never changed. When there is no block, or the chat can't draw it, the reply shows its
markdown as it always has.
@@ -26,13 +26,13 @@ Code: `src/server/smart_results/` (contract types, selectors, checks) and
- **How the block is chosen:** each table gets at most one class (line chart, else bar chart unless
the prose names a pick, else metrics, else comparison) and each list at most one (metrics,
findings, cards, timeline, checklist, steps, facts). The candidates are then offered in the order
- of `selector::PRIORITY`: chart > comparison > metrics > findings > cards > timeline > checklist >
+ of `selector::PRIORITY`: recipe > chart > comparison > metrics > findings > cards > timeline > checklist >
steps > facts. A tie goes to the earliest in the text. The first candidate whose type is in
`ENABLED_TYPES` and that passes the checks is stored, and only that one: a message has at most
one block.
- **The bot prompt line:** every turn's system prompt carries `smart_results::PROMPT_LINE` once
(in the cached tail, `drivers::TurnInput::system_prompt_parts`), asking for tables, numbered
- steps and `**Label:** value` lines.
+ steps, an "Ingredients" list then numbered steps for a recipe, and `**Label:** value` lines.
- **What it never costs:** the reply. If a selector panics, a block fails its checks, or the write
fails, kwant logs it and saves the message exactly as before.
- **Edits:** when a reply's text is replaced (`set_message_text`), its block is deleted, because the
@@ -149,6 +149,32 @@ a literal "Owner: X" or "(owner: X)".
**Facts:** 3–12 items `**Label:** value`, more than half of them not starting with a number.
+**Recipe** (0.7.6; the `Recipe` type in `mod.rs` is the reference). One block for the
+recipe part of a reply: the dish heading, a Serves/time line, the Ingredients lists (with group
+labels), the method and optional notes. The intro and the closing question stay text.
+- Exactly one ingredients cue: a heading or one-line paragraph "Ingredients" (also
+ "Ingredients (serves 4)", "Ingredient list"), or a one-line intro ending in ":" with "ingredients"
+ in it, right before the list. A second cue (a meal plan) gives no recipe.
+- Then 1+ bullet lists of 2–40 ingredients in total (each list may sit under a short group label),
+ then the method: an ordered list, or any list under Method / Instructions / Steps / Directions /
+ Preparation (2–30 steps). Optional notes after it: a Notes / Tips label and a list of 1–6 items.
+- Every top-level block in the section must be accounted for. A prose paragraph, code block, table,
+ quote or HTML in between, a list straight after the method, a second list→numbered-list pair in
+ the reply, steps that read as a weekly plan, or any list past the line where the count becomes
+ unsure: no recipe.
+- `serves` (1–24) and up to 3 `times` come from a meta line or list (`**Serves 4** · Prep 15 min`,
+ `- **Prep time:** 10 minutes`); one the server can't read ("Serves 4–6") stays text above the card.
+- `qty` is the leading amount as written, split off only when `qty + text` (with a space, or none
+ when the text starts with ",") rebuilds the line exactly. A temperature ("350 °F oven", "180C",
+ "350 degrees") is not an amount, so it gets no `qty` and never scales; a lone capital `C` is a
+ temperature only after 90 or more, so "1 C sugar" (a cup) still scales. A GFM task box in front
+ of an ingredient or a note is dropped.
+- Ranks above every other reply selector; recipe replies hold lists the steps and metrics selectors
+ would otherwise take.
+- Source `markdown_section` `{index, ordered, last_index, last_ordered, lead}`: the first and last
+ list of the section, and how many top-level nodes before the first list belong to it. Only a
+ recipe may use it, and a recipe may use nothing else.
+
**Comparison:**
- the table is a clean top-level GFM pipe table;
- it has 2–8 columns and 3–50 rows, every row with as many cells as the header;
@@ -228,7 +254,7 @@ routes.
**`present_result`** is a self tool (offered in `tool_list`, dispatched in `call_tool`). A bot
calls it once before its final reply to say which table or list it wants drawn: `type`
-(`comparison` or `steps`), `source` (`markdown_table` or `markdown_list` and the `index`), `data`.
+(`comparison`, `steps` or `recipe`), `source` (`markdown_table` or `markdown_list` and the `index`), `data`.
Nothing is trusted at call time. When the message is saved, the last call that was valid (status
`ok` or `allowed`) is held to the final reply: the comparison's column labels are in the table's
header, every declared row matches one row of that table cell by cell (a value moved under another
@@ -238,6 +264,9 @@ the named list. Any failure drops the call (logged) and the normal selectors run
call without `source` is refused for a comparison (and for steps). A bot cannot declare
`verification` or `files`, and cannot set provenance: kwant writes `bot_declared` with the call's id.
Calls over 64 KB are refused.
+A `recipe` call has no `source` and `data: {ingredients: [full lines], steps: [texts]}`; it grounds
+only when the reply's own recipe has the same ingredients and steps in the same order, and the
+stored block is the one read from the reply, with `bot_declared` provenance.
Not yet declarable: `chart`, `metrics`, `facts`, `cards`, `findings`. They arrive with
`smart-results-more`; for metrics the plan's rule applies then (each label and its value must be on
diff --git a/docs/teams-api.md b/docs/teams-api.md
index 7dce081f..c8a46395 100644
--- a/docs/teams-api.md
+++ b/docs/teams-api.md
@@ -301,12 +301,15 @@ Before it, the sheet's confirm reads `GET /api/teams/:id/template`:
"handle": "inbox"
},
"chat_messages": 4,
+ "archived_chat": "archived-team-inbox-2",
"also_in": [{"bot": "Drafter", "team": "support"}],
"edited_skills": [],
"needs_done": []
}
```
+`archived_chat`: the name Undo will give the team chat when it keeps it (it has messages): `archived-team-<handle>`, or with `-2`, `-3`… when that name is taken, ignoring case. `null` when Undo deletes the chat (no messages) or doesn't touch it (an existing team). It's worked out from the chats as they are now, so a chat made with that name before the person clicks Undo can still move it on by one.
+
`needs_done`: ids of the template's Needs (§1) the server can see are done. Today that's only the `composer_prompt` need, Sales' `what_you_sell` (A5): done once the team chat has a message from the person. The other Needs (connect email, a CRM, a repo) are ticked by the client from its own state, as before.
404 `not_a_template_team` when the team wasn't made by a template or a suggestion (or was made before 0.7.7).
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 4a911713..a6830c44 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -6,7 +6,10 @@ import { InboxPage } from './components/InboxPage';
import { InboxTab, SettingsScope, SpaceView, viewSegment } from './nav';
import { PHONE_QUERY } from './layout';
import { useSettingsCover } from './settingsFocus';
-import { FirstRunWelcome } from './components/FirstRunWelcome';
+import { WhatsNewHost } from './components/WhatsNewSheet';
+import { GetStarted, GetStartedBanner } from './components/GetStarted';
+import { dismiss as dismissGetStarted, isDismissed as getStartedDismissed, showCard as showGetStarted, wasStarted as getStartedWasStarted, whatsNewEstablished as decideWhatsNewEstablished } from './gettingStarted';
+import { useStartVersion } from './gettingStartedInstall';
import { SpaceTile } from './components/Spaces';
import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState, SendOptions } from './components/ChatView';
import { ReactResult, Reaction, optimisticReplyRef, reactionOf, saveReaction, senderLabel } from './reactReply';
@@ -53,13 +56,12 @@ import { ideasApi, takeArrivedText } from './ideas';
import { JarIcon } from './components/JarIcon';
import { IdeaDropToast, type IdeaDropToastState } from './components/IdeaDropToast';
import { JAR_DROPPED, JAR_SEND_FAILED, ideaSendOutcome, useJarWobble, wobbleJar } from './ideaShell';
-import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings, Sparkles } from 'lucide-react';
+import { Bot, Check, HelpCircle, Inbox, KeyRound, ListChecks, Loader2, MessageSquare, Settings } from 'lucide-react';
import { TG_EVENT, TelegramEventDetail, forThisSpace } from './telegram';
import { ChatApproval, OpenChat, addSettled, settledFromRecords, withdrawApproval, approvalFromEvent, lateAnswerText, approvalsForChat, approvalsFromAway, syncApprovals, upsertApproval, withoutApproval } from './approvals';
import type { AgentFormData } from './components/NewAgentModal';
import { NewTeamModal } from './components/NewTeamModal';
import { ReadyTeamsProvider, TeamNeedsTop, type ReadyTeam } from './components/ReadyTeams';
-import { ReadyTeamsWelcome } from './components/ReadyTeamsEntry';
import { NewChannelModal } from './components/NewChannelModal';
import type { NewChannelBody } from './channels';
import { ManageTeamModal } from './components/ManageTeamModal';
@@ -238,6 +240,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const [selectedTeamId, setSelectedTeamId] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [messagesError, setMessagesError] = useState<string | null>(null);
+ /** The chat whose messages have finished loading at least once since it opened (What's new waits for it). */
+ const [messagesLoadedFor, setMessagesLoadedFor] = useState<string | null>(null);
// The open thread of the selected bot; null for its direct chat (and for channels).
const [openThreadId, setOpenThreadId] = useState<string | null>(null);
const openCtx = openThreadId || selectedId;
@@ -364,8 +368,22 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
return () => void (gone = true);
}, [claudeMissing]);
const offerSetup = claudeMissing && claudeInstallable;
- const setupLabel = offerSetup ? 'Set up Claude' : offerClaude ? 'Sign in with Claude' : 'Add an account';
const setupAction = offerSetup || offerClaude ? openClaudeSignIn : openSettings;
+ // O2: the Get started card in #general (design next-076/onboarding §3–§13). Re-renders when this
+ // browser's getting-started state changes (choice, kept, dismissed).
+ useStartVersion();
+ const gsDismissed = getStartedDismissed(space.id);
+ // C1: on a phone, open #general while getting started is unfinished (not the chats list). Once.
+ const c1Done = useRef(false);
+ useEffect(() => {
+ if (c1Done.current || !isPhone || !loaded || canRun === null) return;
+ c1Done.current = true;
+ if (canRun !== false || gsDismissed || initialView || initialTarget?.channelId || initialTarget?.botId || initialTarget?.live) return;
+ const general = channels.find((c) => c.id === space.general_channel_id) ?? channels.find((c) => c.name === 'general');
+ if (general) handleSelectChannel(general);
+ else setPhoneView('chat');
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isPhone, loaded, canRun, channels]);
// The sidebar and chat under Settings: inert while it's open (the space rail stays usable).
const contentRef = useRef<HTMLDivElement>(null);
useSettingsCover(!!spaceSettingsTab, contentRef);
@@ -916,6 +934,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setMessagesError(null);
refreshContext(openCtx).then(() => {
if (openCtxRef.current !== openCtx) return;
+ setMessagesLoadedFor(openCtx);
const data = messagesCacheRef.current[openCtx] || [];
setTokensUsed(data.reduce((acc, m) => acc + (m.tokens_used || 0), 0));
});
@@ -1593,6 +1612,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const handleSendMessage = async (text: string, attachments: AttachmentRef[] = [], opts: SendOptions = {}): Promise<boolean | string> => {
haptic('tap');
setHistoryWindow(null);
+ // O2 §3: the Get started card goes after the person's first message in any chat, once something can answer.
+ if (canRun !== false && !getStartedDismissed(space.id)) dismissGetStarted(space.id);
const targetId = openCtx;
const threadId = openThreadId;
const isTargetChannel = isChannel;
@@ -3358,28 +3379,32 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
const readyAccounts = space.counts?.ready_accounts ?? 0;
// The space has bots but nothing can run them (a fresh install's starter bots): the checklist's
// first step, kept above the chat until an account works.
+ // §7.1: outside #general the banner is the card's one-liner; Open goes to #general and the card.
+ const openGetStarted = () => {
+ const general = channels.find((c) => c.id === space.general_channel_id) ?? channels.find((c) => c.name === 'general');
+ if (general) handleSelectChannel(general);
+ window.setTimeout(() => document.querySelector('[data-get-started]')?.scrollIntoView({ block: 'start', behavior: 'auto' }), 60);
+ };
const setupBanner =
- loaded && kwants.length > 0 && canRun === false ? (
- <div
- role="status"
- data-setup-banner
- className="shrink-0 px-3 sm:px-6 py-2.5 border-b border-violet-500/20 bg-violet-500/[0.06] flex flex-wrap items-center gap-x-3 gap-y-2"
- >
- <Sparkles size={15} className="shrink-0 text-violet-300" aria-hidden="true" />
- <div className="flex-1 min-w-[12rem]">
- <p className="text-xs font-medium text-zinc-100">One step left: add an account</p>
- <p className="text-[11px] text-zinc-400">Sign in with Claude or ChatGPT, or paste an API key, and your bots can start answering.</p>
- </div>
- <button
- type="button"
- onClick={setupAction}
- data-setup-action={offerSetup ? 'install-claude' : offerClaude ? 'sign-in-claude' : 'add-account'}
- className="shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-violet-600 hover:bg-violet-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-violet-300"
- >
- <KeyRound size={13} aria-hidden="true" />
- {setupLabel}
- </button>
- </div>
+ loaded && kwants.length > 0 && canRun === false && !gsDismissed ? (
+ <GetStartedBanner space={space.id} engines={engines.engines} onOpen={openGetStarted} />
+ ) : null;
+ const getStartedEligible = showGetStarted({
+ dismissed: gsDismissed,
+ canRun,
+ generalMessages: messages.length,
+ teams: teams.length,
+ started: getStartedWasStarted(space.id),
+ });
+ const getStartedCard =
+ loaded && (!openCtx || messagesLoadedFor === openCtx) && kwants.length > 0 && isGeneral && getStartedEligible ? (
+ <GetStarted
+ space={space.id}
+ bots={kwants}
+ engines={engines.engines}
+ reloadEngines={engines.reload}
+ onDismissed={() => undefined}
+ />
) : null;
const setupChecklist = (
<main className="flex-1 min-w-0 overflow-y-auto flex items-start sm:items-center justify-center p-4 sm:p-8" data-space-checklist>
@@ -3706,20 +3731,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onAddAccount={setupAction}
onOpenNeed={(opens) => openTeamNeed(opens, currentTeam)}
/>
+ ) : getStartedCard && messages.length > 0 ? (
+ getStartedCard
) : undefined
}
- welcome={
- setupBanner && isChannel && !selectedTeamId && !currentTeam ? (
- <>
- <FirstRunWelcome
- bots={kwants}
- actionLabel={setupLabel}
- onAction={setupAction}
- />
- <ReadyTeamsWelcome onBlank={() => setIsNewTeamOpen(true)} />
- </>
- ) : undefined
- }
+ welcome={getStartedCard && messages.length === 0 ? getStartedCard : undefined}
onOpenAccounts={openSettings}
onOpenUsage={openUsageSettings}
canRun={canRun}
@@ -3839,6 +3855,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
{ id: 'space', label: 'Space', icon: <Settings size={20} aria-hidden="true" /> },
];
const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;
+ // What's new after an update: only for someone who has used kwant (they've written here, or an account
+ // works and Get started isn't showing). A brand-new person gets Get started instead (F-1); unknown until
+ // the space and the open chat's messages have loaded.
+ const wroteHere = messages.some((m) => m.sender_role === 'user');
+ const whatsNewEstablished = decideWhatsNewEstablished({
+ loaded,
+ messagesLoaded: !openCtx || messagesLoadedFor === openCtx,
+ canRun,
+ wroteHere,
+ getStartedShowing: getStartedEligible,
+ });
const readyBots = useMemo(() => kwants.map((k) => ({ id: k.id, name: k.name, role: k.avatar_sprite })), [kwants]);
return (
@@ -4143,6 +4170,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
{jarAnnouncement}
</p>
<NeedsYouPill items={pill.items} rev={pill.rev} spriteOf={spriteOf} onOpen={openPill} onDismiss={dismissPill} />
+ <WhatsNewHost established={whatsNewEstablished} onOpen={(v) => applyViewRef.current(v)} />
</div>
</ReadyTeamsProvider>
);
diff --git a/frontend/src/components/AppUpdateBanner.tsx b/frontend/src/components/AppUpdateBanner.tsx
index 926bf6fc..25cefee5 100644
--- a/frontend/src/components/AppUpdateBanner.tsx
+++ b/frontend/src/components/AppUpdateBanner.tsx
@@ -3,6 +3,8 @@ import { AlertTriangle, ArrowUpCircle, CheckCircle2, ExternalLink, Info, Loader2
import { BannerView, UpdateController, UpdateModel, aboutLine, appUpdateController, bannerView, dismissVersion, dismissedVersion } from '../appUpdate';
import { MarkdownRenderer } from './MarkdownRenderer';
import { desktopAppOs } from '../externalLinks';
+import { hasWhatsNew } from './WhatsNewSheet';
+import { openWhatsNew } from '../whatsNewSheet';
const PHONE_QUERY = '(max-width: 767px)';
const UPDATED_NOTE_MS = 10000;
@@ -18,13 +20,15 @@ interface ViewProps {
view: BannerView;
onUpdate: () => void;
onDismiss: () => void;
+ /** "See what's new" on the "Updated to" bar, when there's a What's new sheet for that version. */
+ onWhatsNew?: () => void;
}
const btn =
'inline-flex min-h-[32px] items-center gap-1.5 rounded-lg px-3 text-xs font-medium focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
/** The slim bar itself, without the polling: what tests and screenshots render. */
-export const AppUpdateBannerView: React.FC<ViewProps> = ({ view, onUpdate, onDismiss }) => {
+export const AppUpdateBannerView: React.FC<ViewProps> = ({ view, onUpdate, onDismiss, onWhatsNew }) => {
const [notesOpen, setNotesOpen] = useState(false);
const notesId = useId();
const notes = view.kind === 'available' || view.kind === 'error' ? view.notes.trim() : '';
@@ -109,6 +113,17 @@ export const AppUpdateBannerView: React.FC<ViewProps> = ({ view, onUpdate, onDis
</div>
)}
+ {view.kind === 'updated' && onWhatsNew && (
+ <button
+ type="button"
+ onClick={onWhatsNew}
+ data-see-whats-new
+ className={`${btn} min-h-[28px] h-7 border border-emerald-300/35 px-2.5 text-emerald-200 hover:bg-emerald-500/15 hover:text-emerald-50`}
+ >
+ See what’s new
+ </button>
+ )}
+
{(view.kind === 'available' || view.kind === 'updated') && (
<button
type="button"
@@ -158,6 +173,7 @@ export const AppUpdateBanner: React.FC = () => {
key={`${view.kind}-${view.version}`}
view={view}
onUpdate={() => void ctrl.install()}
+ onWhatsNew={view.kind === 'updated' && hasWhatsNew(view.version) ? () => openWhatsNew(view.version) : undefined}
onDismiss={() => {
if (view.kind === 'updated') return ctrl.clearUpdated();
dismissVersion(view.version);
diff --git a/frontend/src/components/BrowserTakeoverStage.tsx b/frontend/src/components/BrowserTakeoverStage.tsx
index ead12abd..ef2c968c 100644
--- a/frontend/src/components/BrowserTakeoverStage.tsx
+++ b/frontend/src/components/BrowserTakeoverStage.tsx
@@ -80,6 +80,11 @@ export interface BrowserTakeoverStageProps {
handBackQuiet?: boolean;
/** A strip under the top bar, such as the Recording bar. */
belowBar?: React.ReactNode;
+ /**
+ * F4: other chats are browsing too. The panel's switcher is under this stage while you're in
+ * control, so its "Hand back first" can't be reached; Hand back says it instead.
+ */
+ othersBrowsing?: boolean;
}
const BUTTON_BIT: Record<number, number> = { 0: 1, 1: 4, 2: 2 };
@@ -89,7 +94,7 @@ const BUTTON_BIT: Record<number, number> = { 0: 1, 1: 4, 2: 2 };
* drawn 1:1 with the page resized to match. Mouse, wheel and keyboard go to the page as they are;
* the top bar keeps the address, history and "Hand back".
*/
-export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botName, pageUrl, pageTitle, stream, image, step, avatarRole, onNavigate, notice, onHandBack, onRetryControl, extraAction, handBackQuiet = false, belowBar }) => {
+export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botName, pageUrl, pageTitle, stream, image, step, avatarRole, onNavigate, notice, onHandBack, onRetryControl, extraAction, handBackQuiet = false, belowBar, othersBrowsing = false }) => {
const { send, controlling, frame, acknowledgeFrame } = stream;
const stageRef = useRef<HTMLDivElement>(null);
const imgRef = useRef<HTMLImageElement>(null);
@@ -454,6 +459,7 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botN
const focusOut = controlling && !pageFocused && !popupOpen;
const outline = controlling ? (focusOut ? 'rgb(124 196 255 / 0.45)' : '#7cc4ff') : 'rgb(255 255 255 / 0.14)';
const hintId = useId();
+ const switchHintId = useId();
const coarse = '[@media(pointer:coarse)]:h-11';
const navButton = `shrink-0 inline-flex items-center justify-center w-8 h-8 [@media(pointer:coarse)]:w-11 ${coarse} rounded-lg text-zinc-200 hover:bg-white/[0.06] aria-disabled:text-[#5a5383] aria-disabled:hover:bg-transparent aria-disabled:cursor-default focus:outline-none focus-visible:ring-2 focus-visible:ring-[#b8adff]`;
@@ -568,11 +574,18 @@ export const BrowserTakeoverStage: React.FC<BrowserTakeoverStageProps> = ({ botN
ref={actionRef}
type="button"
onClick={onHandBack}
+ title={othersBrowsing ? 'Hand back first to switch browser' : undefined}
+ aria-describedby={othersBrowsing ? switchHintId : undefined}
className={`${actionButton} ${step || handBackQuiet ? GHOST_BUTTON : PRIMARY_BUTTON}`}
data-primary={(!step && !handBackQuiet) || undefined}
>
<Hand size={15} aria-hidden="true" /> Hand back
</button>
+ {othersBrowsing && (
+ <span id={switchHintId} className="sr-only">
+ Hand back first to switch browser
+ </span>
+ )}
{step && (
<button type="button" onClick={answerStep} disabled={stepBusy} className={`${actionButton} ${PRIMARY_BUTTON}`} data-primary>
{stepBusy ? <Loader2 size={15} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Check size={15} aria-hidden="true" />}
diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsx
index b2137fa0..6d815e87 100644
--- a/frontend/src/components/ChatView.tsx
+++ b/frontend/src/components/ChatView.tsx
@@ -1,10 +1,11 @@
import React, { Fragment, useState, useRef, useEffect, useLayoutEffect, useMemo } from 'react';
import type { SwitchEntry } from '../watchLive';
-import { trialCardsAfter } from '../showOnce';
+import { emptyTrialReplyLine, trialCardsAfter, trialOf } from '../showOnce';
+import { parsePick } from '../engines';
import { onContinuity } from '../continuity';
import { TrialWaitsCard } from './SkillsPanel';
import { agentSenderLabel } from '../agentConnections';
-import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor } from 'lucide-react';
+import { ArrowDown, ArrowUp, AtSign, Paperclip, Sparkles, ChevronDown, ChevronRight, Copy, Check, ChevronLeft, Users, Square, Settings2, Folder, GitBranch, Pencil, Pin, Monitor, CircleSlash } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { BotHome } from './BotHome';
import { ChatHome, answerTarget, goodAt, recipientsOf } from '../botHome';
@@ -182,7 +183,7 @@ export interface ChatViewProps {
/** Saves the person's thumbs on a bot reply; absent hides the thumbs. */
onReact?: (msg: ChatMessage, reaction: Reaction | null) => Promise<ReactResult> | void;
onResolveApproval: (id: string, decision: 'allow_once' | 'always_allow' | 'deny') => void;
- kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string }>;
+ kwants?: Array<{ id: string; name: string; title: string; avatar_sprite: string; preferred_model?: string }>;
teams?: Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>;
/** Prompts offered above an empty chat, made from who is in it; none hides the bar. */
suggestions?: string[];
@@ -524,7 +525,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
};
// Fallback to fetch kwants and teams if not provided as props
- const [internalKwants, setInternalKwants] = useState<Array<{ id: string; name: string; title: string; avatar_sprite: string }>>([]);
+ const [internalKwants, setInternalKwants] = useState<Array<{ id: string; name: string; title: string; avatar_sprite: string; preferred_model?: string }>>([]);
const [internalTeams, setInternalTeams] = useState<Array<{ id: string; name: string; description?: string; member_kwants?: string[] }>>([]);
useEffect(() => {
@@ -1207,6 +1208,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
const shownDecisions = isUser ? null : messageDecisions(msg.text, msg.meta);
const decisions = shownDecisions?.decisions ?? [];
const text = shownDecisions ? shownDecisions.text : msg.text;
+ // S-F7: a trial turn that came back empty says so, in muted text, instead of a blank bubble.
+ const emptyTrial =
+ !isUser && msg.sender_role === 'kwant' && !(text ?? '').trim() && !files.length && msg.results == null && trialOf(msg)
+ ? emptyTrialReplyLine(parsePick(activeKwants.find((k) => k.id === msg.sender_id || k.name === msg.sender_id)?.preferred_model).family)
+ : null;
const workAhead = isUser ? null : parseWorkAhead(msg.meta);
const displayName = isUser ? agentSenderLabel(msg.meta) ?? 'You' : (msg.sender_id && msg.sender_id.length > 20 ? title : msg.sender_id);
const replyQuote = isUser ? replyRefOf(msg.reply_to) : null;
@@ -1332,6 +1338,11 @@ export const ChatView: React.FC<ChatViewProps> = ({
</>
) : workAhead ? (
<WorkAheadBody messageId={msg.id} text={text} />
+ ) : emptyTrial ? (
+ <p className="flex items-start gap-2 text-sm leading-5 text-zinc-400" data-empty-trial-reply="">
+ <CircleSlash size={14} aria-hidden="true" className="mt-[3px] shrink-0" />
+ <span>{emptyTrial}</span>
+ </p>
) : (
<MarkdownRenderer content={text} results={msg.results} messageId={msg.id} />
)}
@@ -1782,7 +1793,8 @@ export const ChatView: React.FC<ChatViewProps> = ({
</div>
{/* Suggested prompts for who is in this chat: one swipeable row on phones */}
- {messages.length <= 1 && suggestions.length > 0 && !showHome && (
+ {/* O2 §6: hidden while nothing can run, instead of shown disabled */}
+ {messages.length <= 1 && suggestions.length > 0 && !showHome && canRun !== false && (
<ScrollRow
className="kw-scroll-row px-3 sm:px-6 py-2 flex flex-nowrap sm:flex-wrap items-center gap-2 overflow-x-auto sm:overflow-visible select-none"
role="group"
@@ -1794,9 +1806,7 @@ export const ChatView: React.FC<ChatViewProps> = ({
key={prompt}
type="button"
onClick={() => handlePromptSuggestion(prompt)}
- disabled={canRun === false}
- title={canRun === false ? 'Add an account first' : undefined}
- className="shrink-0 whitespace-nowrap px-2.5 py-1 rounded-full text-xs text-zinc-400 bg-zinc-900 border border-zinc-800 hover:border-zinc-700 hover:text-zinc-200 transition-all shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:border-zinc-800 disabled:hover:text-zinc-400"
+ className="shrink-0 whitespace-nowrap px-2.5 py-1 rounded-full text-xs text-zinc-400 bg-zinc-900 border border-zinc-800 hover:border-zinc-700 hover:text-zinc-200 transition-all shadow-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"
>
{prompt}
</button>
diff --git a/frontend/src/components/GetStarted.tsx b/frontend/src/components/GetStarted.tsx
new file mode 100644
index 00000000..5aee52b9
--- /dev/null
+++ b/frontend/src/components/GetStarted.tsx
@@ -0,0 +1,1103 @@
+// O2 (0.7.6): the "Get started" card in #general. One card, three steps: Choose your AI → Sign in →
+// Pick a team. Design: next-076/onboarding/design.md §3–§13 (Mira), C1–C6 accepted by Ada.
+// The step logic is in ../gettingStarted.ts and the install in ../gettingStartedInstall.ts; this file
+// only draws them. Text comes from code, never from data as HTML.
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { AlertCircle, Check, Clock, Copy, ExternalLink, Info, KeyRound, RotateCw, Server, WifiOff } from 'lucide-react';
+import { ModernAvatar } from './ModernAvatar';
+import { TemplateGlyph } from './TeamPreviewSheet';
+import { NewKeyAccountForm } from './EngineAccounts';
+import { useReadyTeams } from './ReadyTeams';
+import type { WelcomeBot } from './FirstRunWelcome';
+import { useMedia } from '../useMedia';
+import { PHONE_QUERY } from '../layout';
+import { inDesktopApp, leaveForSignIn } from '../externalLinks';
+import { plural } from '../teams/teamTemplates';
+import type { EngineInfo } from '../engines';
+import { type SetupItem, setupApi } from '../setupInstall';
+import {
+ type AiChoice,
+ type LoginApi,
+ type LoginEngine,
+ type LoginSession,
+ type Phase,
+ type StepsView,
+ CHOICES,
+ LoginError,
+ bannerView,
+ choiceName,
+ cleanPastedCode,
+ cliName,
+ codeAriaLabel,
+ deviceLabel,
+ dismiss,
+ heroText,
+ installFailView,
+ installable,
+ isKept,
+ isLive,
+ isSignInUrl,
+ loginApi as defaultLoginApi,
+ markStarted,
+ minutesLeft,
+ needsInstall,
+ noDeviceRoute,
+ signInEnd,
+ startOrResume,
+ step1Value,
+ stepsView,
+ storeChoice,
+ storedChoice,
+ tileStatus,
+ whereLabel,
+} from '../gettingStarted';
+import { type InstallTrack, forgetInstall, installDetails, startInstall, useInstallTrack, useStartVersion } from '../gettingStartedInstall';
+
+const FOCUS = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+const SLOW_S = 40;
+const KEY_PROVIDERS = [
+ { card: 'anthropic_api', label: 'Anthropic', note: 'Paid per use on your Anthropic account.' },
+ { card: 'openai_api', label: 'OpenAI', note: 'Paid per use on your OpenAI account.' },
+ { card: 'xai_api', label: 'xAI', note: 'Paid per use on your xAI account.' },
+] as const;
+
+/** Where kwant runs, for "on {host}" (§10): the address the page was opened on, unless it's this computer. */
+export function hostOf(w: { location?: { hostname?: string } } | undefined = typeof window !== 'undefined' ? window : undefined): string | null {
+ if (!w || inDesktopApp(w)) return null;
+ const h = w.location?.hostname || '';
+ if (!h || h === 'localhost' || h === '127.0.0.1' || h === '::1' || h === '[::1]') return null;
+ return h;
+}
+const isMac = () => typeof navigator !== 'undefined' && /Mac/i.test(navigator.platform || navigator.userAgent || '');
+
+async function copyText(text: string): Promise<boolean> {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/** Counts seconds since `from` while `on`; the number is only shown, never announced. */
+function useSeconds(from: number | null, on: boolean) {
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ if (!on) return;
+ setNow(Date.now());
+ const t = window.setInterval(() => setNow(Date.now()), 1000);
+ return () => window.clearInterval(t);
+ }, [on, from]);
+ return from === null ? 0 : Math.max(0, Math.floor((now - from) / 1000));
+}
+
+// ------------------------------------------------------------------ small parts
+
+const Spinner: React.FC = () => (
+ <span
+ aria-hidden="true"
+ className="inline-block w-3.5 h-3.5 shrink-0 rounded-full border-2 border-sky-300/25 border-t-sky-300 animate-spin [animation-duration:.8s] motion-reduce:animate-none"
+ />
+);
+
+const Btn: React.FC<React.ButtonHTMLAttributes<HTMLButtonElement> & { kind?: 'primary' | 'secondary' | 'link'; phone: boolean }> = ({
+ kind = 'secondary',
+ phone,
+ className = '',
+ ...rest
+}) => {
+ const base =
+ kind === 'primary'
+ ? `${phone ? 'h-11' : 'h-9'} px-3.5 rounded-lg bg-accent-gradient text-[13px] font-semibold text-white disabled:opacity-45 disabled:cursor-not-allowed`
+ : kind === 'secondary'
+ ? `${phone ? 'h-11' : 'h-9'} px-3 rounded-lg border border-white/[.14] bg-white/[.04] text-xs text-zinc-200 hover:bg-white/[.08]`
+ : `${phone ? 'min-h-11' : 'min-h-8'} px-1 text-xs text-sky-300 hover:text-sky-200`;
+ return <button type="button" {...rest} className={`inline-flex items-center justify-center gap-1.5 ${base} ${FOCUS} ${className}`} />;
+};
+
+/** One failure row (§9): icon, text, reason, then actions lined up with the text. */
+const FailRow: React.FC<{
+ tone: 'warn' | 'bad' | 'neutral';
+ icon: 'wifi' | 'alert' | 'info' | 'clock';
+ title: string;
+ reason?: string | null;
+ children?: React.ReactNode;
+}> = ({ tone, icon, title, reason, children }) => {
+ const Icon = icon === 'wifi' ? WifiOff : icon === 'alert' ? AlertCircle : icon === 'clock' ? Clock : Info;
+ const color = tone === 'bad' ? 'text-bad' : tone === 'warn' ? 'text-warn' : 'text-zinc-400';
+ return (
+ <div data-fail-row={tone} role={tone === 'neutral' ? 'status' : 'alert'}>
+ <div className="flex items-start gap-2">
+ <Icon size={15} className={`mt-0.5 shrink-0 ${color}`} aria-hidden="true" />
+ <div className="min-w-0">
+ <p className="text-[13px] text-zinc-200">{title}</p>
+ {reason ? <p className="text-xs text-zinc-400 mt-0.5 break-words">{reason}</p> : null}
+ </div>
+ </div>
+ {children ? <div className="pl-[23px] mt-2 flex flex-wrap items-center gap-2">{children}</div> : null}
+ </div>
+ );
+};
+
+// ------------------------------------------------------------------ step 1: the tiles
+
+const Tiles: React.FC<{
+ engines: EngineInfo[] | null;
+ picked: AiChoice | null;
+ where: string;
+ phone: boolean;
+ onPick: (c: AiChoice) => void;
+}> = ({ engines, picked, where, phone, onPick }) => {
+ const refs = useRef<Array<HTMLButtonElement | null>>([]);
+ const current = picked ? CHOICES.findIndex((c) => c.id === picked) : -1;
+ const onKey = (e: React.KeyboardEvent, i: number) => {
+ const n = CHOICES.length;
+ const go = (j: number) => {
+ e.preventDefault();
+ refs.current[(j + n) % n]?.focus();
+ };
+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') go(i + 1);
+ else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') go(i - 1);
+ else if (e.key === 'Home') go(0);
+ else if (e.key === 'End') go(n - 1);
+ };
+ return (
+ <div role="radiogroup" aria-label="Choose your AI" className={`grid gap-2 ${phone ? 'grid-cols-2' : 'grid-cols-4'}`} data-ai-tiles>
+ {CHOICES.map((c, i) => {
+ const st = tileStatus(engines, c.id);
+ const on = picked === c.id;
+ return (
+ <button
+ key={c.id}
+ ref={(el) => (refs.current[i] = el)}
+ type="button"
+ role="radio"
+ aria-checked={on}
+ tabIndex={current === -1 ? (i === 0 ? 0 : -1) : current === i ? 0 : -1}
+ data-ai-tile={c.id}
+ onClick={() => onPick(c.id)}
+ onKeyDown={(e) => onKey(e, i)}
+ className={`flex flex-col items-start gap-0.5 rounded-[10px] border px-3 py-2.5 text-left transition-colors motion-reduce:transition-none ${phone ? 'min-h-[76px]' : 'min-h-[72px]'} ${
+ on
+ ? 'border-sky-400/70 bg-sky-500/10'
+ : st === 'signed_in'
+ ? 'border-emerald-400/45 bg-zinc-900/80 hover:bg-zinc-800/80'
+ : 'border-zinc-700 bg-zinc-900/80 hover:border-zinc-600 hover:bg-zinc-800/80'
+ } ${FOCUS}`}
+ >
+ <span className="flex items-center gap-1.5 text-sm font-semibold text-zinc-100">
+ {c.id === 'key' ? <KeyRound size={13} className="text-zinc-400" aria-hidden="true" /> : null}
+ {c.name}
+ </span>
+ <span className="text-xs text-zinc-400">{c.line}</span>
+ {st === 'signed_in' ? (
+ <span className="text-[11px] text-ok inline-flex items-center gap-1">
+ <Check size={11} aria-hidden="true" />
+ Signed in {where}
+ </span>
+ ) : st === 'installed' ? (
+ <span className="text-[11px] text-zinc-300">Installed · sign in next</span>
+ ) : null}
+ </button>
+ );
+ })}
+ </div>
+ );
+};
+
+// ------------------------------------------------------------------ step 2: getting it ready
+
+const InstallPanel: React.FC<{
+ track: InstallTrack;
+ name: string;
+ host: string | null;
+ where: string;
+ phone: boolean;
+ onRetry: () => void;
+ onOther: () => void;
+}> = ({ track, name, host, where, phone, onRetry, onOther }) => {
+ const running = track.state === 'running';
+ const s = useSeconds(track.startedAt, running);
+ const [copied, setCopied] = useState<string | null>(null);
+ const copy = async (what: string, text: string) => {
+ if (await copyText(text)) {
+ setCopied(what);
+ window.setTimeout(() => setCopied(null), 2000);
+ }
+ };
+ // F1: tries again by itself when the browser is back online, and every 15 s.
+ const offline = track.state === 'failed' && track.kind === 'offline';
+ useEffect(() => {
+ if (!offline) return;
+ const again = () => onRetry();
+ window.addEventListener('online', again);
+ const t = window.setInterval(again, 15000);
+ return () => {
+ window.removeEventListener('online', again);
+ window.clearInterval(t);
+ };
+ }, [offline, onRetry]);
+
+ if (running) {
+ const slow = s >= SLOW_S;
+ const on = host ? ` on ${host}` : '';
+ return (
+ <div data-install-line>
+ <div className="flex items-center gap-2">
+ <Spinner />
+ <p className="text-[13px] text-zinc-200">
+ <span role="status" aria-live="polite">
+ {slow ? 'Still getting' : 'Getting'} {name} ready{on}
+ </span>
+ <span aria-hidden="true">
+ … <span className="tabular-nums text-zinc-500">{s} s</span>
+ </span>
+ </p>
+ </div>
+ <p className="text-xs text-zinc-400 mt-1 pl-[22px]">
+ {slow ? 'A slow connection can take a minute or two. You can pick a team meanwhile.' : `Next you sign in with your ${name} account.`}
+ </p>
+ </div>
+ );
+ }
+ if (track.state === 'needs_admin') {
+ return (
+ <FailRow tone="warn" icon="info" title={`One step needs an admin ${host ? `on ${host}` : where}.`} reason="Run this once as an admin. kwant notices when it’s done.">
+ <div className="w-full">
+ {track.manual.map((m) => (
+ <div key={m.command} className="flex items-center gap-2 mb-2">
+ <code className="flex-1 min-w-0 overflow-x-auto whitespace-pre rounded-lg border border-zinc-700 bg-zinc-950/70 px-3 py-2 font-mono text-xs text-zinc-100" aria-label={m.label || 'Command'}>
+ {m.command}
+ </code>
+ <Btn phone={phone} onClick={() => copy(m.command, m.command)} aria-label="Copy the command">
+ {copied === m.command ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}
+ {copied === m.command ? 'Copied' : 'Copy'}
+ </Btn>
+ </div>
+ ))}
+ <p className="text-xs text-zinc-400 inline-flex items-center gap-2" role="status">
+ <Spinner />
+ Checking every few seconds…
+ </p>
+ </div>
+ </FailRow>
+ );
+ }
+ if (track.state === 'failed') {
+ const kind = track.kind ?? 'other';
+ const v = installFailView(kind, name, where, host);
+ if (kind === 'offline')
+ return (
+ <FailRow tone="warn" icon="wifi" title={v.title} reason={v.reason}>
+ <Btn phone={phone} onClick={onRetry}>
+ Try now
+ </Btn>
+ </FailRow>
+ );
+ const big = kind === 'disk' || kind === 'permission';
+ return (
+ <FailRow tone="bad" icon="alert" title={v.title} reason={v.reason}>
+ <Btn phone={phone} kind="primary" onClick={onRetry}>
+ <RotateCw size={13} aria-hidden="true" />
+ Try again
+ </Btn>
+ <Btn phone={phone} onClick={() => copy('details', installDetails(track))}>
+ {copied === 'details' ? 'Copied' : 'Copy details'}
+ </Btn>
+ {!big ? (
+ <Btn phone={phone} kind="link" onClick={onOther}>
+ Choose another AI
+ </Btn>
+ ) : null}
+ </FailRow>
+ );
+ }
+ return null;
+};
+
+/** The O1 install route can't do this one here (e.g. Codex without its standalone build, §11). */
+const CantInstall: React.FC<{ engine: EngineInfo | undefined; name: string; choice: LoginEngine }> = ({ engine, name, choice }) => (
+ <p className="text-[13px] text-zinc-300" data-cant-install>
+ {choice === 'codex' ? 'Needs Node.js first. ' : ''}
+ {engine?.detail || `Install ${name} on this computer.`} This step moves on by itself once it’s there.
+ </p>
+);
+
+// ------------------------------------------------------------------ step 2: sign in
+
+/** Claude: open claude.ai, then paste the code (§5.3). Always the paste flow (D5 unverified). */
+const ClaudePaste: React.FC<{ api: LoginApi; phone: boolean; onDone: () => void; onOther: () => void }> = ({ api, phone, onDone, onOther }) => {
+ const [s, setS] = useState<LoginSession | null>(null);
+ const [opened, setOpened] = useState(false);
+ const [code, setCode] = useState('');
+ const [bad, setBad] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const field = useRef<HTMLInputElement>(null);
+ const tab = useRef<Window | null>(null);
+ const fieldId = useId();
+ const sid = s?.session_id;
+ const live = !!s && isLive(s.state);
+
+ useEffect(() => {
+ if (!sid || !live) return;
+ const t = window.setInterval(async () => {
+ try {
+ const next = await api.get('claude', sid);
+ setS(next);
+ if (next.state === 'done') onDone();
+ } catch (e) {
+ if (e instanceof LoginError && e.status === 404) setS((p) => (p ? { ...p, state: 'expired' } : p));
+ }
+ }, 2000);
+ return () => window.clearInterval(t);
+ }, [api, sid, live, onDone]);
+
+ const go = (url: string) => {
+ const t = tab.current;
+ tab.current = null;
+ if (inDesktopApp()) leaveForSignIn(url);
+ else if (t && !t.closed) t.location.replace(url);
+ else window.open(url, '_blank', 'noopener,noreferrer');
+ };
+
+ const open = async () => {
+ setError(null);
+ if (s && isLive(s.state) && isSignInUrl('claude', s.url)) {
+ go(s.url);
+ setOpened(true);
+ return;
+ }
+ if (!inDesktopApp()) {
+ try {
+ const t = window.open('about:blank', '_blank');
+ if (t) t.opener = null;
+ tab.current = t;
+ } catch {
+ tab.current = null;
+ }
+ }
+ try {
+ let next = await startOrResume(api, 'claude');
+ for (let i = 0; i < 20 && next.state === 'starting' && !next.url; i++) {
+ await new Promise((r) => setTimeout(r, 500));
+ next = await api.get('claude', next.session_id);
+ }
+ setS(next);
+ if (isSignInUrl('claude', next.url)) {
+ go(next.url);
+ setOpened(true);
+ } else {
+ tab.current?.close();
+ setError(next.detail || 'Couldn’t get a sign-in link from Claude.');
+ }
+ } catch (e) {
+ tab.current?.close();
+ setError(e instanceof Error ? e.message : 'Sign-in didn’t start.');
+ }
+ };
+
+ const submit = async (e?: React.FormEvent) => {
+ e?.preventDefault();
+ const c = cleanPastedCode(code);
+ if (!c || !sid) return;
+ setBad(false);
+ try {
+ const next = await api.submitCode('claude', sid, c);
+ setS(next);
+ if (next.state === 'done') onDone();
+ else if (next.state === 'failed') {
+ setBad(true);
+ field.current?.focus();
+ }
+ } catch {
+ setBad(true);
+ field.current?.focus();
+ }
+ };
+
+ const paste = async () => {
+ try {
+ const t = await navigator.clipboard.readText();
+ if (t) setCode(cleanPastedCode(t));
+ } catch {
+ /* the browser said no; the field still takes a long-press paste */
+ }
+ };
+
+ const end = s && !isLive(s.state) && s.state !== 'done' && !(s.state === 'failed' && bad) ? signInEnd(s, 'claude') : null;
+ if (end)
+ return (
+ <FailRow tone={end.tone} icon={end.kind === 'expired' ? 'clock' : end.tone === 'bad' ? 'alert' : 'info'} title={end.title} reason={end.reason}>
+ <Btn
+ phone={phone}
+ kind="primary"
+ onClick={() => {
+ setS(null);
+ setOpened(false);
+ setCode('');
+ }}
+ >
+ {end.action}
+ </Btn>
+ <Btn phone={phone} kind="link" onClick={onOther}>
+ Choose another AI
+ </Btn>
+ </FailRow>
+ );
+
+ const dot = (n: number, done: boolean) => (
+ <span aria-hidden="true" className={`mt-0.5 w-[18px] h-[18px] shrink-0 rounded-full text-[11px] font-semibold flex items-center justify-center ${done ? 'bg-zinc-800 text-ok' : 'border border-zinc-600 text-zinc-300'}`}>
+ {done ? <Check size={11} /> : n}
+ </span>
+ );
+ return (
+ <ol className="flex flex-col gap-3" data-claude-paste>
+ <li className="flex items-start gap-2.5">
+ {dot(1, opened)}
+ <div className="min-w-0 flex-1">
+ <p className="text-[13px] text-zinc-200">Open claude.ai and allow kwant bots.</p>
+ <div className="mt-2">
+ <Btn phone={phone} kind={opened ? 'secondary' : 'primary'} onClick={open} data-open-claude>
+ {opened ? 'Open again' : 'Open claude.ai'}
+ <ExternalLink size={12} aria-hidden="true" />
+ </Btn>
+ </div>
+ {error ? (
+ <p className="text-xs text-bad mt-1.5" role="alert">
+ {error}
+ </p>
+ ) : null}
+ </div>
+ </li>
+ <li className="flex items-start gap-2.5">
+ {dot(2, false)}
+ <form className="min-w-0 flex-1" onSubmit={submit}>
+ <label htmlFor={fieldId} className="text-[13px] text-zinc-200">
+ Paste the code claude.ai shows you.
+ </label>
+ <div className="mt-2 flex items-center gap-2">
+ <input
+ ref={field}
+ id={fieldId}
+ value={code}
+ onChange={(e) => {
+ setCode(e.target.value);
+ setBad(false);
+ }}
+ onPaste={(e) => {
+ const t = e.clipboardData.getData('text');
+ if (t) {
+ e.preventDefault();
+ setCode(cleanPastedCode(t));
+ setBad(false);
+ }
+ }}
+ placeholder="Paste the code"
+ autoComplete="off"
+ spellCheck={false}
+ aria-invalid={bad || undefined}
+ aria-describedby={bad ? `${fieldId}-err` : undefined}
+ className={`flex-1 min-w-0 rounded-lg border bg-zinc-950/70 px-3 font-mono text-zinc-100 placeholder:text-zinc-500 ${phone ? 'h-11 text-base' : 'h-9 text-[13px]'} ${
+ bad ? 'border-rose-400/70' : 'border-zinc-700'
+ } ${FOCUS}`}
+ />
+ {phone && typeof navigator !== 'undefined' && typeof navigator.clipboard?.readText === 'function' ? (
+ <Btn phone={phone} onClick={paste}>
+ Paste
+ </Btn>
+ ) : null}
+ <Btn phone={phone} kind="primary" type="submit" disabled={!code.trim() || !sid || s?.state === 'verifying'}>
+ Sign in
+ </Btn>
+ </div>
+ {bad ? (
+ <p id={`${fieldId}-err`} className="text-xs text-bad mt-1.5" role="alert">
+ That code didn’t work. Copy the whole code from claude.ai and paste it again.
+ </p>
+ ) : null}
+ </form>
+ </li>
+ </ol>
+ );
+};
+
+/** ChatGPT and Grok: the device code (§5.4). Falls back to the Terminal line when O3 isn't on this server. */
+const DevicePanel: React.FC<{
+ api: LoginApi;
+ engine: 'codex' | 'grok';
+ phone: boolean;
+ onDone: () => void;
+ onOther: () => void;
+ onNoRoute: () => void;
+}> = ({ api, engine, phone, onDone, onOther, onNoRoute }) => {
+ const [s, setS] = useState<LoginSession | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [copied, setCopied] = useState(false);
+ const [round, setRound] = useState(0);
+ const sid = s?.session_id;
+ const live = !!s && isLive(s.state);
+ const name = cliName(engine);
+ const noRouteRef = useRef(onNoRoute);
+ noRouteRef.current = onNoRoute;
+ const doneRef = useRef(onDone);
+ doneRef.current = onDone;
+
+ // One sign-in per round (Start again / Get a new code start the next); never one per render.
+ useEffect(() => {
+ let off = false;
+ setError(null);
+ startOrResume(api, engine)
+ .then((x) => !off && setS(x))
+ .catch((e) => {
+ if (off) return;
+ if (noDeviceRoute(e)) noRouteRef.current();
+ else setError(e instanceof Error ? e.message : 'Sign-in didn’t start.');
+ });
+ return () => {
+ off = true;
+ };
+ }, [api, engine, round]);
+
+ useEffect(() => {
+ if (!sid || !live) return;
+ const t = window.setInterval(async () => {
+ try {
+ const next = await api.get(engine, sid);
+ setS(next);
+ if (next.state === 'done') doneRef.current();
+ } catch (e) {
+ if (e instanceof LoginError && e.status === 404) setS((p) => (p ? { ...p, state: 'expired' } : p));
+ }
+ }, 1500);
+ return () => window.clearInterval(t);
+ }, [api, engine, sid, live]);
+
+ const cancel = async () => {
+ if (!sid) return;
+ try {
+ await api.cancel(engine, sid);
+ } catch {
+ /* it ends by itself */
+ }
+ setS((p) => (p ? { ...p, state: 'cancelled' } : p));
+ };
+
+ const copyCode = async () => {
+ if (!s?.user_code) return false;
+ const ok = await copyText(s.user_code);
+ if (ok) {
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 2000);
+ }
+ return ok;
+ };
+
+ // C6: copies the code first, then opens the page.
+ const open = async () => {
+ if (!s || !isSignInUrl(engine, s.url)) return;
+ const url = s.url;
+ await copyCode();
+ if (inDesktopApp()) leaveForSignIn(url);
+ else window.open(url, '_blank', 'noopener,noreferrer');
+ };
+
+ if (error)
+ return (
+ <FailRow tone="bad" icon="alert" title="Sign-in didn’t start." reason={error}>
+ <Btn phone={phone} kind="primary" onClick={() => setRound((r) => r + 1)}>
+ Try again
+ </Btn>
+ <Btn phone={phone} kind="link" onClick={onOther}>
+ Choose another AI
+ </Btn>
+ </FailRow>
+ );
+
+ const end = s ? signInEnd(s, engine) : null;
+ if (end)
+ return (
+ <FailRow tone={end.tone} icon={end.kind === 'expired' ? 'clock' : end.tone === 'bad' ? 'alert' : 'info'} title={end.title} reason={end.kind === 'failed' && s?.detail ? `${name} said: “${s.detail}”` : end.reason}>
+ <Btn
+ phone={phone}
+ kind="primary"
+ onClick={() => {
+ setS(null);
+ setRound((r) => r + 1);
+ }}
+ >
+ {end.kind === 'failed' ? 'Sign in with another account' : end.action}
+ </Btn>
+ <Btn phone={phone} kind="link" onClick={onOther}>
+ Choose another AI
+ </Btn>
+ </FailRow>
+ );
+
+ const label = deviceLabel(s?.url);
+ if (!s || !s.user_code || !label)
+ return (
+ <p className="text-[13px] text-zinc-300 inline-flex items-center gap-2" role="status">
+ <Spinner />
+ Getting a sign-in code from {name}…
+ </p>
+ );
+ const mins = minutesLeft(s.expires_at, Date.now());
+ const site = label.split('/')[0];
+ return (
+ <div data-device-panel>
+ <p className="text-[13px] text-zinc-200">
+ Open <span className="font-semibold">{label}</span> and enter this code:
+ </p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span
+ aria-label={codeAriaLabel(s.user_code)}
+ data-user-code
+ className={`select-all rounded-[10px] border border-dashed border-zinc-600 bg-zinc-950/70 px-4 py-2 font-mono font-semibold tracking-[.12em] text-zinc-50 ${phone ? 'text-[22px]' : 'text-2xl'}`}
+ >
+ {s.user_code}
+ </span>
+ <Btn phone={phone} onClick={copyCode}>
+ {copied ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}
+ {copied ? 'Copied' : 'Copy'}
+ </Btn>
+ </div>
+ <div className="mt-3 flex flex-wrap items-center gap-x-3 gap-y-1">
+ <Btn phone={phone} kind="primary" onClick={open} data-open-device>
+ Open {label}
+ <ExternalLink size={12} aria-hidden="true" />
+ </Btn>
+ {!phone ? <span className="text-xs text-zinc-400">Copies the code too.</span> : null}
+ </div>
+ <div className="mt-3 flex items-start gap-2">
+ <span className="mt-0.5">
+ <Spinner />
+ </span>
+ <div className="min-w-0">
+ <p className="text-[13px] text-zinc-200" role="status" aria-live="polite">
+ Waiting for you to finish on {site}…
+ </p>
+ <p className="text-xs text-zinc-400">This moves on by itself.{mins !== null ? ` The code works for ${mins} ${mins === 1 ? 'minute' : 'minutes'}.` : ''}</p>
+ </div>
+ </div>
+ <div className="mt-1">
+ <Btn phone={phone} kind="link" onClick={cancel}>
+ Cancel
+ </Btn>
+ </div>
+ </div>
+ );
+};
+
+/** Before O3 (§11): "Run `codex login` in Terminal", with Copy, and the engine list is read again. */
+const TerminalSignIn: React.FC<{ engine: 'codex' | 'grok'; phone: boolean; recheck: () => void }> = ({ engine, phone, recheck }) => {
+ const cmd = `${engine} login`;
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ const t = window.setInterval(recheck, 5000);
+ return () => window.clearInterval(t);
+ }, [recheck]);
+ return (
+ <div data-terminal-signin>
+ <p className="text-[13px] text-zinc-200">Run this in Terminal and sign in with your {engine === 'codex' ? 'ChatGPT' : 'Grok'} account:</p>
+ <div className="mt-2 flex items-center gap-2">
+ <code className="rounded-lg border border-zinc-700 bg-zinc-950/70 px-3 py-2 font-mono text-[13px] text-zinc-100">{cmd}</code>
+ <Btn
+ phone={phone}
+ onClick={async () => {
+ if (await copyText(cmd)) {
+ setCopied(true);
+ window.setTimeout(() => setCopied(false), 2000);
+ }
+ }}
+ >
+ {copied ? 'Copied' : 'Copy'}
+ </Btn>
+ </div>
+ <p className="mt-2 text-xs text-zinc-400 inline-flex items-center gap-2" role="status">
+ <Spinner />
+ This moves on by itself when you’re signed in.
+ </p>
+ </div>
+ );
+};
+
+const KeyPanel: React.FC<{ phone: boolean; onAdded: () => void }> = ({ phone, onAdded }) => {
+ const [card, setCard] = useState<(typeof KEY_PROVIDERS)[number]['card']>('anthropic_api');
+ const p = KEY_PROVIDERS.find((x) => x.card === card)!;
+ return (
+ <div data-key-panel>
+ <div role="radiogroup" aria-label="Key from" className="flex flex-wrap gap-1.5">
+ {KEY_PROVIDERS.map((k) => (
+ <button
+ key={k.card}
+ type="button"
+ role="radio"
+ aria-checked={card === k.card}
+ onClick={() => setCard(k.card)}
+ className={`${phone ? 'h-11' : 'h-[30px]'} px-3 rounded-full border text-xs ${card === k.card ? 'border-sky-400/70 bg-sky-500/10 text-zinc-100' : 'border-zinc-700 text-zinc-300'} ${FOCUS}`}
+ >
+ {k.label}
+ </button>
+ ))}
+ </div>
+ <div className="mt-2">
+ <NewKeyAccountForm key={card} card={card} onCancel={() => undefined} onCreated={onAdded} />
+ </div>
+ <p className="mt-1 text-xs text-zinc-400">{p.note} The key stays on this computer.</p>
+ </div>
+ );
+};
+
+// ------------------------------------------------------------------ step 3: pick a team
+
+const TeamStep: React.FC<{ phone: boolean; onKeep: () => void; onPicked: () => void }> = ({ phone, onKeep, onPicked }) => {
+ const rt = useReadyTeams();
+ const templates = rt?.available ? (rt.templates ?? []) : [];
+ const tile = `w-full rounded-xl border text-left ${phone ? 'min-h-16 p-3' : 'p-3'} ${FOCUS}`;
+ return (
+ <div data-team-step>
+ <p className="text-xs text-zinc-400 mb-2.5">Each team has a lead, helpers and skills for one job. You can add more teams later.</p>
+ <ul className={phone ? 'flex flex-col gap-2' : 'grid grid-cols-2 gap-2'}>
+ {templates.map((t) => (
+ <li key={t.id}>
+ <button
+ type="button"
+ data-template={t.id}
+ onClick={() => rt?.open({ kind: 'template', templateId: t.id }, { onDone: onPicked })}
+ aria-label={`${t.label} team: ${t.card_line} ${plural(t.bots.length, 'bot')}. Preview`}
+ className={`${tile} flex flex-col gap-1.5 border-zinc-700 bg-zinc-900/80 hover:border-sky-300/45`}
+ >
+ <span className="flex items-center gap-2.5">
+ <TemplateGlyph icon={t.icon} box="w-8 h-8 rounded-[9px] border border-sky-300/35 bg-sky-500/10 text-sky-300" />
+ <span className="text-sm font-semibold text-zinc-50">{t.label}</span>
+ </span>
+ <span className="text-[12.5px] leading-[18px] text-zinc-300">{t.card_line}</span>
+ <span className="flex items-center gap-2" aria-hidden="true">
+ <span className="flex -space-x-[5px]">
+ {t.bots.map((b) => (
+ <span key={b.key} className="rounded-full ring-2 ring-zinc-900">
+ <ModernAvatar role={b.avatar_sprite} name={b.name} size={18} />
+ </span>
+ ))}
+ </span>
+ <span className="text-xs text-zinc-400">{plural(t.bots.length, 'bot')}</span>
+ <span className="ml-auto text-xs text-sky-300">Preview ›</span>
+ </span>
+ </button>
+ </li>
+ ))}
+ <li>
+ <button type="button" data-keep-starter onClick={onKeep} className={`${tile} h-full flex flex-col gap-1 border-dashed border-zinc-600 bg-transparent hover:border-zinc-500`}>
+ <span className="text-sm font-semibold text-zinc-100">Keep the starter bots</span>
+ <span className="text-[12.5px] leading-[18px] text-zinc-300">Architect, TechLead and DevOps, in #general.</span>
+ <span className="mt-auto text-right text-xs text-sky-300" aria-hidden="true">
+ Use ›
+ </span>
+ </button>
+ </li>
+ </ul>
+ </div>
+ );
+};
+
+// ------------------------------------------------------------------ the card
+
+export interface GetStartedProps {
+ space: string;
+ bots: WelcomeBot[];
+ engines: EngineInfo[] | null;
+ /** Reads /api/engines again (after an install or a sign-in). */
+ reloadEngines: () => void;
+ /** The card goes for good ("Keep the starter bots" after step 2). */
+ onDismissed: () => void;
+ loginApiOverride?: LoginApi;
+ /** For tests and shots: the address it's opened on. */
+ hostOverride?: string | null;
+}
+
+export const GetStarted: React.FC<GetStartedProps> = ({ space, bots, engines, reloadEngines, onDismissed, loginApiOverride, hostOverride }) => {
+ const api = loginApiOverride ?? defaultLoginApi;
+ const phone = useMedia(PHONE_QUERY);
+ useStartVersion();
+ const track = useInstallTrack(space);
+ const host = hostOverride !== undefined ? hostOverride : hostOf();
+ const mac = !host && isMac();
+ const where = whereLabel({ host, mac });
+ const chosen = storedChoice(space);
+ const [changing, setChanging] = useState(false);
+ const [teamEarly, setTeamEarly] = useState(false);
+ const [noRoute, setNoRoute] = useState<Record<string, boolean>>({});
+ const [items, setItems] = useState<SetupItem[] | null>(null);
+ const [resumed] = useState(() => !!chosen && !(engines && tileStatus(engines, chosen) === 'signed_in'));
+ const v: StepsView = stepsView({ engines, chosen, teamEarly, changing });
+ const kept = isKept(space);
+ const titleId = useId();
+ const stepIds = [useId(), useId(), useId()];
+ const cardRef = useRef<HTMLElement>(null);
+ const hadFocus = useRef(false);
+
+ useEffect(() => markStarted(space), [space]);
+ useEffect(() => {
+ let off = false;
+ setupApi
+ .status()
+ .then((x) => !off && setItems(x))
+ .catch(() => !off && setItems([]));
+ return () => {
+ off = true;
+ };
+ }, [track?.state]);
+
+ const choice = v.choice;
+ const loginEngine: LoginEngine | null = choice && choice !== 'key' ? choice : null;
+ const missing = !!loginEngine && needsInstall(engines, loginEngine);
+ const canAuto = loginEngine ? installable(items, loginEngine) : null;
+
+ const install = useCallback(
+ (c: LoginEngine) => {
+ void startInstall(space, c, { onDone: reloadEngines });
+ },
+ [space, reloadEngines],
+ );
+
+ // F7: a running job picks up where it left off; a lost one starts again (409 is followed).
+ useEffect(() => {
+ if (v.open !== 2 && !(teamEarly && !v.done2)) return;
+ if (!loginEngine || !missing || canAuto !== true) return;
+ if (track && track.item === loginEngine) return;
+ install(loginEngine);
+ }, [v.open, teamEarly, v.done2, loginEngine, missing, canAuto, track, install]);
+
+ // Once the CLI is installed, read the engines again so step 2 moves on to sign-in.
+ useEffect(() => {
+ if (track?.state === 'done') reloadEngines();
+ }, [track?.state, reloadEngines]);
+
+ const pick = (c: AiChoice) => {
+ if (track && track.item !== c) forgetInstall(space);
+ storeChoice(space, c);
+ setChanging(false);
+ setTeamEarly(false);
+ };
+ const other = () => {
+ forgetInstall(space);
+ setChanging(true);
+ };
+ const signedIn = useCallback(() => {
+ reloadEngines();
+ }, [reloadEngines]);
+ const keep = () => {
+ if (v.done2) {
+ dismiss(space);
+ onDismissed();
+ } else markStarted(space, 'kept');
+ };
+
+ // §13: focus doesn't jump unless it was inside the step that closed; then it goes to the new heading.
+ const lastOpen = useRef(v.open);
+ useEffect(() => {
+ if (lastOpen.current === v.open) return;
+ lastOpen.current = v.open;
+ const a = typeof document !== 'undefined' ? document.activeElement : null;
+ if (hadFocus.current && (!a || a === document.body)) document.getElementById(stepIds[v.open - 1])?.focus();
+ });
+
+ const hero = heroText(v, { host, mac });
+ const name = choice ? choiceName(choice) : '';
+ const stepTitle2 = choice === 'key' ? 'Add your key' : 'Sign in';
+ const slow = !!track && track.state === 'running' && Date.now() - track.startedAt >= SLOW_S * 1000;
+ const done3 = kept;
+ const row = phone ? 'px-3.5 py-3' : 'px-[18px] py-3.5';
+ const body = phone ? 'pt-2.5' : 'pl-[33px] pt-2.5';
+ const engineOf = (id: string) => engines?.find((e) => e.id === id);
+
+ const step2Body = (() => {
+ if (!choice) return null;
+ if (choice === 'key') return <KeyPanel phone={phone} onAdded={signedIn} />;
+ const le = choice;
+ if (track && track.item === le && track.state !== 'done')
+ return <InstallPanel track={track} name={cliName(le)} host={host} where={where} phone={phone} onRetry={() => install(le)} onOther={other} />;
+ if (missing) {
+ if (canAuto === false) return <CantInstall engine={engineOf(le)} name={cliName(le)} choice={le} />;
+ return (
+ <p className="text-[13px] text-zinc-300 inline-flex items-center gap-2" role="status">
+ <Spinner />
+ Getting {cliName(le)} ready…
+ </p>
+ );
+ }
+ if (le === 'claude') return <ClaudePaste api={api} phone={phone} onDone={signedIn} onOther={other} />;
+ if (noRoute[le]) return <TerminalSignIn engine={le} phone={phone} recheck={reloadEngines} />;
+ return <DevicePanel key={le} api={api} engine={le} phone={phone} onDone={signedIn} onOther={other} onNoRoute={() => setNoRoute((m) => ({ ...m, [le]: true }))} />;
+ })();
+
+ const head = (n: 1 | 2 | 3, title: string, state: 'open' | 'todo' | 'done', value?: string, extra?: React.ReactNode) => {
+ const said = state === 'open' ? (n === 2 && track?.state === 'running' ? 'in progress' : 'open') : state === 'done' ? 'done' : 'to do';
+ return (
+ <div className="flex items-center gap-[11px] min-h-6">
+ <span
+ aria-hidden="true"
+ className={`w-[22px] h-[22px] shrink-0 rounded-full text-xs font-semibold flex items-center justify-center ${
+ state === 'open' ? 'bg-sky-300 text-zinc-950' : state === 'done' ? 'bg-zinc-800 border border-zinc-700 text-ok' : 'border border-zinc-600 text-zinc-300'
+ }`}
+ >
+ {state === 'done' ? <Check size={12} /> : n}
+ </span>
+ <h3 id={stepIds[n - 1]} tabIndex={-1} className={`min-w-0 text-sm ${state === 'open' ? 'font-semibold text-zinc-100' : state === 'done' ? 'font-medium text-zinc-200' : 'font-medium text-zinc-400'} focus:outline-none`}>
+ <span className="sr-only">{`Step ${n} of 3, `}</span>
+ {title}
+ <span className="sr-only">{`, ${said}`}</span>
+ {value ? <span className="ml-2 text-xs font-normal text-zinc-400">{value}</span> : null}
+ </h3>
+ {extra}
+ </div>
+ );
+ };
+
+ return (
+ <section
+ ref={cardRef}
+ aria-labelledby={titleId}
+ data-get-started
+ data-open-step={v.open}
+ onFocus={() => (hadFocus.current = true)}
+ onBlur={(e) => {
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null) && e.relatedTarget) hadFocus.current = false;
+ }}
+ className={`w-full max-w-[640px] mx-auto ${phone ? 'px-3.5 pt-6' : 'pt-6 sm:pt-16'} pb-6`}
+ >
+ <div className="flex flex-col items-center text-center">
+ {bots.length ? (
+ <div className="flex -space-x-2" aria-hidden="true">
+ {bots.slice(0, 5).map((b) => (
+ <span key={b.id} className="rounded-full ring-4 ring-zinc-950">
+ <ModernAvatar role={b.avatar_sprite} name={b.name} size={44} />
+ </span>
+ ))}
+ </div>
+ ) : null}
+ <h2 id={titleId} className="mt-4 text-[17px] leading-6 font-semibold text-zinc-100">
+ {hero.title}
+ </h2>
+ <p className="mt-1 text-sm text-zinc-400">{hero.sub}</p>
+ {host ? (
+ <span className="mt-3 inline-flex items-center gap-1.5 h-7 px-3 rounded-full border border-white/[.14] bg-white/[.04] text-xs text-zinc-200" data-host-chip>
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400" aria-hidden="true" />
+ <Server size={12} className="text-zinc-400" aria-hidden="true" />
+ Setting up on {host}
+ </span>
+ ) : null}
+ </div>
+
+ {resumed && !v.done2 ? (
+ <p className="mt-4 text-xs text-zinc-400 inline-flex items-center gap-1.5" data-resumed>
+ <RotateCw size={12} aria-hidden="true" />
+ Picking up where you left off.
+ </p>
+ ) : null}
+
+ <div className={`${resumed && !v.done2 ? 'mt-2' : 'mt-5'} rounded-xl border border-zinc-700/60 bg-zinc-900/60 shadow-raised text-left`}>
+ <div className={row} data-step="1">
+ {head(
+ 1,
+ 'Choose your AI',
+ v.open === 1 ? 'open' : v.done1 ? 'done' : 'todo',
+ v.open !== 1 && v.done1 ? step1Value(v, engines, where) : undefined,
+ v.open !== 1 && v.done1 ? (
+ <Btn phone={phone} kind="link" className="ml-auto shrink-0" onClick={() => setChanging(true)} aria-label="Change your AI">
+ Change
+ </Btn>
+ ) : undefined,
+ )}
+ {v.open === 1 ? (
+ <div className={`${body} gs-open`}>
+ <p className="text-xs text-zinc-400 mb-2.5">{host ? `Tap one. It gets ready on ${host} by itself.` : 'Tap one. It gets ready by itself: no Terminal, no password for this computer.'}</p>
+ <Tiles engines={engines} picked={changing ? chosen : null} where={where} phone={phone} onPick={pick} />
+ </div>
+ ) : null}
+ </div>
+ <div className={`${row} border-t border-white/[.07]`} data-step="2">
+ {head(
+ 2,
+ stepTitle2,
+ v.open === 2 ? 'open' : v.done2 ? 'done' : teamEarly && v.done1 ? 'open' : 'todo',
+ v.done2 && v.open !== 1 ? (v.foundReady ? 'Nothing to do' : `${name}, signed in`) : undefined,
+ teamEarly && !v.done2 ? (
+ <Btn phone={phone} kind="link" className="ml-auto shrink-0" onClick={() => setTeamEarly(false)}>
+ Open
+ </Btn>
+ ) : undefined,
+ )}
+ {v.open === 2 ? <div className={`${body} gs-open`}>{step2Body}</div> : null}
+ </div>
+ <div className={`${row} border-t border-white/[.07]`} data-step="3">
+ {head(
+ 3,
+ 'Pick a team',
+ v.open === 3 && !done3 ? 'open' : done3 ? 'done' : 'todo',
+ done3 ? 'Starter bots' : undefined,
+ v.open === 2 && slow && !done3 ? (
+ <Btn phone={phone} kind="link" className="ml-auto shrink-0" onClick={() => setTeamEarly(true)}>
+ Open
+ </Btn>
+ ) : undefined,
+ )}
+ {v.open === 3 && !done3 ? (
+ <div className={`${body} gs-open`}>
+ <TeamStep phone={phone} onKeep={keep} onPicked={() => undefined} />
+ </div>
+ ) : null}
+ </div>
+ </div>
+ </section>
+ );
+};
+
+// ------------------------------------------------------------------ the banner outside #general (§7.1)
+
+/** What the banner says now; null once step 2 is done (team choice isn't nagged). */
+export function bannerPhase(engines: EngineInfo[] | null, choice: AiChoice | null, track: InstallTrack | null): Phase | null {
+ const v = stepsView({ engines, chosen: choice });
+ if (v.done2) return null;
+ if (!v.choice) return { kind: 'choose' };
+ if (track && track.item === v.choice) {
+ if (track.state === 'running') return { kind: 'installing', seconds: 0 };
+ if (track.state === 'failed' || track.state === 'needs_admin') return { kind: 'failed' };
+ }
+ return v.choice !== 'key' && needsInstall(engines, v.choice) ? { kind: 'installing', seconds: 0 } : { kind: 'signin' };
+}
+
+export const GetStartedBanner: React.FC<{ space: string; engines: EngineInfo[] | null; onOpen: () => void }> = ({ space, engines, onOpen }) => {
+ const phone = useMedia(PHONE_QUERY);
+ useStartVersion();
+ const track = useInstallTrack(space);
+ const choice = storedChoice(space);
+ const phase = useMemo(() => bannerPhase(engines, choice, track), [engines, choice, track]);
+ const running = phase?.kind === 'installing' && !!track && track.state === 'running';
+ const seconds = useSeconds(track?.startedAt ?? null, running);
+ if (!phase) return null;
+ const view = bannerView(phase.kind === 'installing' ? { kind: 'installing', seconds } : phase, stepsView({ engines, chosen: choice }).choice);
+ if (!view) return null;
+ // The seconds are shown, never announced: the live text stops before them.
+ const [live, tail] = phase.kind === 'installing' ? [view.title.replace(/… \d+ s$/, ''), `… ${seconds} s`] : [view.title, ''];
+ const [liveShort, tailShort] = phase.kind === 'installing' ? [view.short.replace(/… \d+ s$/, ''), `… ${seconds} s`] : [view.short, ''];
+ return (
+ <div role="status" data-setup-banner data-get-started-banner className={`flex items-center gap-3 border-b border-sky-500/20 bg-sky-500/[.06] ${phone ? 'px-3 py-2' : 'px-6 py-2.5'}`}>
+ {view.spinner ? <Spinner /> : null}
+ <div className="min-w-0 flex-1">
+ <p className="text-xs font-medium text-zinc-100 truncate">
+ {phone ? liveShort : live}
+ {tail ? (
+ <span aria-hidden="true" className="tabular-nums">
+ {phone ? tailShort : tail}
+ </span>
+ ) : null}
+ </p>
+ {!phone && view.sub ? <p className="text-[11.5px] text-zinc-400 truncate">{view.sub}</p> : null}
+ </div>
+ <Btn phone={phone} onClick={onOpen} className={phone ? '' : '!h-8'}>
+ {view.button}
+ </Btn>
+ </div>
+ );
+};
diff --git a/frontend/src/components/MarkdownRenderer.tsx b/frontend/src/components/MarkdownRenderer.tsx
index 9b80a336..fc31743f 100644
--- a/frontend/src/components/MarkdownRenderer.tsx
+++ b/frontend/src/components/MarkdownRenderer.tsx
@@ -3,10 +3,11 @@ import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import { Copy, Check, Terminal } from 'lucide-react';
import { playSfx } from '../audio/chiptune';
-import { HastNode, blockAt, hastText, rehypeSmartIndex, resultBlocks } from '../smartResults';
+import { HastNode, blockAt, hastText, rehypeSmartIndex, rehypeSmartSection, resultBlocks, sectionBlock } from '../smartResults';
import type { ReplyPart, ReplySource } from './results/registry';
import { SmartResult } from './results/SmartResult';
import { ReplyText } from './results/ReplyText';
+import { inlineCodeClass, linkClass } from './markdownInline';
interface CodeBlockProps {
language?: string;
@@ -164,6 +165,8 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
// Never while streaming: the block appears when the final message arrives.
const smart = !isStreaming && !!messageId && resultBlocks(results).length > 0;
const slot = smart ? blockAt(results, { kind: 'slot' }) : null;
+ // A recipe stands for a stretch of the reply: rehypeSmartSection cuts it out and leaves a placeholder.
+ const section = smart ? sectionBlock(results) : null;
const listView = (node: HastNode | undefined, children: React.ReactNode, plain: React.ReactElement) => {
if (!smart || !node || node.data?.smartTop !== true || typeof node.data.smartIndex !== 'number') return plain;
@@ -177,7 +180,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
<div className={`markdown-content text-sm leading-relaxed text-zinc-200 ${className}`}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
- rehypePlugins={smart ? [rehypeSmartIndex as never] : undefined}
+ rehypePlugins={smart ? [rehypeSmartIndex as never, ...(section ? [rehypeSmartSection(content, results) as never] : [])] : undefined}
components={{
// Pre element pass-through to let CodeBlock handle layout
pre: ({ children }) => <>{children}</>,
@@ -201,7 +204,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
return (
<code
- className="px-1.5 py-0.5 rounded-md font-mono text-[12px] bg-zinc-800/80 text-sky-300 border border-zinc-700/50 [overflow-wrap:anywhere] [box-decoration-break:clone] [-webkit-box-decoration-break:clone]"
+ className={inlineCodeClass}
{...props}
>
{children}
@@ -209,6 +212,16 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
);
},
+ // A stretch of the reply that one block stands for (a recipe). Its markdown is the fallback.
+ div: ({ node, children, ...props }) => {
+ const data = (node as HastNode | undefined)?.data;
+ if (!section || data?.smartSection !== true || typeof data.markdown !== 'string') return <div {...props}>{children}</div>;
+ const md = data.markdown;
+ return (
+ <SmartResult raw={section} reply={{ kind: 'section', markdown: md }} messageId={messageId as string} fallback={<MarkdownRenderer content={md} />} />
+ );
+ },
+
// Tables
table: ({ node, children }) => {
const plain = (
@@ -340,7 +353,7 @@ export const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
href={href}
target="_blank"
rel="noopener noreferrer"
- className="text-sky-400 hover:text-sky-300 underline underline-offset-2 transition-colors"
+ className={linkClass}
>
{children}
</a>
diff --git a/frontend/src/components/ReadyTeams.tsx b/frontend/src/components/ReadyTeams.tsx
index 7a63b56b..c70c74a5 100644
--- a/frontend/src/components/ReadyTeams.tsx
+++ b/frontend/src/components/ReadyTeams.tsx
@@ -353,6 +353,7 @@ export const ReadyTeamsProvider: React.FC<ReadyTeamsProviderProps> = ({ space, b
routine={confirm.info.removes.routines > 0}
messages={confirm.info.chat_messages}
teamName={confirm.team.name}
+ archivedChat={confirm.info.archived_chat}
alsoIn={confirm.info.other_teams}
editedSkills={confirm.info.edited_skills}
busy={busy}
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 3c7267ba..317ea556 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -34,6 +34,7 @@ import { signedInDevicesVisible } from '../deviceSignIn';
import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';
import { LayaStatusRow } from './LayaStatus';
import { AppUpdateAbout, useAppUpdate } from './AppUpdateBanner';
+import { WhatsNewAbout } from './WhatsNewSheet';
import { StarAskSettingsLink } from './StarAsk';
import { ProactiveSettings, WORK_AHEAD_CAP_MAX, WORK_AHEAD_CAP_MIN, parseProactiveSettings } from '../decideFirst';
import { IDEA_CAP_DEFAULT, IDEA_CAP_MAX, IDEA_CAP_MIN, ideaCapForSwitch, lastIdeaCap, parseIdeaCap, rememberIdeaCap } from '../ideaShell';
@@ -664,6 +665,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</div>
<AppUpdateAbout />
+ <WhatsNewAbout />
<StarAskSettingsLink />
{computer.state.settings && (
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx
index 0c7b0682..0febc7a8 100644
--- a/frontend/src/components/Sidebar.tsx
+++ b/frontend/src/components/Sidebar.tsx
@@ -1049,10 +1049,8 @@ export const Sidebar: React.FC<SidebarProps> = ({
{readyCount === null
? 'Checking accounts…'
: readyCount === 0
- ? offerClaude
- ? 'No account yet · Sign in with Claude'
- : 'No account yet · Add an account'
- : `Runs on ${runsOn[0]}${runsOn.length > 1 ? ` +${runsOn.length - 1}` : ''}`}
+ ? 'No account yet · Getting started'
+ : `${runsOn[0]} · signed in${runsOn.length > 1 ? ` +${runsOn.length - 1}` : ''}`}
</span>
</button>
</div>
diff --git a/frontend/src/components/TeamNeedsCard.tsx b/frontend/src/components/TeamNeedsCard.tsx
index 816731d6..2d66ec42 100644
--- a/frontend/src/components/TeamNeedsCard.tsx
+++ b/frontend/src/components/TeamNeedsCard.tsx
@@ -279,6 +279,13 @@ export const TeamCreatedToast: React.FC<{ text: string; onUndo?: () => void; onD
// ---------------------------------------------------------------------------------------------------
// T4 confirm (only when the chat has messages)
+/** The chat name for the confirm's archive line, or null for no line (see `archivedChat` below). */
+export const archivedChatLine = (archivedChat: string | null | undefined, messages: number, teamName: string): string | null => {
+ if (archivedChat === null) return null;
+ if (typeof archivedChat === 'string') return archivedChat.trim().replace(/^#+/, '') || null;
+ return messages > 0 ? `archived-team-${teamName}` : null;
+};
+
export const UndoTeamConfirm: React.FC<{
label: string;
handle: string;
@@ -286,8 +293,14 @@ export const UndoTeamConfirm: React.FC<{
skills: number;
routine: boolean;
messages: number;
- /** The team's name: the server renames its chat to #archived-team-<name> (a number added when taken). */
+ /** The team's name: only for a server older than 0.7.6 that doesn't send `archivedChat`. */
teamName: string;
+ /**
+ * The undo preview's `archived_chat` (teams-api.md §6): the exact name the kept chat gets, `-2`… included
+ * when the plain name is taken. null: Undo deletes the chat or leaves it alone, so there's no line.
+ * undefined: an older server; we fall back to #archived-team-<teamName> when the chat has messages.
+ */
+ archivedChat?: string | null;
/** "Drafter is also in @support; it will leave that team." */
alsoIn?: { bot: string; team: string }[];
/** Starter skills the person edited; Undo removes them too (Q-T2). */
@@ -296,7 +309,8 @@ export const UndoTeamConfirm: React.FC<{
error?: string | null;
onKeep: () => void;
onUndo: () => void;
-}> = ({ label, handle, botNames, skills, routine, messages, teamName, alsoIn = [], editedSkills = [], busy, error, onKeep, onUndo }) => {
+}> = ({ label, handle, botNames, skills, routine, messages, teamName, archivedChat, alsoIn = [], editedSkills = [], busy, error, onKeep, onUndo }) => {
+ const archivedAs = archivedChatLine(archivedChat, messages, teamName);
const phone = useMedia(PHONE_QUERY);
const ref = useRef<HTMLDivElement>(null);
const keep = useRef<HTMLButtonElement>(null);
@@ -339,9 +353,11 @@ export const UndoTeamConfirm: React.FC<{
You edited {editedSkills.join(', ')}. {editedSkills.length === 1 ? 'It’s' : 'They’re'} removed too.
</p>
)}
- {messages > 0 && (
- <p className="mt-2">
- The chat has {plural(messages, 'message')}, so it’s kept, not deleted: it moves under Channels as #archived-team-{teamName}.
+ {archivedAs && (
+ <p className="mt-2" data-archived-chat={archivedAs}>
+ {messages > 0 ? `The chat has ${plural(messages, 'message')}, so it’s kept, not deleted` : 'The chat is kept, not deleted'}: it moves under Channels as{' '}
+ {/* One unit: the name wraps onto its own line rather than splitting at a hyphen; a very long one still wraps. */}
+ <span className="inline-block max-w-full [overflow-wrap:anywhere]">#{archivedAs}.</span>
</p>
)}
{error && (
diff --git a/frontend/src/components/TeamPreviewSheet.tsx b/frontend/src/components/TeamPreviewSheet.tsx
index dd3d0fbf..ff55bd3d 100644
--- a/frontend/src/components/TeamPreviewSheet.tsx
+++ b/frontend/src/components/TeamPreviewSheet.tsx
@@ -11,6 +11,7 @@ import {
Code2,
Crown,
FileText,
+ FolderOpen,
Handshake,
Inbox,
Info,
@@ -47,6 +48,7 @@ import {
newBotCount,
botNameByKey,
cantRead,
+ folderInUse,
partialBody,
partialHead,
plural,
@@ -251,6 +253,8 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
const [dPhase, setDPhase] = useState<DPhase>('reading');
/** U-5: the server's `error` when Suggest was refused (bad_path, folder_in_use, …). */
const [readError, setReadError] = useState<string | null>(null);
+ /** N-5: the last read or create was refused with `folder_in_use`, which a retry can't change. */
+ const [inUse, setInUse] = useState(false);
/** U-3: the 422's `forge`, and the GitLab hosts already connected, for which Connect to offer. */
const [cantForge, setCantForge] = useState<unknown>(null);
const [gitlabHosts, setGitlabHosts] = useState<string[]>([]);
@@ -317,6 +321,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
const ac = new AbortController();
readAbort.current = ac;
setDPhase('reading');
+ setInUse(false);
setElapsed(0);
setLive('Reading the project');
if (!navigator.onLine) {
@@ -373,6 +378,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
} else {
const said = serverErrorText(e);
setReadError(said);
+ setInUse(folderInUse(e));
setDPhase('error');
setLive(`Couldn’t read the project. ${said ? `${said} ` : ''}Nothing was created.`);
}
@@ -516,6 +522,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
}
const said = serverErrorText(e);
setCreateError(said);
+ setInUse(folderInUse(e));
setPhase('failed');
setLive(`Couldn’t create the team. ${said ? `${said} ` : ''}Nothing was created.`);
}
@@ -1062,9 +1069,12 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
const nothingNew = manage && dPhase === 'ready' && !!sug && sug.bots.length === 0 && sug.also_possible.length === 0;
const sNote = isD && dPhase === 'ready' && !nothingNew ? sizeNote(ticked, minBots) : null;
const fallbackFooter = isD && (dPhase === 'cantread' || dPhase === 'offline' || dPhase === 'error');
- const retry = (!isD && templatesError && !t) || phase === 'failed' || (isD && (dPhase === 'error' || dPhase === 'offline'));
- const primaryLabel = creating ? 'Creating…' : retry ? 'Try again' : manage ? (nothingNew || ticked === 0 ? 'Add bots' : `Add ${plural(ticked, 'bot')}`) : isD && dPhase === 'reading' ? 'Create team' : `Create team · ${plural(ticked, 'bot')}`;
+ // N-5: the same folder gets the same refusal, so offer another folder instead of "Try again".
+ const pickOther = inUse && !!onPickFolder && mode.kind === 'suggest' && !mode.team && (phase === 'failed' || dPhase === 'error');
+ const retry = !pickOther && ((!isD && templatesError && !t) || phase === 'failed' || (isD && (dPhase === 'error' || dPhase === 'offline')));
+ const primaryLabel = creating ? 'Creating…' : pickOther ? 'Pick another folder' : retry ? 'Try again' : manage ? (nothingNew || ticked === 0 ? 'Add bots' : `Add ${plural(ticked, 'bot')}`) : isD && dPhase === 'reading' ? 'Create team' : `Create team · ${plural(ticked, 'bot')}`;
const onPrimary = () => {
+ if (pickOther) return onPickFolder?.();
if (retry) {
if (!isD && templatesError && !t) return onRetryTemplates?.();
if (isD && dPhase !== 'ready') return void read();
@@ -1073,7 +1083,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
}
void create();
};
- const primaryDisabled = creating || (retry ? (isD && dPhase === 'offline' && !online) || (phase === 'failed' && !online) : !canCreate);
+ const primaryDisabled = creating || (pickOther ? false : retry ? (isD && dPhase === 'offline' && !online) || (phase === 'failed' && !online) : !canCreate);
// Reused bots are left alone by Undo (api.md §6); with none new, say what it does instead of "the 0 new bots".
const footNote = nothingNew
? null
@@ -1169,6 +1179,7 @@ const Sheet: React.FC<TeamPreviewSheetProps> = ({
className={`${btnH} inline-flex items-center justify-center gap-2 px-4 rounded-lg bg-sky-600 hover:bg-sky-500 text-white text-sm font-medium disabled:opacity-50 disabled:hover:bg-sky-600 ${FOCUS}`}
>
{creating && <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}
+ {pickOther && !creating && <FolderOpen size={14} aria-hidden="true" />}
{retry && !creating && <RefreshCw size={14} aria-hidden="true" />}
{primaryLabel}
</button>
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index ddb7c990..9f5ca837 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -16,7 +16,7 @@ import {
Hand,
} from 'lucide-react';
import { playSfx } from '../audio/chiptune';
-import { BOT_BUSY_TEXT, useBrowserStream } from '../useBrowserStream';
+import { BOT_BUSY_TEXT, HELD_BY_PERSON_TEXT, useBrowserStream } from '../useBrowserStream';
import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';
import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';
import { loginMatchesPage } from '../savedPasswords';
@@ -329,6 +329,15 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
}, [waitBot, botBusy, send]);
const waitingForBot = !!waitBot && !waitBot.gaveUp;
+ // The person holds this browser in another window: say so once, never retry. Taking over here
+ // waits for them to press Hand back there and then Take over here, so a browser never moves without a press.
+ const heldElsewhere = stream.error === HELD_BY_PERSON_TEXT && !controlling;
+ useEffect(() => {
+ if (!heldElsewhere) return;
+ setFullScreen(false);
+ setWaitBot(null);
+ }, [heldElsewhere]);
+
// The frame the side pane shows is acknowledged once drawn; one image, its source swapped
const paneFrameId = useRef<number | null>(null);
paneFrameId.current = stream.frame?.id ?? null;
@@ -629,7 +638,23 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
</div>
)}
- {controlError && !botBusy && (
+ {/* The person already has this browser in another window: a static note, no spinner, no retry */}
+ {heldElsewhere && !isControlMode && (
+ <div role="status" aria-live="polite" data-takeover-wait data-takeover-held className="flex items-start gap-2.5 px-3 py-2.5 rounded-xl border border-[rgb(157_143_255/0.35)] bg-[#1a1538]">
+ <Hand size={16} className="shrink-0 mt-0.5 text-[#9d8fff]" aria-hidden="true" />
+ <p className="flex-1 min-w-0 text-[13px] leading-[18px] text-zinc-100">{HELD_BY_PERSON_TEXT}</p>
+ <button
+ type="button"
+ onClick={() => stream.clearError()}
+ aria-label="Close"
+ className="shrink-0 -mr-1 -mt-0.5 w-6 h-6 inline-flex items-center justify-center rounded-md text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06]"
+ >
+ <X size={14} aria-hidden="true" />
+ </button>
+ </div>
+ )}
+
+ {controlError && !botBusy && !heldElsewhere && (
<div role="alert" className="px-2.5 py-2 rounded-lg border border-red-500/30 bg-red-950/40 text-xs text-red-300">
{controlError}
</div>
@@ -798,6 +823,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
{showStage && (
<BrowserTakeoverStage
botName={teamName}
+ othersBrowsing={switching}
pageUrl={pageUrl}
pageTitle={shownTitle}
stream={stream}
diff --git a/frontend/src/components/WhatsNewSheet.tsx b/frontend/src/components/WhatsNewSheet.tsx
new file mode 100644
index 00000000..65ff726f
--- /dev/null
+++ b/frontend/src/components/WhatsNewSheet.tsx
@@ -0,0 +1,401 @@
+// "What's new in kwant X.Y.Z" (spec: next-076/whats-new, design: Mira's whatsnew.html).
+// WhatsNewSheetView draws one version; WhatsNewHost decides when it opens; WhatsNewAbout is the Settings › About card.
+import React, { useEffect, useId, useRef, useState, useSyncExternalStore } from 'react';
+import { ArrowRight, ChevronDown, ChevronLeft, ChevronRight, ExternalLink, List, X } from 'lucide-react';
+import { MarkdownRenderer } from './MarkdownRenderer';
+import { useEscapeLayer } from '../escape';
+import { useMedia } from '../useMedia';
+import { PHONE_QUERY } from '../layout';
+import type { SpaceView } from '../nav';
+import {
+ FIXES_FOLD_OVER,
+ FIXES_SHOWN,
+ RELEASES_URL,
+ type WhatsNewEntry,
+ decideOnLoad,
+ entrySummary,
+ highlightView,
+ markSeen,
+ openRequest,
+ openWhatsNew,
+ otherDialogOpen,
+ releaseUrl,
+ seenVersion,
+ shortDate,
+ subscribeOpen,
+} from '../whatsNewSheet';
+import { WHATS_NEW, changelogFor, latestWhatsNew, whatsNewFor } from '../whatsNewContent';
+
+/** kwant's own pixel bot with a teal hat: the sheet's and the Settings row's mark. */
+const Mark: React.FC<{ size: number }> = ({ size }) => {
+ const r = (x: number, y: number, w = 1, h = 1, f = '#b8adff') => <rect x={x} y={y} width={w} height={h} fill={f} />;
+ const eye = '#120e26';
+ return (
+ <svg viewBox="0 0 10 10" width={size} height={size} aria-hidden="true" shapeRendering="crispEdges">
+ {r(4, 0, 2, 1, '#5eead4')}
+ {r(2, 1, 6, 1)}
+ {r(1, 2, 8, 6)}
+ {r(2, 8, 6, 1)}
+ {r(3, 4, 1, 2, eye)}
+ {r(6, 4, 1, 2, eye)}
+ {r(3, 7, 4, 1, eye)}
+ {r(2, 7, 1, 1, eye)}
+ {r(7, 7, 1, 1, eye)}
+ </svg>
+ );
+};
+
+const focus = 'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-400';
+
+export interface SheetProps {
+ entry: WhatsNewEntry;
+ /** That version's CHANGELOG section; without it there's no "All changes". */
+ changelog: string | null;
+ phone: boolean;
+ /** Opened after an update: "Updated from <from>" (or "Updated" with no earlier version known). Null when opened by hand. */
+ updatedFrom: string | null | undefined;
+ onClose: () => void;
+ /** "Show me": open a place in the app. */
+ onOpen: (view: SpaceView) => void;
+ /** Start on the All changes view (screenshots). */
+ initialPage?: 'main' | 'all';
+}
+
+/** The sheet itself, without deciding when: what tests and screenshots render. */
+export const WhatsNewSheetView: React.FC<SheetProps> = ({ entry, changelog, phone, updatedFrom, onClose, onOpen, initialPage = 'main' }) => {
+ const [page, setPage] = useState<'main' | 'all'>(initialPage === 'all' && changelog ? 'all' : 'main');
+ const [fixesOpen, setFixesOpen] = useState(false);
+ const rootRef = useRef<HTMLDivElement>(null);
+ const titleRef = useRef<HTMLHeadingElement>(null);
+ const bodyRef = useRef<HTMLDivElement>(null);
+ const titleId = useId();
+ const fixesId = useId();
+ useEscapeLayer(rootRef, true, onClose, { modal: true });
+
+ // Switching views starts at the top, with focus on the new title (as a page change would).
+ const first = useRef(true);
+ useEffect(() => {
+ if (first.current) return void (first.current = false);
+ bodyRef.current?.scrollTo?.({ top: 0 });
+ titleRef.current?.focus();
+ }, [page]);
+
+ const date = shortDate(entry.date);
+ const folded = entry.fixes.length > FIXES_FOLD_OVER && !fixesOpen;
+ const fixes = folded ? entry.fixes.slice(0, FIXES_SHOWN) : entry.fixes;
+ const leadId = entry.highlights.find((h) => h.image)?.id;
+ const img = (name: string) => `/whatsnew/${entry.version}/${name}`;
+
+ const btnH = phone ? 'h-12' : 'h-10';
+ const ghost = `inline-flex ${btnH} items-center justify-center gap-1.5 rounded-xl border border-white/[0.14] bg-white/[0.03] px-3.5 text-[13px] font-medium text-zinc-200 hover:bg-white/[0.08] hover:text-zinc-50 ${focus}`;
+ const primary = `inline-flex ${btnH} min-w-[120px] items-center justify-center rounded-xl bg-[linear-gradient(135deg,#7a62f0_0%,#5b47d6_100%)] px-5 text-sm font-semibold text-white shadow-[inset_0_1px_0_0_rgb(255_255_255/.04),0_1px_2px_0_rgb(6_3_20/.5)] hover:brightness-110 ${phone ? 'flex-1' : ''} ${focus}`;
+ const close = (
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ className={`absolute ${phone ? 'right-2 top-3.5 h-11 w-11' : 'right-3 top-3 h-8 w-8'} grid place-items-center rounded-lg text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-100 ${focus}`}
+ >
+ <X size={15} aria-hidden="true" />
+ </button>
+ );
+ const gotIt = (
+ <button type="button" onClick={onClose} className={primary} data-whats-new-done>
+ Got it
+ </button>
+ );
+
+ const main = (
+ <>
+ <div className={`flex shrink-0 items-center ${phone ? 'gap-3 py-3 pl-[18px] pr-[52px]' : 'gap-3.5 pb-3.5 pl-6 pr-14 pt-5'}`}>
+ <span className={`grid shrink-0 place-items-center rounded-xl bg-surface-overlay shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)] ${phone ? 'h-10 w-10' : 'h-11 w-11'}`}>
+ <Mark size={phone ? 26 : 30} />
+ </span>
+ <div className="min-w-0">
+ <p className="m-0 text-xs leading-[18px] text-zinc-400" data-whats-new-eyebrow>
+ {updatedFrom !== null ? (
+ <>
+ <b className="font-medium text-teal-300">Updated</b>
+ {updatedFrom ? ` from ${updatedFrom}` : ''} · {date}
+ </>
+ ) : (
+ `Released ${date}`
+ )}
+ </p>
+ <h2 ref={titleRef} id={titleId} tabIndex={-1} className={`m-0 font-semibold tracking-[-.005em] text-zinc-50 outline-none ${phone ? 'text-[17px] leading-6' : 'text-lg leading-[26px]'}`}>
+ What’s new in kwant bots {entry.version}
+ </h2>
+ </div>
+ </div>
+ {close}
+ <div ref={bodyRef} className={`min-h-0 flex-1 overflow-y-auto overscroll-contain ${phone ? 'px-[18px] pb-4' : 'px-6 pb-[18px]'}`}>
+ <ul className="m-0 list-none p-0">
+ {entry.highlights.map((h, i) => {
+ const view = highlightView(h);
+ const lead = h.image && h.id === leadId;
+ const text = (
+ <div className="min-w-0 flex-1">
+ <h3 className="m-0 flex items-baseline gap-2.5 text-[15px] font-semibold leading-[22px] text-zinc-100">
+ <span aria-hidden="true" className="h-1.5 w-1.5 shrink-0 -translate-y-0.5 bg-sky-400" />
+ {h.title}
+ </h3>
+ <p className={`mb-0 ml-4 mt-0.5 text-sm text-zinc-300 ${phone ? 'leading-5' : 'leading-[21px]'}`}>{h.text}</p>
+ {view && (
+ <button
+ type="button"
+ onClick={() => onOpen(view)}
+ aria-label={`Show me: ${h.title}`}
+ className={`-mb-1 ml-2.5 mt-1 inline-flex items-center gap-1.5 rounded-lg pl-1.5 text-[13px] font-semibold text-sky-300 hover:bg-sky-500/[0.14] hover:text-sky-200 ${phone ? 'h-11 pr-2.5' : 'h-8 pr-2'} ${focus}`}
+ >
+ Show me <ArrowRight size={14} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ );
+ return (
+ <li key={h.id} className={`border-t border-white/[0.07] ${i === 0 ? 'border-t-0 pb-3 pt-1' : 'py-3'}`} data-highlight={h.id}>
+ {lead ? (
+ <>
+ <img src={img(h.image!)} alt="" className="mb-3 block aspect-[2/1] w-full rounded-[10px] bg-[#0f0b22] object-cover shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)]" />
+ {text}
+ </>
+ ) : (
+ <div className={`flex items-start ${phone ? 'gap-3' : 'gap-4'}`}>
+ {text}
+ {h.image && (
+ <img
+ src={img(h.image)}
+ alt=""
+ className={`mt-1 block aspect-[16/10] shrink-0 rounded-[10px] bg-[#0f0b22] object-cover ${phone ? 'w-[88px]' : 'w-[120px]'}`}
+ />
+ )}
+ </div>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ {entry.fixes.length > 0 && (
+ <section aria-labelledby={fixesId} className={`mt-1.5 rounded-xl bg-white/[0.03] shadow-[inset_0_0_0_1px_rgb(255_255_255/.07)] ${phone ? 'px-3.5 py-3' : 'px-4 pb-3.5 pt-3'}`}>
+ <h4 id={fixesId} className="m-0 mb-1.5 text-[13px] font-semibold leading-5 text-zinc-300">
+ Smaller changes and fixes: {entry.fixes.length}
+ </h4>
+ <ul className="m-0 grid list-none gap-1 p-0" data-whats-new-fixes>
+ {fixes.map((f, i) => (
+ <li key={i} className="relative pl-3.5 text-[13px] leading-5 text-zinc-400">
+ <span aria-hidden="true" className="absolute left-0.5 top-2 h-1 w-1 rounded-[1px] bg-zinc-600" />
+ {f}
+ </li>
+ ))}
+ </ul>
+ {folded && (
+ <button
+ type="button"
+ aria-expanded={false}
+ onClick={() => setFixesOpen(true)}
+ className={`-ml-1.5 mt-1.5 inline-flex h-7 items-center gap-1 rounded-md px-1.5 text-[13px] font-medium text-sky-300 hover:bg-sky-500/[0.12] ${phone ? 'min-h-[44px]' : ''} ${focus}`}
+ >
+ Show {entry.fixes.length - FIXES_SHOWN} more <ChevronDown size={15} aria-hidden="true" />
+ </button>
+ )}
+ </section>
+ )}
+ </div>
+ <div className={`relative flex shrink-0 items-center gap-2.5 border-t border-white/[0.07] bg-surface-raised ${phone ? 'px-4 pb-[calc(14px+env(safe-area-inset-bottom))] pt-3' : 'px-6 pb-[18px] pt-3.5'}`}>
+ <span aria-hidden="true" className="pointer-events-none absolute inset-x-0 bottom-full h-6 bg-gradient-to-t from-[var(--kw-surface-raised)] to-transparent" />
+ {changelog && (
+ <button type="button" onClick={() => setPage('all')} className={ghost}>
+ <List size={15} aria-hidden="true" /> All changes
+ </button>
+ )}
+ {!phone && <span className="flex-1" />}
+ {gotIt}
+ </div>
+ </>
+ );
+
+ const all = (
+ <>
+ <div className={`flex shrink-0 flex-col items-start gap-1 ${phone ? 'py-3 pl-[18px] pr-[52px]' : 'pb-3.5 pl-6 pr-14 pt-5'}`}>
+ <button
+ type="button"
+ onClick={() => setPage('main')}
+ className={`-ml-1 inline-flex items-center gap-1 rounded-lg pl-1 pr-2 text-[13px] font-medium text-zinc-300 hover:bg-white/[0.06] hover:text-zinc-100 ${phone ? 'h-11' : 'h-8'} ${focus}`}
+ >
+ <ChevronLeft size={15} aria-hidden="true" /> What’s new
+ </button>
+ <h2 ref={titleRef} id={titleId} tabIndex={-1} className={`m-0 font-semibold text-zinc-50 outline-none ${phone ? 'text-[17px] leading-6' : 'text-lg leading-[26px]'}`}>
+ All changes in {entry.version}
+ </h2>
+ </div>
+ {close}
+ <div ref={bodyRef} className={`min-h-0 flex-1 overflow-y-auto overscroll-contain select-text text-[13.5px] text-zinc-300 ${phone ? 'px-[18px] pb-4' : 'px-6 pb-[18px]'}`} data-whats-new-all>
+ <MarkdownRenderer content={changelog ?? ''} />
+ </div>
+ <div className={`flex shrink-0 items-center gap-2.5 border-t border-white/[0.07] bg-surface-raised ${phone ? 'px-4 pb-[calc(14px+env(safe-area-inset-bottom))] pt-3' : 'px-6 pb-[18px] pt-3.5'}`}>
+ <a href={releaseUrl(entry.version)} target="_blank" rel="noreferrer" className={ghost}>
+ <ExternalLink size={15} aria-hidden="true" /> On GitHub
+ </a>
+ {!phone && <span className="flex-1" />}
+ {gotIt}
+ </div>
+ </>
+ );
+
+ return (
+ <div
+ className={`fixed inset-0 z-[80] bg-[rgb(6_3_20/.6)] ${phone ? 'flex items-end' : 'grid place-items-center p-10'}`}
+ onClick={onClose}
+ data-whats-new={entry.version}
+ >
+ <div
+ ref={rootRef}
+ tabIndex={-1}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={titleId}
+ onClick={(e) => e.stopPropagation()}
+ className={
+ phone
+ ? 'relative flex max-h-[88vh] w-full flex-col overflow-hidden rounded-t-[20px] border border-b-0 border-white/[0.14] bg-surface-raised outline-none animate-[t-sheet_200ms_ease-out] motion-reduce:animate-none'
+ : 'relative flex max-h-[min(760px,calc(100vh-80px))] w-[560px] max-w-[calc(100vw-32px)] flex-col overflow-hidden rounded-2xl border border-white/[0.14] bg-surface-raised shadow-[inset_0_1px_0_0_rgb(255_255_255/.05),0_24px_64px_-16px_rgb(6_3_20/.85)] outline-none animate-[t-rise_180ms_ease-out] motion-reduce:animate-none'
+ }
+ >
+ {phone && <span aria-hidden="true" className="mx-auto mt-2 block h-1 w-9 shrink-0 rounded bg-zinc-700" />}
+ {page === 'all' ? all : main}
+ </div>
+ </div>
+ );
+};
+
+interface Open {
+ entry: WhatsNewEntry;
+ updatedFrom: string | null | undefined;
+}
+
+/**
+ * Opens the sheet once per device after an update, and whenever the update banner or Settings › About asks.
+ * `established`: this person has used kwant before (an account works, or they've written in a chat); false
+ * for a brand-new person, null while that isn't known yet. Mounted once inside the space.
+ */
+export const WhatsNewHost: React.FC<{ established: boolean | null; onOpen: (view: SpaceView) => void; latest?: WhatsNewEntry | null }> = ({
+ established,
+ onOpen,
+ latest = latestWhatsNew(),
+}) => {
+ const phone = useMedia(PHONE_QUERY);
+ const [open, setOpen] = useState<Open | null>(null);
+ const isOpen = !!open;
+
+ // After an update: once per version per device, never over another dialog.
+ useEffect(() => {
+ if (!latest || isOpen) return;
+ const seen = seenVersion();
+ const todo = decideOnLoad(seen, latest.version, established);
+ if (todo === 'record') markSeen(latest.version);
+ if (todo !== 'show') return;
+ const tryOpen = () => {
+ if (otherDialogOpen()) return false;
+ markSeen(latest.version);
+ // No stored key: someone upgrading from 0.7.5 or earlier, from a version we can't name.
+ setOpen({ entry: latest, updatedFrom: seen ?? '' });
+ return true;
+ };
+ if (tryOpen() || typeof MutationObserver === 'undefined') return;
+ const watch = new MutationObserver(() => {
+ if (tryOpen()) watch.disconnect();
+ });
+ watch.observe(document.body, { subtree: true, childList: true, attributes: true, attributeFilter: ['aria-modal', 'role', 'open'] });
+ return () => watch.disconnect();
+ }, [latest, established, isOpen]);
+
+ // Asked for by hand (banner, Settings): opens over Settings, since that's where the person is.
+ const req = useSyncExternalStore(subscribeOpen, openRequest, openRequest);
+ const handled = useRef(req?.seq ?? 0);
+ useEffect(() => {
+ if (!req || req.seq === handled.current) return;
+ handled.current = req.seq;
+ const entry = whatsNewFor(req.version);
+ if (!entry) return;
+ markSeen(entry.version);
+ setOpen({ entry, updatedFrom: null });
+ }, [req]);
+
+ if (!open) return null;
+ return (
+ <WhatsNewSheetView
+ key={open.entry.version}
+ entry={open.entry}
+ changelog={changelogFor(open.entry.version)}
+ phone={phone}
+ updatedFrom={open.updatedFrom}
+ onClose={() => setOpen(null)}
+ onOpen={(view) => {
+ setOpen(null);
+ onOpen(view);
+ }}
+ />
+ );
+};
+
+/** Settings › About: "What's new in X" and the earlier versions. Shown everywhere (the update card is Mac-only). */
+export const WhatsNewAboutView: React.FC<{ entries: WhatsNewEntry[]; onPick: (version: string) => void }> = ({ entries, onPick }) => {
+ const [latest, ...earlier] = entries;
+ if (!latest) return null;
+ return (
+ <section aria-labelledby="whats-new-about-title" data-whats-new-about className="space-y-0 rounded-xl border border-zinc-800 bg-zinc-950/60 p-4">
+ <h3 id="whats-new-about-title" className="flex items-center gap-2 text-xs font-medium text-zinc-300">
+ <List size={15} className="text-sky-400" aria-hidden="true" />
+ <span>What’s new</span>
+ </h3>
+ <button
+ type="button"
+ onClick={() => onPick(latest.version)}
+ className={`mt-3 flex min-h-[56px] w-full items-center gap-3 rounded-[10px] bg-sky-500/10 py-2 pl-2.5 pr-3 text-left shadow-[inset_0_0_0_1px_rgb(157_143_255/.25)] hover:bg-sky-500/[0.16] max-md:min-h-[60px] ${focus}`}
+ >
+ <span className="grid h-9 w-9 shrink-0 place-items-center rounded-[9px] bg-surface-overlay shadow-[inset_0_0_0_1px_rgb(255_255_255/.14)]">
+ <Mark size={24} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <b className="block text-[13.5px] font-semibold leading-5 text-zinc-100">What’s new in {latest.version}</b>
+ <span className="block text-xs leading-[18px] text-zinc-400">
+ {shortDate(latest.date)} · {entrySummary(latest)}
+ </span>
+ </span>
+ <ChevronRight size={15} className="shrink-0 text-sky-300" aria-hidden="true" />
+ </button>
+ {earlier.length > 0 && (
+ <>
+ <p className="mb-1 mt-3.5 text-[11px] font-semibold uppercase tracking-[.08em] text-zinc-400">Earlier versions</p>
+ <ul className="m-0 list-none p-0">
+ {earlier.map((e, i) => (
+ <li key={e.version} className={i ? 'border-t border-white/[0.07]' : ''}>
+ <button
+ type="button"
+ onClick={() => onPick(e.version)}
+ aria-label={`What’s new in ${e.version}`}
+ className={`flex min-h-[44px] w-full items-center gap-3 rounded-lg px-2.5 py-1.5 text-left hover:bg-white/[0.04] ${focus}`}
+ >
+ <span className="w-[54px] shrink-0 font-mono text-[13px] font-semibold text-zinc-200">{e.version}</span>
+ <span className="w-[52px] shrink-0 text-xs text-zinc-400">{shortDate(e.date)}</span>
+ <span className="min-w-0 flex-1 truncate text-[12.5px] text-zinc-300">{entrySummary(e)}</span>
+ <ChevronRight size={15} className="shrink-0 text-zinc-500" aria-hidden="true" />
+ </button>
+ </li>
+ ))}
+ </ul>
+ </>
+ )}
+ <a href={RELEASES_URL} target="_blank" rel="noreferrer" className={`mt-2 inline-flex items-center gap-1.5 py-1 text-xs text-sky-300 hover:underline ${focus}`}>
+ Older releases on GitHub <ExternalLink size={13} aria-hidden="true" />
+ </a>
+ </section>
+ );
+};
+
+export const WhatsNewAbout: React.FC<{ onPick?: (version: string) => void }> = ({ onPick }) => (
+ <WhatsNewAboutView entries={WHATS_NEW} onPick={onPick ?? openWhatsNew} />
+);
+
+/** Whether the banner's "See what's new" has something to open for `version`. */
+export const hasWhatsNew = (version: string) => !!whatsNewFor(version);
diff --git a/frontend/src/components/dev/TicketBrief.tsx b/frontend/src/components/dev/TicketBrief.tsx
index 7049a847..9947eb51 100644
--- a/frontend/src/components/dev/TicketBrief.tsx
+++ b/frontend/src/components/dev/TicketBrief.tsx
@@ -127,10 +127,12 @@ export interface TicketBriefProps {
/** The lead's name for "by Ann" and "Ann won't act on it"; falls back to the brief's author. */
lead?: string | null;
defaultOpen?: boolean;
+ /** D8: the ticket's key, so the toggle reads "Show brief TRAIL-142" with several cards on screen. */
+ ticketKey?: string | null;
}
/** The brief, open or collapsed. Collapsed: "BRIEF Ann · 10:03 · 6 parts, 11 sources" and Show brief. */
-export const TicketBrief: React.FC<TicketBriefProps> = ({ brief, fallbackText = null, lead = null, defaultOpen = false }) => {
+export const TicketBrief: React.FC<TicketBriefProps> = ({ brief, fallbackText = null, lead = null, defaultOpen = false, ticketKey = null }) => {
const [open, setOpen] = useState(defaultOpen);
const bodyId = useId();
const origins = useContext(SiteOrigins);
@@ -151,7 +153,14 @@ export const TicketBrief: React.FC<TicketBriefProps> = ({ brief, fallbackText =
Brief
</h4>
<span className="by">{by.filter(Boolean).join(' · ')}</span>
- <button type="button" className="tk-textbtn" aria-expanded={open} aria-controls={bodyId} onClick={() => setOpen((o) => !o)}>
+ <button
+ type="button"
+ className="tk-textbtn"
+ aria-expanded={open}
+ aria-controls={bodyId}
+ aria-label={ticketKey ? `${open ? 'Hide' : 'Show'} brief ${ticketKey}` : undefined}
+ onClick={() => setOpen((o) => !o)}
+ >
{open ? 'Hide' : 'Show brief'}
{open ? <Minus size={12} aria-hidden="true" /> : <ChevronDown size={12} aria-hidden="true" />}
</button>
diff --git a/frontend/src/components/dev/TicketCard.tsx b/frontend/src/components/dev/TicketCard.tsx
index 0fe3e1ad..54957572 100644
--- a/frontend/src/components/dev/TicketCard.tsx
+++ b/frontend/src/components/dev/TicketCard.tsx
@@ -362,7 +362,7 @@ export const TicketCard: React.FC<TicketCardProps> = (props) => {
<>
Not every done-when line is met.{' '}
{props.onOpenReview ? (
- <button type="button" className="tk-inl" onClick={props.onOpenReview} data-see-review>
+ <button type="button" className="tk-inl" onClick={props.onOpenReview} aria-label={`See the review ${t.key}`} data-see-review>
See the review
</button>
) : (
@@ -544,7 +544,7 @@ export const TicketCard: React.FC<TicketCardProps> = (props) => {
{showBrief && (
<div id={briefId}>
- <TicketBrief key={`${t.key}-${t.state}`} brief={brief} fallbackText={briefText} lead={w.lead} defaultOpen={briefOpen || linkBrief} />
+ <TicketBrief key={`${t.key}-${t.state}`} brief={brief} fallbackText={briefText} lead={w.lead} defaultOpen={briefOpen || linkBrief} ticketKey={t.key} />
</div>
)}
{linkBrief && !showBrief && <div id={briefId} hidden />}
diff --git a/frontend/src/components/markdownInline.ts b/frontend/src/components/markdownInline.ts
new file mode 100644
index 00000000..fd9bd4a5
--- /dev/null
+++ b/frontend/src/components/markdownInline.ts
@@ -0,0 +1,5 @@
+// The chat's own look for a link and an inline code span, shared by MarkdownRenderer and the renderers
+// that draw a reply's inline markdown themselves (results/InlineText.tsx).
+export const linkClass = 'text-sky-400 hover:text-sky-300 underline underline-offset-2 transition-colors';
+export const inlineCodeClass =
+ 'px-1.5 py-0.5 rounded-md font-mono text-[12px] bg-zinc-800/80 text-sky-300 border border-zinc-700/50 [overflow-wrap:anywhere] [box-decoration-break:clone] [-webkit-box-decoration-break:clone]';
diff --git a/frontend/src/components/results/InlineText.tsx b/frontend/src/components/results/InlineText.tsx
new file mode 100644
index 00000000..238ebcde
--- /dev/null
+++ b/frontend/src/components/results/InlineText.tsx
@@ -0,0 +1,36 @@
+import React from 'react';
+import ReactMarkdown from 'react-markdown';
+import remarkGfm from 'remark-gfm';
+import { inlineCodeClass, linkClass } from '../markdownInline';
+
+// Only what can sit inside one line of a reply: the paragraph wrapper is dropped, anything else (a
+// heading, a list, raw HTML) keeps just its text. Raw HTML is never drawn (react-markdown skips it).
+const INLINE = ['p', 'a', 'code', 'strong', 'em', 'del', 'br'];
+
+/**
+ * One line of a reply as the chat draws it (F-1): links stay links (the chat's own new-tab link), code
+ * stays code, bold and italics stay (in the line's own colour, so a done step dims all of it). A leading "1." "-" "#" or ">" is the reply's text, not a new block.
+ */
+export const InlineText: React.FC<{ md: string }> = ({ md }) => (
+ <ReactMarkdown
+ remarkPlugins={[remarkGfm]}
+ allowedElements={INLINE}
+ unwrapDisallowed
+ components={{
+ p: ({ children }) => <>{children}</>,
+ a: ({ href, children }) => (
+ <a href={href} target="_blank" rel="noopener noreferrer" className={linkClass}>
+ {children}
+ </a>
+ ),
+ code: ({ children }) => <code className={inlineCodeClass}>{children}</code>,
+ strong: ({ children }) => <strong className="font-semibold">{children}</strong>,
+ em: ({ children }) => <em className="italic">{children}</em>,
+ }}
+ >
+ {escapeBlockStart(md)}
+ </ReactMarkdown>
+);
+
+/** "1. Mix" or "- salt" as one line of text: escape the marker that would start a list, heading or quote. */
+export const escapeBlockStart = (md: string) => md.replace(/^(\s*)(#{1,6}|>|[-+*]|\d{1,9}[.)])(?=\s|$)/, (_all, sp: string, mark: string) => sp + mark.replace(/^(\d+)([.)])$/, '$1\\$2').replace(/^([#>+*-])/, '\\$1'));
diff --git a/frontend/src/components/results/Recipe.tsx b/frontend/src/components/results/Recipe.tsx
new file mode 100644
index 00000000..3f29e388
--- /dev/null
+++ b/frontend/src/components/results/Recipe.tsx
@@ -0,0 +1,358 @@
+import React, { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react';
+import { Check, ChevronDown, ChevronUp, Clock, Minus, Plus, Users } from 'lucide-react';
+import type { RecipeBlock, RecipeIngredient, RecipeStep, RecipeTime } from '../../smartResults';
+import { inRange, isObj, isText, optText, parseCommon, plainText, uniqueIds } from '../../smartResults';
+import { InlineText } from './InlineText';
+import { factor, groupIngredients, isScalable, scaleQty, servesRange, shownServes, useRecipeState } from '../../recipe';
+import type { RendererProps } from './registry';
+
+/**
+ * A recipe (0.7.6): 2–40 ingredients, 2–30 steps, 0–3 times, 0–6 notes, `serves` optional. qty + text is
+ * the reply's line (design §11), so the renderer never strips a prefix. Any field off, and the reply
+ * shows as text.
+ */
+export function validRecipe(raw: unknown): RecipeBlock | null {
+ const b = parseCommon(raw, 'recipe');
+ // Limits as in contract.md §1: the server only writes a recipe as a stretch of the reply.
+ if (!b || b.source.kind !== 'markdown_section') return null;
+ const serves = b.serves ?? null;
+ if (serves !== null && !(typeof serves === 'number' && Number.isInteger(serves) && serves >= 1 && serves <= 24)) return null;
+
+ const rawTimes = b.times ?? [];
+ if (!inRange(rawTimes, 0, 3)) return null;
+ const times: RecipeTime[] = [];
+ for (const t of rawTimes) {
+ if (!isObj(t) || !isText(t.label, 40) || !isText(t.text, 60)) return null;
+ times.push({ label: t.label, text: t.text });
+ }
+
+ if (!inRange(b.ingredients, 2, 40) || !uniqueIds(b.ingredients)) return null;
+ const ingredients: RecipeIngredient[] = [];
+ for (const it of b.ingredients as Record<string, unknown>[]) {
+ const qty = optText(it.qty, 40), group = optText(it.group, 100);
+ if (qty === undefined || group === undefined || !isText(it.text, 300) || !/^i\d+$/.test(it.id as string)) return null;
+ if (qty !== null && !/^[\d¼½¾⅓⅔⅛]/.test(qty)) return null;
+ ingredients.push({ id: it.id as string, text: it.text, qty, group });
+ }
+
+ if (!inRange(b.steps, 2, 30) || !uniqueIds(b.steps)) return null;
+ const steps: RecipeStep[] = [];
+ for (const s of b.steps as Record<string, unknown>[]) {
+ if (!isText(s.text, 600) || !/^s\d+$/.test(s.id as string)) return null;
+ steps.push({ id: s.id as string, text: s.text });
+ }
+
+ const rawNotes = b.notes ?? [];
+ if (!inRange(rawNotes, 0, 6) || !rawNotes.every((n) => isText(n, 600))) return null;
+
+ return { id: b.id, type: 'recipe', title: b.title, source: b.source, provenance: b.provenance, serves, times, ingredients, steps, notes: [...(rawNotes as string[])] };
+}
+
+const PHONE = '(max-width: 639px)';
+const subscribePhone = (cb: () => void) => {
+ const mq = typeof window.matchMedia === 'function' ? window.matchMedia(PHONE) : null;
+ mq?.addEventListener?.('change', cb);
+ return () => mq?.removeEventListener?.('change', cb);
+};
+/** A viewport under 640 px (design §4): where the ingredients fold. */
+export const usePhone = () =>
+ useSyncExternalStore(subscribePhone, () => (typeof window.matchMedia === 'function' ? window.matchMedia(PHONE).matches : false), () => false);
+
+/**
+ * Two columns need room: the card itself must be at least this wide (design §8, Ada's §11 check). 700
+ * puts a 1180 px window with the sidebar at two columns and keeps 1024 at one (F-6).
+ */
+export const TWO_COLUMNS_MIN = 700;
+/** Ingredients fold on a phone when there are more than this many, showing FOLD_SHOW. */
+export const FOLD_OVER = 10;
+export const FOLD_SHOW = 8;
+
+const openKey = (messageId: string, blockId: string) => `kwnt:recipe-open:${messageId}:${blockId}`;
+const readOpen = (key: string) => {
+ try {
+ return sessionStorage.getItem(key) === '1';
+ } catch {
+ return false;
+ }
+};
+
+const chipClass = 'inline-flex h-8 items-center gap-1.5 whitespace-nowrap rounded-full border border-hairline px-3 text-meta text-zinc-200';
+const stepBtn =
+ 'grid h-[30px] w-[30px] max-sm:h-11 max-sm:w-11 place-items-center rounded-full text-zinc-200 hover:bg-white/[0.05] hover:text-zinc-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 aria-disabled:opacity-40 aria-disabled:cursor-not-allowed';
+const boxClass =
+ 'mt-[3px] h-4 w-4 shrink-0 cursor-pointer rounded accent-sky-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-900';
+
+const SectionHead: React.FC<{ id: string; title: string; children: React.ReactNode }> = ({ id, title, children }) => (
+ <div className="mb-1 flex items-baseline justify-between gap-2">
+ <h4 id={id} className="text-meta font-semibold text-zinc-200">
+ {title}
+ </h4>
+ {children}
+ </div>
+);
+
+/** The card: header (name, Serves stepper, times), ingredients and method, notes. Ticks stay on this device. */
+export const Recipe: React.FC<RendererProps<RecipeBlock>> = ({ block, messageId }) => {
+ const { state, toggleHave, toggleDone, setServes } = useRecipeState(messageId, block);
+ const uid = useId();
+ const phone = usePhone();
+ const card = useRef<HTMLElement>(null);
+ const [wide, setWide] = useState(false);
+ const [open, setOpen] = useState(() => readOpen(openKey(messageId, block.id)));
+ const [popped, setPopped] = useState<string | null>(null);
+
+ // Two columns when the card itself has room, whatever the sidebar takes (no container queries here).
+ useLayoutEffect(() => {
+ const el = card.current;
+ if (!el) return;
+ const measure = () => setWide(el.getBoundingClientRect().width >= TWO_COLUMNS_MIN);
+ measure();
+ if (typeof ResizeObserver !== 'function') return;
+ const ro = new ResizeObserver(measure);
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+ useEffect(() => {
+ try {
+ if (open) sessionStorage.setItem(openKey(messageId, block.id), '1');
+ else sessionStorage.removeItem(openKey(messageId, block.id));
+ } catch {
+ // The open state then lasts for this view only.
+ }
+ }, [open, messageId, block.id]);
+
+ const scalable = isScalable(block);
+ const shown = shownServes(block, state.serves);
+ const k = scalable ? factor(block, shown) : 1;
+ const scaled = scalable && shown !== block.serves;
+ const range = servesRange(block.serves ?? 1);
+
+ const groups = groupIngredients(block);
+ const total = block.ingredients.length;
+ const folds = phone && total > FOLD_OVER;
+ const limit = folds && !open ? FOLD_SHOW : Infinity;
+ const have = block.ingredients.filter((i) => state.have.has(i.id)).length;
+
+ const stepsDone = block.steps.filter((s) => state.done.has(s.id)).length;
+ const allDone = stepsDone === block.steps.length;
+ const next = stepsDone > 0 && !allDone ? block.steps.find((s) => !state.done.has(s.id))?.id : undefined;
+
+ const ingId = `${uid}-ing`;
+ const methodId = `${uid}-method`;
+ const listId = `${uid}-ings`;
+ const hasChips = !!block.serves || block.times.length > 0;
+
+ let seen = 0;
+ const title = block.title ?? 'Recipe';
+
+ return (
+ <section
+ ref={card}
+ aria-label={title}
+ data-smart-result="recipe"
+ data-block-id={block.id}
+ data-columns={wide ? 2 : 1}
+ className="my-3.5 rounded-xl border border-zinc-700/60 bg-zinc-900/60 p-3.5 shadow-[var(--kws-shadow)] sm:p-5"
+ >
+ <h3 className="text-title font-semibold text-zinc-100 [overflow-wrap:anywhere]">{title}</h3>
+ {hasChips && (
+ <div className="mt-2.5 flex flex-wrap items-center gap-2">
+ {scalable ? (
+ <span
+ role="group"
+ aria-label="Servings"
+ className="inline-flex h-8 items-center rounded-full border border-hairline-strong bg-white/[0.04] pl-3 text-meta text-zinc-400 max-sm:h-11"
+ >
+ <span className="mr-0.5 inline-flex items-center gap-1.5">
+ <Users size={13} aria-hidden="true" />
+ Serves
+ </span>
+ <button
+ type="button"
+ aria-label="Fewer servings"
+ aria-disabled={shown <= range.min}
+ onClick={() => shown > range.min && setServes(shown - 1)}
+ className={stepBtn}
+ >
+ <Minus size={14} aria-hidden="true" />
+ </button>
+ <output aria-live="polite" aria-label={`${shown} ${shown === 1 ? 'serving' : 'servings'}`} className="min-w-[22px] text-center text-[13px] font-semibold tabular-nums text-zinc-100">
+ {shown}
+ </output>
+ <button
+ type="button"
+ aria-label="More servings"
+ aria-disabled={shown >= range.max}
+ onClick={() => shown < range.max && setServes(shown + 1)}
+ className={stepBtn}
+ >
+ <Plus size={14} aria-hidden="true" />
+ </button>
+ </span>
+ ) : block.serves ? (
+ <span className={chipClass} data-serves-chip>
+ <Users size={13} className="text-zinc-400" aria-hidden="true" />
+ <span className="text-zinc-400">Serves</span> {block.serves}
+ </span>
+ ) : null}
+ {block.times.map((t, i) => (
+ <span key={`${t.label}-${i}`} className={chipClass}>
+ {i === 0 && <Clock size={13} className="text-zinc-400" aria-hidden="true" />}
+ <span className="text-zinc-400">{t.label}</span> {t.text}
+ </span>
+ ))}
+ {scaled && (
+ <button
+ type="button"
+ onClick={() => block.serves && setServes(block.serves)}
+ className="inline-flex min-h-8 items-center rounded px-1 text-meta text-sky-300 underline-offset-[3px] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400 max-sm:min-h-11"
+ >
+ Back to {block.serves}
+ </button>
+ )}
+ </div>
+ )}
+
+ <div className={`mt-4 grid gap-4 border-t border-hairline pt-3.5 ${wide ? 'grid-cols-[minmax(0,2fr)_minmax(0,3fr)] gap-x-7' : ''}`}>
+ <div>
+ <SectionHead id={ingId} title="Ingredients">
+ <span className="text-meta tabular-nums text-zinc-400">{have ? `${have} of ${total}` : total}</span>
+ </SectionHead>
+ <div id={listId}>
+ {groups.map(({ group, items }, gi) => {
+ const visible = items.filter(() => seen++ < limit);
+ if (!visible.length) return null;
+ const labelId = `${uid}-g${gi}`;
+ return (
+ <div key={group ?? '_'}>
+ {group && (
+ <div id={labelId} className="mb-0.5 mt-2.5 text-meta font-medium text-zinc-400 [overflow-wrap:anywhere]">
+ {group}
+ </div>
+ )}
+ <ul role="list" aria-labelledby={group ? labelId : ingId}>
+ {visible.map((ing) => {
+ const on = state.have.has(ing.id);
+ const s = ing.qty ? scaleQty(ing.qty, k, plainText(ing.text)) : null;
+ const amountClass = on ? 'font-medium text-zinc-500' : s?.scaled ? 'font-semibold text-sky-200' : 'font-medium text-zinc-100';
+ return (
+ <li key={ing.id}>
+ <label className="-mx-1.5 flex min-h-8 cursor-pointer items-start gap-2.5 rounded-lg px-1.5 py-[5px] hover:bg-white/[0.05] max-sm:min-h-11 max-sm:py-[11px]">
+ <input type="checkbox" checked={on} onChange={() => toggleHave(ing.id)} className={boxClass} />
+ <span
+ className={`min-w-0 text-body [overflow-wrap:anywhere] ${on ? 'text-zinc-500 line-through decoration-zinc-600' : 'text-zinc-300'}`}
+ data-ingredient={ing.id}
+ >
+ {s ? (
+ <>
+ <span className={`tabular-nums ${amountClass}`} title={s.scaled ? `In the reply: ${ing.qty}` : undefined} data-scaled={s.scaled || undefined}>
+ {s.qty}
+ </span>
+ {/* Colour and the hover title don't reach a screen reader (F-5). */}
+ {s.scaled && <span className="sr-only"> (was {ing.qty})</span>}
+ {ing.text.startsWith(',') ? '' : ' '}
+ <InlineText md={ing.text} />
+ </>
+ ) : (
+ <InlineText md={ing.text} />
+ )}
+ </span>
+ </label>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+ })}
+ </div>
+ {folds && (
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={listId}
+ onClick={() => setOpen((o) => !o)}
+ className="mt-1.5 flex min-h-11 w-full items-center justify-center gap-1.5 rounded-lg border border-hairline text-meta font-medium text-zinc-200 hover:bg-white/[0.05] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-400"
+ >
+ {open ? 'Show fewer' : `Show all ${total}`}
+ {open ? <ChevronUp size={14} aria-hidden="true" /> : <ChevronDown size={14} aria-hidden="true" />}
+ </button>
+ )}
+ </div>
+
+ <div className={wide ? 'border-l border-hairline pl-6' : 'border-t border-hairline pt-3.5'}>
+ <SectionHead id={methodId} title="Method">
+ {allDone ? (
+ <span className="inline-flex items-center gap-1 text-meta text-ok">
+ <Check size={12} aria-hidden="true" />
+ All {block.steps.length} done
+ </span>
+ ) : (
+ <span className="text-meta tabular-nums text-zinc-400">{stepsDone ? `${stepsDone} of ${block.steps.length} done` : `${block.steps.length} steps`}</span>
+ )}
+ </SectionHead>
+ <ol role="list" aria-labelledby={methodId} className="grid gap-0.5">
+ {block.steps.map((step, i) => {
+ const on = state.done.has(step.id);
+ const isNext = step.id === next;
+ return (
+ <li key={step.id}>
+ <label
+ data-step={step.id}
+ data-state={on ? 'done' : isNext ? 'next' : undefined}
+ className={`relative -mx-2 flex cursor-pointer gap-3 rounded-lg p-2 hover:bg-white/[0.05] has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-sky-400 max-sm:min-h-11 max-sm:py-2.5 ${
+ isNext ? 'bg-sky-500/10 ring-1 ring-inset ring-sky-400/40' : ''
+ }`}
+ >
+ <input
+ type="checkbox"
+ className="sr-only"
+ checked={on}
+ onChange={() => {
+ setPopped(on ? null : step.id);
+ toggleDone(step.id);
+ }}
+ />
+ <span
+ aria-hidden="true"
+ className={`mt-px grid h-[22px] min-w-[22px] shrink-0 place-items-center rounded-full border px-[5px] text-meta font-semibold leading-none tabular-nums ${
+ on
+ ? `border-zinc-700 bg-zinc-800 text-ok ${popped === step.id ? 'motion-safe:animate-[kw-step-done_160ms_var(--kw-ease)_both]' : ''}`
+ : isNext
+ ? 'border-sky-300 bg-sky-300 text-zinc-950'
+ : 'border-zinc-600 text-zinc-300'
+ }`}
+ >
+ {on ? <Check size={12} strokeWidth={3} /> : i + 1}
+ </span>
+ <span className={`min-w-0 text-body [overflow-wrap:anywhere] ${on ? 'text-zinc-500' : isNext ? 'text-zinc-100' : 'text-zinc-300'}`}>
+ <span className="sr-only">Step {i + 1}: </span>
+ <InlineText md={step.text} />
+ {isNext && <span className="sr-only"> (next)</span>}
+ </span>
+ </label>
+ </li>
+ );
+ })}
+ </ol>
+ <span className="sr-only" aria-live="polite">
+ {stepsDone} of {block.steps.length} steps done
+ </span>
+ </div>
+ </div>
+
+ {block.notes.length > 0 && (
+ <div className="mt-4 border-t border-hairline pt-3">
+ <h4 className="mb-1 text-meta font-semibold text-zinc-400">Notes</h4>
+ <ul className="list-disc space-y-1 pl-[18px] text-meta leading-[19px] text-zinc-400 marker:text-zinc-600">
+ {block.notes.map((n, i) => (
+ <li key={i} className="[overflow-wrap:anywhere]">
+ <InlineText md={n} />
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ </section>
+ );
+};
diff --git a/frontend/src/components/results/RecipeActions.tsx b/frontend/src/components/results/RecipeActions.tsx
new file mode 100644
index 00000000..a7c8c190
--- /dev/null
+++ b/frontend/src/components/results/RecipeActions.tsx
@@ -0,0 +1,79 @@
+import React, { useEffect, useRef, useState } from 'react';
+import { Check, Copy, ShoppingBasket } from 'lucide-react';
+import type { RecipeBlock } from '../../smartResults';
+import { recipeMarkdown, shoppingItems, shoppingListText, shownServes, useRecipeState } from '../../recipe';
+import { playSfx } from '../../audio/chiptune';
+import { actionClass } from './SmartActions';
+
+// Kept apart from Recipe.tsx so the registry (and its tests) never load the sound module.
+
+/** A copy chip that says "Copied" (emerald check) for 2 s, with its own words for screen readers. */
+function useCopied() {
+ const [said, setSaid] = useState<{ ok: boolean; shown: string; sr: string } | null>(null);
+ const timer = useRef<number>();
+ useEffect(() => () => window.clearTimeout(timer.current), []);
+ const copy = async (text: string, shown: string, sr: string) => {
+ try {
+ await navigator.clipboard.writeText(text);
+ setSaid({ ok: true, shown, sr });
+ playSfx('click');
+ } catch {
+ setSaid({ ok: false, shown: 'Copy failed', sr: 'Could not copy' });
+ }
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => setSaid(null), 2000);
+ };
+ return { said, copy };
+}
+
+/**
+ * The recipe's chips in the message's action row (design §6): Copy recipe and Copy shopping list, in
+ * place of Copy data. The shopping list is the unticked ingredients at the shown servings; its count
+ * follows the ticks live.
+ */
+export const RecipeActions: React.FC<{ block: RecipeBlock; messageId: string }> = ({ block, messageId }) => {
+ const { state } = useRecipeState(messageId, block);
+ const shown = shownServes(block, state.serves);
+ const left = shoppingItems(block, state.have).length;
+ const recipe = useCopied();
+ const list = useCopied();
+ const forServes = block.serves ? ` for ${shown} ${shown === 1 ? 'serving' : 'servings'}` : '';
+ const items = (n: number) => `${n} ${n === 1 ? 'item' : 'items'}`;
+ const none = left === 0;
+ return (
+ <>
+ <button
+ type="button"
+ data-recipe-copy="recipe"
+ onClick={() => recipe.copy(recipeMarkdown(block, shown), 'Copied', `Copied the recipe${forServes}`)}
+ className={actionClass}
+ >
+ {recipe.said?.ok ? <Check size={14} className="text-emerald-400" aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}
+ <span className={recipe.said?.ok ? 'font-medium text-emerald-400' : recipe.said ? 'text-rose-300' : ''}>{recipe.said?.shown ?? 'Copy recipe'}</span>
+ </button>
+ <button
+ type="button"
+ data-recipe-copy="shopping"
+ aria-disabled={none || undefined}
+ aria-label={list.said ? undefined : `Copy shopping list, ${items(left)}`}
+ title={none ? 'Everything is ticked.' : undefined}
+ onClick={() => !none && list.copy(shoppingListText(block, state.have, shown), `Copied ${items(left)}`, `Copied ${items(left)}${forServes}`)}
+ className={`${actionClass} ${none ? 'cursor-not-allowed opacity-45' : ''}`}
+ >
+ {list.said?.ok ? <Check size={14} className="text-emerald-400" aria-hidden="true" /> : <ShoppingBasket size={14} aria-hidden="true" />}
+ {list.said ? (
+ <span className={list.said.ok ? 'font-medium text-emerald-400' : 'text-rose-300'}>{list.said.shown}</span>
+ ) : (
+ <>
+ <span className="max-sm:hidden">Copy shopping list</span>
+ <span className="sm:hidden">Shopping list</span>
+ <span className="min-w-[18px] rounded-full bg-zinc-800 px-[5px] text-center text-2xs leading-[18px] tabular-nums text-zinc-200">{left}</span>
+ </>
+ )}
+ </button>
+ <span className="sr-only" aria-live="polite">
+ {recipe.said?.sr ?? list.said?.sr ?? ''}
+ </span>
+ </>
+ );
+};
diff --git a/frontend/src/components/results/SmartResult.tsx b/frontend/src/components/results/SmartResult.tsx
index d1fc9e6b..5e003884 100644
--- a/frontend/src/components/results/SmartResult.tsx
+++ b/frontend/src/components/results/SmartResult.tsx
@@ -7,6 +7,7 @@ import { ReplySource, resolveBlock } from './registry';
import { blockCsv, blockJson, blockMarkdown } from './exporters';
import { SmartActions, actionClass, actionOnClass, evidenceClass } from './SmartActions';
import { VerifiedStamp } from '../Signature';
+import { RecipeActions } from './RecipeActions';
import { stampText } from '../../signature';
/** "Ask about this": ChatView puts `text` in the composer and focuses it. Nothing is sent. */
@@ -37,6 +38,7 @@ const saveAsText = (messageId: string, on: boolean) => {
};
const TYPE_LABEL: Record<SmartBlock['type'], string> = {
+ recipe: 'Recipe',
comparison: 'Comparison',
chart: 'Chart',
metrics: 'Key numbers',
@@ -221,11 +223,13 @@ const Footer: React.FC<{ block: SmartBlock; messageId: string; asText: boolean;
label={`All ${verified.total} ${verified.total === 1 ? 'check' : 'checks'} passed`}
/>
)}
+ {/* A recipe copies itself or its shopping list; its CSV/JSON aren't useful (design §6). */}
+ {block.type === 'recipe' && <RecipeActions block={block} messageId={messageId} />}
<button type="button" aria-pressed={asText} onClick={onToggle} className={`${actionClass} ${asText ? actionOnClass : ''}`}>
<FileText size={14} aria-hidden="true" />
Show as text
</button>
- <CopyData block={block} messageId={messageId} />
+ {block.type !== 'recipe' && <CopyData block={block} messageId={messageId} />}
{/* Where the numbers come from: a chip in the row's style, a fact rather than a button. */}
<span className={evidenceClass} data-evidence title={evidenceText(block)}>
<EvidenceIcon block={block} />
@@ -258,6 +262,7 @@ export const SmartResult: React.FC<SmartResultProps> = ({ raw, reply, messageId,
const { block, renderer } = resolved;
const { Component } = renderer;
const slot = reply === null;
+ // A recipe's stretch of the reply ("Show as text", or a render error) is that stretch as written.
const text = slot ? renderText?.(blockMarkdown(block)) ?? null : fallback;
const toggle = () => {
saveAsText(messageId, !asText);
@@ -267,7 +272,8 @@ export const SmartResult: React.FC<SmartResultProps> = ({ raw, reply, messageId,
return (
<div role="group" aria-label={name} data-smart-frame={block.type} className={slot ? 'mt-3 min-w-0 max-w-full' : 'min-w-0 max-w-full'}>
- {slot && block.title && <div className="mb-1.5 text-xs font-semibold text-zinc-300">{block.title}</div>}
+ {/* A recipe's card already leads with the dish name. */}
+ {slot && block.title && block.type !== 'recipe' && <div className="mb-1.5 text-xs font-semibold text-zinc-300">{block.title}</div>}
{asText ? (
text
) : (
diff --git a/frontend/src/components/results/exporters.ts b/frontend/src/components/results/exporters.ts
index 30bcabfb..9b81f206 100644
--- a/frontend/src/components/results/exporters.ts
+++ b/frontend/src/components/results/exporters.ts
@@ -3,6 +3,7 @@
// override this with `markdown` / `csv` in its registry entry.
import type { SmartBlock } from '../../smartResults';
+import { joinLine, recipeMarkdown } from '../../recipe';
import { comparisonCsv, csvCell, plainText, previewNote, stepsMarkdown } from '../../smartResults';
type Row = Record<string, unknown>;
@@ -36,6 +37,8 @@ export function blockRows(block: SmartBlock): Row[] {
});
case 'steps':
return block.items.map(({ text, done, when, owner }) => ({ ...(when != null ? { when } : {}), step: text, ...(owner != null ? { owner } : {}), ...(done != null ? { done } : {}) }));
+ case 'recipe':
+ return block.ingredients.map((i) => ({ ...(i.group ? { group: i.group } : {}), ingredient: i.qty ? joinLine(i.qty, i.text) : i.text }));
default:
return block.items.map(({ id: _id, ...rest }) => rest as Row);
}
@@ -54,6 +57,8 @@ const mdCell = (v: unknown) => cell(v).replace(/\|/g, '\\|').replace(/\n/g, ' ')
export function blockMarkdown(block: SmartBlock, done?: Set<string>): string {
if (block.type === 'steps') return stepsMarkdown(block, done);
+ // As the reply wrote it, at its own servings.
+ if (block.type === 'recipe') return recipeMarkdown(block, block.serves ?? 1);
const rows = blockRows(block);
const keys = [...new Set(rows.flatMap((r) => Object.keys(r)))];
const table = [
diff --git a/frontend/src/components/results/fixtures.ts b/frontend/src/components/results/fixtures.ts
index d184d15d..01fc7936 100644
--- a/frontend/src/components/results/fixtures.ts
+++ b/frontend/src/components/results/fixtures.ts
@@ -3,6 +3,7 @@
// the server copies it (or, for verification and files, from typed kwant data).
import type { ResultSet, SmartBlock } from '../../smartResults';
+import { recipe } from './recipeFixtures';
export interface Fixture {
/** The reply's markdown, as streamed and stored. */
@@ -297,4 +298,5 @@ export const FIXTURES = {
findings,
verification,
files,
+ recipe,
} satisfies Record<string, Fixture>;
diff --git a/frontend/src/components/results/recipeFixtures.ts b/frontend/src/components/results/recipeFixtures.ts
new file mode 100644
index 00000000..05bd377c
--- /dev/null
+++ b/frontend/src/components/results/recipeFixtures.ts
@@ -0,0 +1,210 @@
+// Recipe fixtures (design.md §9): the made-up "Golden squash and lentil stew" from Mira's mocks and its
+// edge states. Every value is the reply's text; qty + text is the reply's line (§11).
+
+import type { RecipeBlock, RecipeIngredient } from '../../smartResults';
+import type { Fixture } from './fixtures';
+
+type Line = [qty: string | null, text: string, group?: string];
+
+const ing = (lines: Line[]): RecipeIngredient[] => lines.map(([qty, text, group], i) => ({ id: `i${i + 1}`, qty, text, group: group ?? null }));
+const steps = (texts: string[]) => texts.map((text, i) => ({ id: `s${i + 1}`, text }));
+const join = (qty: string | null, text: string) => (!qty ? text : text.startsWith(',') ? qty + text : `${qty} ${text}`);
+
+const STEW_LINES: Line[] = [
+ ['1 tbsp', 'olive oil', 'For the stew'],
+ ['1 onion', ', diced', 'For the stew'],
+ ['2 cloves', 'garlic, crushed', 'For the stew'],
+ ['2 tsp', 'smoked paprika', 'For the stew'],
+ ['500 g', 'squash, peeled and cubed', 'For the stew'],
+ ['1 cup', 'red lentils, rinsed', 'For the stew'],
+ ['1 can', '(400 g) chopped tomatoes', 'For the stew'],
+ ['3 cups', 'vegetable stock', 'For the stew'],
+ [null, 'Salt to taste', 'For the stew'],
+ ['½ cup', 'plain yogurt', 'For the topping'],
+ ['1 lemon', ', zested', 'For the topping'],
+ ['2 tbsp', 'chopped parsley', 'For the topping'],
+ ['1–2 tsp', 'chili flakes', 'For the topping'],
+ [null, 'A pinch of flaky salt', 'For the topping'],
+];
+const STEW_STEPS = [
+ 'Warm the oil in a large pot over medium heat. Add the onion and cook for 5 minutes, until soft.',
+ 'Stir in the garlic and paprika and cook for 1 minute.',
+ 'Add the squash, lentils, tomatoes and stock, and bring to a boil.',
+ 'Lower the heat and simmer for 25 minutes, stirring now and then, until the lentils break down.',
+ 'Meanwhile, mix the yogurt with the lemon zest.',
+ 'Taste the stew and add salt.',
+ 'Serve with a spoon of the lemon yogurt, the parsley, the chili flakes and a pinch of flaky salt.',
+];
+const STEW_NOTES = [
+ 'Keeps 3 days in the fridge. It thickens, so add a splash of stock when you reheat it.',
+ 'Sweet potato works in place of the squash.',
+ 'Leave out the yogurt for a vegan version.',
+];
+
+/** The reply as the Chef bot wrote it, and its block. Lists: ul 0 (stew), ul 1 (topping), ol 0 (method), ul 2 (notes). */
+export function recipeFixture(over: Partial<RecipeBlock> = {}, lines: Line[] = STEW_LINES): Fixture {
+ const block: RecipeBlock = {
+ id: 'b-recipe',
+ type: 'recipe',
+ title: 'Golden squash and lentil stew',
+ source: { kind: 'markdown_section', index: 0, ordered: false, last_index: 2, last_ordered: false, lead: 4 },
+ provenance: { kind: 'reply_text' },
+ serves: 4,
+ times: [
+ { label: 'Prep', text: '15 min' },
+ { label: 'Cook', text: '35 min' },
+ ],
+ ingredients: ing(lines),
+ steps: steps(STEW_STEPS),
+ notes: STEW_NOTES,
+ ...over,
+ };
+ const groups: string[] = [];
+ for (const i of block.ingredients) if (i.group && !groups.includes(i.group)) groups.push(i.group);
+ const loose = block.ingredients.filter((i) => !i.group);
+ const list = (xs: RecipeIngredient[]) => xs.map((i) => `- ${join(i.qty, i.text)}`).join('\n');
+ const head = [block.serves ? `Serves ${block.serves}` : '', ...block.times.map((t) => `${t.label} ${t.text}`)].filter(Boolean).join(' · ');
+ const reply = [
+ 'Here is a cosy one-pot dinner for tonight.',
+ `## ${block.title ?? 'Recipe'}`,
+ ...(head ? [head] : []),
+ '### Ingredients',
+ ...(loose.length ? [list(loose)] : []),
+ ...groups.flatMap((g) => [`**${g}**`, list(block.ingredients.filter((i) => i.group === g))]),
+ '### Method',
+ block.steps.map((s, i) => `${i + 1}. ${s.text}`).join('\n'),
+ ...(block.notes.length ? ['### Notes', block.notes.map((n) => `- ${n}`).join('\n')] : []),
+ 'Want a quick flatbread to go with it?',
+ ].join('\n\n');
+ // Before the first list: the name, the head line, "Ingredients" and, when the list opens with a group, its label.
+ const lead = 2 + (head ? 1 : 0) + (!loose.length && groups.length ? 1 : 0);
+ const uls = (loose.length ? 1 : 0) + groups.length + (block.notes.length ? 1 : 0);
+ const first = loose.length || groups.length ? { index: 0, ordered: false } : { index: 0, ordered: true };
+ const last = block.notes.length ? { index: uls - 1, ordered: false } : { index: 0, ordered: true };
+ const source = { kind: 'markdown_section' as const, index: first.index, ordered: first.ordered, last_index: last.index, last_ordered: last.ordered, lead };
+ return { reply, results: { version: 1, blocks: [{ ...block, source }] } };
+}
+
+export const recipe = recipeFixture();
+
+/** E1–E6 and the fold (design §9). */
+export const RECIPE_EDGES = {
+ /** E1: a long name, three times, groups. */
+ longName: recipeFixture({
+ title: 'Slow-roasted golden squash, red lentil and smoked paprika stew with a bright lemon and herb yogurt',
+ times: [
+ { label: 'Prep', text: '15 min' },
+ { label: 'Cook', text: '35 min' },
+ { label: 'Total', text: '50 min' },
+ ],
+ }),
+ /** E2: no times. */
+ noTimes: recipeFixture({ title: 'Lemon yogurt dip', times: [], notes: [] }, [
+ ['½ cup', 'plain yogurt'],
+ ['1 lemon', ', zested'],
+ ['2 tbsp', 'chopped parsley'],
+ [null, 'Salt to taste'],
+ ]),
+ /** E3: no serves. */
+ noServes: recipeFixture({ title: 'Garlic flatbreads', serves: null, times: [{ label: 'Total', text: 'about 30 min' }], notes: [] }, [
+ ['2 cups', 'flour'],
+ ['1 tsp', 'baking powder'],
+ ['¾ cup', 'plain yogurt'],
+ ['2 cloves', 'garlic, grated'],
+ [null, 'A good pinch of salt'],
+ ]),
+ /** E3b: serves, but nothing can scale. */
+ nothingScales: recipeFixture({ title: 'Green salad', notes: [] }, [
+ [null, 'A head of lettuce'],
+ [null, 'A handful of soft herbs'],
+ [null, 'Olive oil and lemon to taste'],
+ ]),
+ /** E4: no serves, no times, no notes. */
+ bare: recipeFixture({ title: 'Herb oil', serves: null, times: [], notes: [], steps: steps(['Blend the herbs with the oil.', 'Strain through a fine sieve.']) }, [
+ ['½ cup', 'olive oil'],
+ [null, 'A handful of soft herbs'],
+ ]),
+ /** E6: 30 steps. */
+ thirty: recipeFixture({
+ title: 'Layered vegetable bake',
+ times: [
+ { label: 'Prep', text: '40 min' },
+ { label: 'Cook', text: '1 h 10 min' },
+ { label: 'Total', text: '1 h 50 min' },
+ ],
+ notes: [],
+ steps: steps(Array.from({ length: 30 }, (_, i) => `Step text for part ${i + 1} of the bake, kept short in this sheet.`)),
+ }),
+} satisfies Record<string, Fixture>;
+
+/** contract.md §3 exactly: Vega's backend unit test (recipe_tests::the_contract_example_is_exact). */
+export const RECIPE_CONTRACT: Fixture = {
+ reply: `Here's a cosy stew for tonight.
+
+## Golden squash and lentil stew
+
+**Serves 4** · Prep 15 min · Cook 35 min
+
+### Ingredients
+
+**For the stew**
+- 1 tbsp olive oil
+- 1 onion, diced
+- 2 cloves garlic, crushed
+- 500 g squash, peeled and cubed
+- 1 can (400 g) chopped tomatoes
+- Salt to taste
+
+**For the topping:**
+- ½ cup plain yogurt
+- 1–2 tsp chili flakes
+
+### Method
+
+1. Warm the oil in a large pot over medium heat. Add the onion and cook for 5 minutes, until soft.
+2. Stir in the garlic and cook for 1 minute.
+3. Add the squash and tomatoes and simmer for 25 minutes.
+4. Serve with the yogurt and chili flakes.
+
+### Notes
+
+- Keeps 3 days in the fridge.
+- Sweet potato works in place of the squash.
+
+Want a vegan version?
+`,
+ results: {
+ version: 1,
+ blocks: [
+ {
+ type: 'recipe',
+ id: 'b0',
+ title: 'Golden squash and lentil stew',
+ source: { kind: 'markdown_section', index: 0, ordered: false, last_index: 2, last_ordered: false, lead: 4 },
+ serves: 4,
+ times: [
+ { label: 'Prep', text: '15 min' },
+ { label: 'Cook', text: '35 min' },
+ ],
+ ingredients: [
+ { id: 'i0', text: 'olive oil', qty: '1 tbsp', group: 'For the stew' },
+ { id: 'i1', text: ', diced', qty: '1 onion', group: 'For the stew' },
+ { id: 'i2', text: 'garlic, crushed', qty: '2 cloves', group: 'For the stew' },
+ { id: 'i3', text: 'squash, peeled and cubed', qty: '500 g', group: 'For the stew' },
+ { id: 'i4', text: '(400 g) chopped tomatoes', qty: '1 can', group: 'For the stew' },
+ { id: 'i5', text: 'Salt to taste', qty: null, group: 'For the stew' },
+ { id: 'i6', text: 'plain yogurt', qty: '½ cup', group: 'For the topping' },
+ { id: 'i7', text: 'chili flakes', qty: '1–2 tsp', group: 'For the topping' },
+ ],
+ steps: [
+ { id: 's0', text: 'Warm the oil in a large pot over medium heat. Add the onion and cook for 5 minutes, until soft.' },
+ { id: 's1', text: 'Stir in the garlic and cook for 1 minute.' },
+ { id: 's2', text: 'Add the squash and tomatoes and simmer for 25 minutes.' },
+ { id: 's3', text: 'Serve with the yogurt and chili flakes.' },
+ ],
+ notes: ['Keeps 3 days in the fridge.', 'Sweet potato works in place of the squash.'],
+ provenance: { kind: 'reply_text' },
+ },
+ ],
+ },
+};
diff --git a/frontend/src/components/results/registry.ts b/frontend/src/components/results/registry.ts
index 3414e7ed..39d64db9 100644
--- a/frontend/src/components/results/registry.ts
+++ b/frontend/src/components/results/registry.ts
@@ -21,6 +21,7 @@ import { Cards, validCards } from './Cards';
import { Findings, validFindings } from './Findings';
import { Verification, validVerification } from './Verification';
import { Files, validFiles } from './Files';
+import { Recipe, validRecipe } from './Recipe';
/** One cell or list item of the reply as react-markdown drew it, plus its plain text for matching. */
export interface ReplyPart {
@@ -31,7 +32,9 @@ export interface ReplyPart {
/** The reply's own table or list that a block replaces in place. */
export type ReplySource =
| { kind: 'table'; head: ReplyPart[]; body: ReplyPart[][] }
- | { kind: 'list'; items: ReplyPart[]; start: number; ordered: boolean; task: boolean };
+ | { kind: 'list'; items: ReplyPart[]; start: number; ordered: boolean; task: boolean }
+ /** A stretch of the reply (a recipe, from its dish heading through its last list), as written. */
+ | { kind: 'section'; markdown: string };
export interface RendererProps<B extends SmartBlock = SmartBlock> {
block: B;
@@ -79,6 +82,7 @@ export const REGISTRY: { [T in BlockType]?: Renderer<BlockOf<T>> } = {
findings: { validate: validFindings, Component: Findings },
verification: { validate: validVerification, Component: Verification },
files: { validate: validFiles, Component: Files },
+ recipe: { validate: validRecipe, Component: Recipe },
};
const count = (block: SmartBlock): number | null => {
@@ -88,7 +92,7 @@ const count = (block: SmartBlock): number | null => {
/** Same number of rows (table) or items (list) as the block. */
export const defaultMatches = (block: SmartBlock, reply: ReplySource) =>
- reply.kind === 'table' ? reply.body.length === count(block) : reply.items.length === count(block);
+ reply.kind === 'section' ? true : reply.kind === 'table' ? reply.body.length === count(block) : reply.items.length === count(block);
/** The checked block and its renderer, or null: then the reply shows its markdown. */
export function resolveBlock(raw: unknown, reply: ReplySource | null): { block: SmartBlock; renderer: Renderer<SmartBlock> } | null {
@@ -99,6 +103,9 @@ export function resolveBlock(raw: unknown, reply: ReplySource | null): { block:
if (!renderer || !block) return null;
const src = block.source.kind;
if (!reply) return src === 'slot' ? { block, renderer } : null;
+ // The section was found in the reply and cut out for this block; it stands for that stretch.
+ if ((src === 'markdown_section') !== (reply.kind === 'section')) return null;
+ if (reply.kind === 'section') return { block, renderer };
if ((src === 'markdown_table') !== (reply.kind === 'table') || src === 'slot') return null;
return (renderer.matches ?? defaultMatches)(block, reply) ? { block, renderer } : null;
}
diff --git a/frontend/src/dev/ticketFixtures.ts b/frontend/src/dev/ticketFixtures.ts
index 8d99a5b1..40f2eb88 100644
--- a/frontend/src/dev/ticketFixtures.ts
+++ b/frontend/src/dev/ticketFixtures.ts
@@ -78,6 +78,11 @@ export function ticket(state: TicketState, extra: Record<string, unknown> & { wo
return { ...base, state, ...back, ...at, ...err, ...rest, work: w };
}
+/** D6 (next-076/jira-tickets/d6-contract.md): the lead's engine can't prepare a brief (Grok, Custom API, or
+ * tool checks off), so the brief turn was refused before it read anything. The card shows the server's
+ * `message` as is; the contract's sentence lives in tests/fixtures/tickets.mjs, so pass it in. */
+export const TICKET_ENGINE_REFUSED = (message: string) => ticket('failed', { error: { code: 'engine_refused', message } });
+
export const TICKET_151 = {
...base,
key: 'TRAIL-151',
diff --git a/frontend/src/gettingStarted.ts b/frontend/src/gettingStarted.ts
new file mode 100644
index 00000000..271a46c6
--- /dev/null
+++ b/frontend/src/gettingStarted.ts
@@ -0,0 +1,490 @@
+// 0.7.6 O2 "Get started": the one stepped card in #general (Choose your AI → Sign in → Pick a team).
+// Design: next-076/onboarding/design.md §3–§13, Ada's C1–C6 in review.md. This file is the logic only
+// (which step is open, the words for each state, the sign-in API for three engines); the card is
+// components/GetStarted.tsx. Installed and signed-in always come from the server (/api/engines,
+// /api/setup/status), so a reopened app resumes where it was; only the chosen AI and "dismissed" are
+// kept in this browser.
+
+import type { EngineId, EngineInfo } from './engines';
+import { isUsable } from './engines';
+import type { SetupItem } from './setupInstall';
+
+/** The four tiles (design §5.1). */
+export type AiChoice = 'claude' | 'codex' | 'grok' | 'key';
+/** Engines that sign in inside the app (Lin's O3 routes). */
+export type LoginEngine = 'claude' | 'codex' | 'grok';
+
+export const CHOICES: Array<{ id: AiChoice; name: string; line: string }> = [
+ { id: 'claude', name: 'Claude', line: 'Claude Pro or Max plan' },
+ { id: 'codex', name: 'ChatGPT', line: 'Your ChatGPT plan, through Codex' },
+ { id: 'grok', name: 'Grok', line: 'Your Grok account' },
+ { id: 'key', name: 'API key', line: 'Anthropic, OpenAI or xAI' },
+];
+
+export const choiceName = (c: AiChoice) => CHOICES.find((x) => x.id === c)?.name ?? c;
+/** What the CLI is called while it is being got ready ("Getting Claude ready…"). */
+export const cliName = (c: LoginEngine) => (c === 'codex' ? 'Codex' : c === 'grok' ? 'Grok' : 'Claude');
+
+const KEY_ENGINES: EngineId[] = ['anthropic_api', 'openai_api', 'xai_api'];
+/** Today's engine order, for "already signed in" when several are (design §5.1). */
+const ORDER: EngineId[] = ['claude', 'codex', 'grok', 'anthropic_api', 'openai_api', 'xai_api'];
+
+/** The tile an engine belongs to. Ollama and custom APIs aren't tiles; they still count as "can run". */
+export const choiceOf = (id: EngineId): AiChoice | null =>
+ id === 'claude' || id === 'codex' || id === 'grok' ? id : KEY_ENGINES.includes(id) ? 'key' : null;
+
+/** The first tile that can already run, in today's engine order; null when none. */
+export function readyChoice(engines: EngineInfo[] | null | undefined): AiChoice | null {
+ if (!engines) return null;
+ for (const id of ORDER) {
+ const e = engines.find((x) => x.id === id);
+ if (e && isUsable(e)) return choiceOf(id);
+ }
+ return null;
+}
+
+/** What a tile says under its line (design §5.1, T3): signed in, installed but signed out, or nothing. */
+export type TileStatus = 'signed_in' | 'installed' | null;
+export function tileStatus(engines: EngineInfo[] | null | undefined, c: AiChoice): TileStatus {
+ if (!engines) return null;
+ if (c === 'key') return engines.some((e) => KEY_ENGINES.includes(e.id) && isUsable(e)) ? 'signed_in' : null;
+ const e = engines.find((x) => x.id === c);
+ if (!e || e.enabled === false) return null;
+ if (isUsable(e)) return 'signed_in';
+ return e.status === 'signed_out' ? 'installed' : null;
+}
+
+/** Whether the chosen AI's CLI still has to be installed before it can sign in. */
+export function needsInstall(engines: EngineInfo[] | null | undefined, c: AiChoice): boolean {
+ if (c === 'key' || !engines) return false;
+ const e = engines.find((x) => x.id === c);
+ return !e || e.status === 'not_installed';
+}
+
+/** Whether the server can install it here (setup status); null while unknown. */
+export function installable(items: SetupItem[] | null, c: AiChoice): boolean | null {
+ if (c === 'key') return false;
+ if (!items) return null;
+ const row = items.find((i) => i.id === c);
+ return !!row && (row.state !== 'missing' || row.can_install);
+}
+
+export type StepNo = 1 | 2 | 3;
+
+export interface StepsInput {
+ engines: EngineInfo[] | null;
+ /** The tile the person picked (stored); null before. */
+ chosen: AiChoice | null;
+ /** Step 3 was opened early while an install is slow (F8). */
+ teamEarly?: boolean;
+ /** The person pressed Change on step 1. */
+ changing?: boolean;
+}
+
+export interface StepsView {
+ open: StepNo;
+ /** Step 1 shows as done, with this value ("Claude, installed"). */
+ done1: boolean;
+ done2: boolean;
+ /** The AI the card is about: the stored choice, or the one found signed in. */
+ choice: AiChoice | null;
+ /** D2: nothing was chosen here and an account already worked on first look. */
+ foundReady: boolean;
+}
+
+/**
+ * Which step is open (design §3). Exactly one is. Steps never go backwards by themselves: once the
+ * chosen AI can run, steps 1–2 are done and 3 is open; Change reopens 1.
+ */
+export function stepsView({ engines, chosen, teamEarly = false, changing = false }: StepsInput): StepsView {
+ const ready = readyChoice(engines);
+ const choice = chosen ?? ready;
+ const foundReady = !chosen && !!ready;
+ const chosenReady = !!choice && tileStatus(engines, choice) === 'signed_in';
+ if (changing) return { open: 1, done1: false, done2: false, choice, foundReady };
+ if (chosenReady) return { open: 3, done1: true, done2: true, choice, foundReady };
+ if (!choice) return { open: 1, done1: false, done2: false, choice, foundReady };
+ return { open: teamEarly ? 3 : 2, done1: true, done2: false, choice, foundReady };
+}
+
+/** Step 1's value when done ("Claude, installed" / "Claude, already signed in on this Mac"). */
+export function step1Value(v: StepsView, engines: EngineInfo[] | null, where: string): string {
+ if (!v.choice) return '';
+ const name = choiceName(v.choice);
+ if (v.foundReady) return `${name}, already signed in ${where}`;
+ if (v.choice === 'key') return name;
+ return needsInstall(engines, v.choice) ? name : `${name}, installed`;
+}
+
+/** "on this Mac", "on this computer", or "on {host}" for a server opened on a phone (design §10). */
+export function whereLabel(opts: { host?: string | null; mac?: boolean }): string {
+ if (opts.host) return `on ${opts.host}`;
+ return opts.mac ? 'on this Mac' : 'on this computer';
+}
+
+/** The hero's title and subtitle (design §4). */
+export function heroText(v: StepsView, opts: { host?: string | null; mac?: boolean }): { title: string; sub: string } {
+ const name = v.choice ? choiceName(v.choice) : '';
+ if (v.open === 3 && v.done2 && v.foundReady)
+ return {
+ title: `${name} is ready ${opts.host ? `on ${opts.host}` : opts.mac ? 'on this Mac' : 'on this computer'}`,
+ sub: 'You were already signed in. Pick a team and say hello.',
+ };
+ if (v.open === 3 && v.done2) return { title: `${name} is ready`, sub: 'Last step: who should your bots be?' };
+ return {
+ title: 'Welcome to kwant bots',
+ sub: opts.host
+ ? 'Choose your AI and sign in. It installs on your server, not on this phone.'
+ : 'Choose your AI and sign in. The rest installs by itself.',
+ };
+}
+
+// ------------------------------------------------------------------ install failures (design §9)
+
+export type InstallFailKind = 'offline' | 'network' | 'disk' | 'permission' | 'other';
+
+/** The job's error and last lines mapped to one of four kinds; the raw text only goes to Copy details. */
+export function installFailKind(text: string | null | undefined, online = true): InstallFailKind {
+ if (!online) return 'offline';
+ const t = (text || '').toLowerCase();
+ if (/no space|enospc|disk full|not enough (free )?space/.test(t)) return 'disk';
+ if (/sudo|permission denied|eacces|operation not permitted|needs? root|as root/.test(t)) return 'permission';
+ if (/could not resolve|network|timed out|timeout|connection (reset|refused)|econn|enotfound|curl: \(\d+\)|tls|ssl|download/.test(t)) return 'network';
+ return 'other';
+}
+
+export interface FailView {
+ tone: 'warn' | 'bad';
+ title: string;
+ reason: string;
+}
+
+export function installFailView(kind: InstallFailKind, name: string, where: string, host?: string | null): FailView {
+ const onHost = host ? ` on ${host}` : '';
+ switch (kind) {
+ case 'offline':
+ return { tone: 'warn', title: `You’re offline, so ${name} can’t download yet.`, reason: 'It starts again by itself when you’re back online.' };
+ case 'network':
+ return { tone: 'bad', title: `Couldn’t get ${name} ready${onHost}.`, reason: 'The download stopped partway. Your connection may have dropped.' };
+ case 'disk':
+ return { tone: 'bad', title: `Couldn’t get ${name} ready${onHost}.`, reason: 'There isn’t enough free space. Free some up, then try again.' };
+ case 'permission':
+ return { tone: 'bad', title: `Couldn’t get ${name} ready${onHost}.`, reason: `It needs an admin step ${where}. Copy details shows what went wrong.` };
+ default:
+ return { tone: 'bad', title: `Something went wrong while getting ${name} ready.`, reason: 'Try again, or copy the details for help.' };
+ }
+}
+
+// ------------------------------------------------------------------ sign-in for three engines (O3)
+
+export type LoginState =
+ | 'starting'
+ | 'waiting_for_code'
+ | 'waiting_for_approval'
+ | 'verifying'
+ | 'done'
+ | 'failed'
+ | 'expired'
+ | 'cancelled';
+
+/** SessionView from o3-api.md. Claude on an older server has no `kind`, `engine` or `user_code`. */
+export interface LoginSession {
+ session_id: string;
+ engine?: LoginEngine;
+ kind?: 'device_code' | 'paste_code';
+ state: LoginState;
+ detail: string | null;
+ url: string | null;
+ user_code?: string | null;
+ expires_at: string | null;
+}
+
+export class LoginError extends Error {
+ constructor(
+ message: string,
+ readonly status: number,
+ readonly sessionId: string | null = null,
+ ) {
+ super(message);
+ }
+}
+
+export const isLive = (s: LoginState) => s === 'starting' || s === 'waiting_for_code' || s === 'waiting_for_approval' || s === 'verifying';
+
+export interface LoginApi {
+ start: (engine: LoginEngine) => Promise<LoginSession>;
+ get: (engine: LoginEngine, sid: string) => Promise<LoginSession>;
+ cancel: (engine: LoginEngine, sid: string) => Promise<void>;
+ submitCode: (engine: LoginEngine, sid: string, code: string) => Promise<LoginSession>;
+}
+
+async function call<T>(method: string, path: string, body?: unknown, send: typeof fetch = (...a) => fetch(...a)): Promise<T> {
+ let r: Response;
+ try {
+ r = await send(path, {
+ method,
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new LoginError('Couldn’t reach the server.', 0);
+ }
+ if (r.status === 204) return undefined as T;
+ const d = await r.json().catch(() => null);
+ if (!r.ok) {
+ throw new LoginError(typeof d?.error === 'string' && d.error ? d.error : `HTTP ${r.status}`, r.status, typeof d?.session_id === 'string' ? d.session_id : null);
+ }
+ return d as T;
+}
+
+export const makeLoginApi = (send?: typeof fetch): LoginApi => {
+ const base = (e: LoginEngine) => `/api/engines/${e}/login`;
+ return {
+ start: (e) => call('POST', base(e), undefined, send),
+ get: (e, sid) => call('GET', `${base(e)}/${encodeURIComponent(sid)}`, undefined, send),
+ cancel: (e, sid) => call('DELETE', `${base(e)}/${encodeURIComponent(sid)}`, undefined, send),
+ submitCode: (e, sid, code) => call('POST', `${base(e)}/${encodeURIComponent(sid)}/code`, { code }, send),
+ };
+};
+export const loginApi = makeLoginApi();
+
+/** Starts a sign-in, or picks up the one already running (409 with its session id; F7). */
+export async function startOrResume(api: LoginApi, engine: LoginEngine): Promise<LoginSession> {
+ try {
+ return await api.start(engine);
+ } catch (e) {
+ if (e instanceof LoginError && e.status === 409 && e.sessionId) return api.get(engine, e.sessionId);
+ throw e;
+ }
+}
+
+/** Whether this server has the in-app device sign-in (O3): false on a 404 for the engine's route. */
+export const noDeviceRoute = (e: unknown) => e instanceof LoginError && e.status === 404;
+
+/** The page to open, shown without https:// and without the query ("chatgpt.com/device"). */
+export function deviceLabel(url: string | null | undefined): string | null {
+ if (!url) return null;
+ try {
+ const u = new URL(url);
+ if (u.protocol !== 'https:') return null;
+ const path = u.pathname.replace(/\/$/, '');
+ return `${u.hostname.replace(/^www\./, '')}${path}`;
+ } catch {
+ return null;
+ }
+}
+
+/** Only https links are opened; for device codes, only the engines' own sign-in hosts. */
+export function isSignInUrl(engine: LoginEngine, url: string | null | undefined): url is string {
+ if (!url) return false;
+ try {
+ const u = new URL(url);
+ if (u.protocol !== 'https:') return false;
+ const hosts =
+ engine === 'claude'
+ ? /(^|\.)(claude\.ai|claude\.com|anthropic\.com)$/
+ : engine === 'codex'
+ ? /(^|\.)(openai\.com|chatgpt\.com)$/
+ : /(^|\.)(x\.ai|grok\.com|x\.com)$/;
+ return hosts.test(u.hostname);
+ } catch {
+ return false;
+ }
+}
+
+/** "Code K 7 Q F, 2 M X D": read out one character at a time, groups split by a pause (design §13). */
+export function codeAriaLabel(code: string): string {
+ const groups = code
+ .trim()
+ .split(/[-\s]+/)
+ .filter(Boolean)
+ .map((g) => g.split('').join(' '));
+ return `Code ${groups.join(', ')}`;
+}
+
+/** Whole minutes left on a code, for "The code works for 15 minutes." null without an expiry. */
+export function minutesLeft(expiresAt: string | null | undefined, now: number): number | null {
+ if (!expiresAt) return null;
+ const t = Date.parse(expiresAt);
+ if (!Number.isFinite(t)) return null;
+ return Math.max(0, Math.ceil((t - now) / 60000));
+}
+
+/** A pasted Claude code with spaces or a newline, trimmed to one token (design §5.3). */
+export const cleanPastedCode = (raw: string) => raw.replace(/\s+/g, '');
+
+/** What a finished sign-in that didn't sign in shows (design §9 F3, F4, F6). */
+export interface SignInEnd {
+ kind: 'cancelled' | 'expired' | 'failed';
+ tone: 'neutral' | 'bad';
+ title: string;
+ reason: string | null;
+ action: string;
+}
+export function signInEnd(s: Pick<LoginSession, 'state' | 'detail'>, engine: LoginEngine): SignInEnd | null {
+ const name = cliName(engine);
+ switch (s.state) {
+ case 'cancelled':
+ return { kind: 'cancelled', tone: 'neutral', title: 'Sign-in stopped. Nothing was saved.', reason: 'You can start again whenever you like.', action: 'Start again' };
+ case 'expired':
+ return engine === 'claude'
+ ? { kind: 'expired', tone: 'neutral', title: 'That sign-in timed out.', reason: 'Start it again to get a fresh link.', action: 'Start again' }
+ : { kind: 'expired', tone: 'neutral', title: 'That code expired.', reason: s.detail || 'Get a new code to try again.', action: 'Get a new code' };
+ case 'failed':
+ return {
+ kind: 'failed',
+ tone: 'bad',
+ title: /can’t use this account|can't use this account/i.test(s.detail || '') ? `Signed in, but ${name} can’t use this account.` : 'Sign-in didn’t finish.',
+ reason: s.detail,
+ action: 'Try again',
+ };
+ default:
+ return null;
+ }
+}
+
+// ------------------------------------------------------------------ the banner outside #general (§7.1)
+
+export type Phase =
+ | { kind: 'choose' }
+ | { kind: 'installing'; seconds: number }
+ | { kind: 'signin' }
+ | { kind: 'failed' }
+ | { kind: 'done' };
+
+export interface BannerView {
+ title: string;
+ /** Phones show only this. */
+ short: string;
+ sub: string | null;
+ button: 'Open' | 'Continue';
+ spinner: boolean;
+}
+
+export function bannerView(phase: Phase, choice: AiChoice | null): BannerView | null {
+ const name = choice && choice !== 'key' ? cliName(choice) : choice ? 'your key' : 'your AI';
+ switch (phase.kind) {
+ case 'choose':
+ return { title: 'Getting started · Choose your AI', short: 'Getting started · Choose your AI', sub: 'One tap installs it.', button: 'Open', spinner: false };
+ case 'installing':
+ return {
+ title: `Getting started · Getting ${name} ready… ${phase.seconds} s`,
+ short: `Getting ${name} ready… ${phase.seconds} s`,
+ sub: 'Then sign in, and your bots can answer.',
+ button: 'Open',
+ spinner: true,
+ };
+ case 'signin':
+ return choice === 'key'
+ ? { title: 'Getting started · Add your key', short: 'Getting started · Add your key', sub: 'One key and your bots can answer.', button: 'Continue', spinner: false }
+ : {
+ title: `Getting started · Sign in to ${name}`,
+ short: `Sign in to ${name}`,
+ sub: `${name} is installed. One sign-in and your bots can answer.`,
+ button: 'Continue',
+ spinner: false,
+ };
+ case 'failed':
+ return { title: `Getting started · Couldn’t get ${name} ready`, short: `Couldn’t get ${name} ready`, sub: null, button: 'Open', spinner: false };
+ default:
+ return null;
+ }
+}
+
+// ------------------------------------------------------------------ what this browser keeps (§11)
+
+const startListeners = new Set<() => void>();
+let startVersion = 0;
+/** Something this browser keeps about getting started changed (choice, kept, dismissed). */
+export const onStartChange = (l: () => void) => {
+ startListeners.add(l);
+ return () => void startListeners.delete(l);
+};
+export const getStartVersion = () => startVersion;
+const changed = () => {
+ startVersion++;
+ startListeners.forEach((l) => l());
+};
+
+const dismissKey = (space: string) => `kwnt:getting-started:${space}`;
+const startKey = (space: string) => `kwnt:start:${space}`;
+
+const store = (): Storage | null => {
+ try {
+ return typeof localStorage === 'undefined' ? null : localStorage;
+ } catch {
+ return null;
+ }
+};
+
+export const isDismissed = (space: string) => store()?.getItem(dismissKey(space)) === 'dismissed';
+/** The card was shown here before (so it stays until dismissed, C4, even once an account works). */
+export const wasStarted = (space: string) => {
+ const v = store()?.getItem(dismissKey(space));
+ return v === 'open' || v === 'kept';
+};
+/** "Keep the starter bots" pressed before sign-in finished: step 3 is done, the card waits for step 2. */
+export const isKept = (space: string) => store()?.getItem(dismissKey(space)) === 'kept';
+export function markStarted(space: string, value: 'open' | 'kept' = 'open') {
+ try {
+ const cur = store()?.getItem(dismissKey(space));
+ if (cur === 'dismissed' || (cur === 'kept' && value === 'open')) return;
+ store()?.setItem(dismissKey(space), value);
+ } catch {
+ /* nothing to keep */
+ }
+ changed();
+}
+export function dismiss(space: string) {
+ try {
+ store()?.setItem(dismissKey(space), 'dismissed');
+ store()?.removeItem(startKey(space));
+ } catch {
+ /* private mode: the card goes on the next message anyway */
+ }
+ changed();
+}
+export function storedChoice(space: string): AiChoice | null {
+ const v = store()?.getItem(startKey(space));
+ return v === 'claude' || v === 'codex' || v === 'grok' || v === 'key' ? v : null;
+}
+export function storeChoice(space: string, c: AiChoice | null) {
+ try {
+ if (c) store()?.setItem(startKey(space), c);
+ else store()?.removeItem(startKey(space));
+ } catch {
+ /* nothing to keep */
+ }
+ changed();
+}
+
+/**
+ * Whether #general shows the card (C4): not dismissed here, and either nothing can run yet or the
+ * card was started here, or #general is still empty in a space with only the starter team (a fresh install that
+ * found an account already signed in, D2). An older install with any history never sees it.
+ */
+export function showCard(opts: { dismissed: boolean; canRun: boolean | null; generalMessages: number; teams: number; started: boolean }): boolean {
+ if (opts.dismissed) return false;
+ if (opts.canRun === false || opts.started) return true;
+ if (opts.canRun === null) return false;
+ // A fresh install comes with one starter team (core-engineering), so one team still counts as fresh.
+ return opts.generalMessages === 0 && opts.teams <= 1;
+}
+
+/**
+ * Whether What's new may treat this person as someone who has used kwant (true), as brand new (false: the
+ * version is recorded silently), or can't tell yet (null: wait). Get started wins (F-1): a fresh install that
+ * found an AI already signed in gets the card, never the sheet on top of it. Until the space and the open
+ * chat's messages have loaded, an upgrading user could look new, so the answer waits.
+ */
+export function whatsNewEstablished(opts: {
+ loaded: boolean;
+ messagesLoaded: boolean;
+ canRun: boolean | null;
+ wroteHere: boolean;
+ getStartedShowing: boolean;
+}): boolean | null {
+ if (opts.wroteHere) return true;
+ if (!opts.loaded || opts.canRun == null || !opts.messagesLoaded) return null;
+ return opts.canRun === true && !opts.getStartedShowing;
+}
diff --git a/frontend/src/gettingStartedInstall.ts b/frontend/src/gettingStartedInstall.ts
new file mode 100644
index 00000000..def0b064
--- /dev/null
+++ b/frontend/src/gettingStartedInstall.ts
@@ -0,0 +1,159 @@
+// O2: the install inside step 2 (design §5.2, §9 F1/F2/F2c/F7/F8). It lives outside the card so it keeps
+// going when the person leaves #general, and the banner there can show "Getting Claude ready… 9 s".
+// One tracker per space; the card and the banner read it with useInstallTrack.
+
+import { useSyncExternalStore } from 'react';
+import { type SetupApi, setupApi } from './setupInstall';
+import { type InstallFailKind, type LoginEngine, getStartVersion, installFailKind, onStartChange } from './gettingStarted';
+
+export interface ManualStep {
+ label: string;
+ command: string;
+}
+
+export interface InstallTrack {
+ item: LoginEngine;
+ state: 'running' | 'done' | 'failed' | 'needs_admin';
+ startedAt: number;
+ /** The job's lines, only for Copy details; never shown in the card. */
+ lines: string[];
+ error: string | null;
+ kind: InstallFailKind | null;
+ manual: ManualStep[];
+}
+
+const tracks = new Map<string, InstallTrack>();
+const listeners = new Set<() => void>();
+const emit = () => listeners.forEach((l) => l());
+const runs = new Map<string, number>();
+
+export const getTrack = (space: string): InstallTrack | null => tracks.get(space) ?? null;
+const set = (space: string, t: InstallTrack | null) => {
+ if (t) tracks.set(space, t);
+ else tracks.delete(space);
+ emit();
+};
+
+export function subscribeTracks(l: () => void) {
+ listeners.add(l);
+ return () => void listeners.delete(l);
+}
+
+export const useInstallTrack = (space: string) =>
+ useSyncExternalStore(
+ subscribeTracks,
+ () => getTrack(space),
+ () => getTrack(space),
+ );
+
+/** Forget it (Change, or another AI chosen): a running job keeps running on the server, it just isn't shown. */
+export function forgetInstall(space: string) {
+ runs.set(space, (runs.get(space) ?? 0) + 1);
+ set(space, null);
+}
+
+export interface RunOpts {
+ api?: SetupApi;
+ sleep?: (ms: number) => Promise<void>;
+ now?: () => number;
+ online?: () => boolean;
+ pollMs?: number;
+ busyMs?: number;
+ /** Called once the CLI is installed (read the engines again). */
+ onDone?: () => void;
+}
+
+const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
+const isOnline = () => (typeof navigator === 'undefined' ? true : navigator.onLine !== false);
+
+/**
+ * Installs `item` and follows the job. 409 (another install runs, e.g. one started before the app was
+ * closed, F7) is waited out and tried again. 422 with manual steps is F2c: it is shown with its command
+ * and the status is read every few seconds until the part is there.
+ */
+export async function startInstall(space: string, item: LoginEngine, opts: RunOpts = {}): Promise<InstallTrack> {
+ const api = opts.api ?? setupApi;
+ const sleep = opts.sleep ?? wait;
+ const now = opts.now ?? Date.now;
+ const online = opts.online ?? isOnline;
+ const pollMs = opts.pollMs ?? 1000;
+ const busyMs = opts.busyMs ?? 3000;
+ const run = (runs.get(space) ?? 0) + 1;
+ runs.set(space, run);
+ const live = () => runs.get(space) === run;
+ const prev = getTrack(space);
+ const startedAt = prev && prev.item === item && prev.state === 'running' ? prev.startedAt : now();
+ let t: InstallTrack = { item, state: 'running', startedAt, lines: [], error: null, kind: null, manual: [] };
+ const put = (patch: Partial<InstallTrack>) => {
+ t = { ...t, ...patch };
+ if (live()) set(space, t);
+ return t;
+ };
+ put({});
+ const fail = (error: string | null) => put({ state: 'failed', error, kind: installFailKind([error, ...t.lines.slice(-3)].join('\n'), online()) });
+ try {
+ if (!online()) return fail('offline');
+ let started: { status: number; body: any };
+ for (;;) {
+ started = await api.install(item);
+ if (!live()) return t;
+ if (started.status !== 409) break;
+ await sleep(busyMs);
+ if (!live()) return t;
+ }
+ if (started.status === 200) {
+ put({ state: 'done' });
+ opts.onDone?.();
+ return t;
+ }
+ if (started.status === 422) {
+ const manual: ManualStep[] = Array.isArray(started.body?.manual)
+ ? started.body.manual.filter((m: any) => typeof m?.command === 'string').map((m: any) => ({ label: String(m.label ?? ''), command: m.command }))
+ : [];
+ put({ state: 'needs_admin', manual, error: typeof started.body?.error === 'string' ? started.body.error : null });
+ // Checks every few seconds; moves on by itself once the part is there.
+ for (;;) {
+ await sleep(4000);
+ if (!live()) return t;
+ try {
+ const items = await api.status();
+ const row = items.find((i) => i.id === item);
+ if (row && row.state !== 'missing') {
+ put({ state: 'done' });
+ opts.onDone?.();
+ return t;
+ }
+ } catch {
+ /* look again */
+ }
+ }
+ }
+ if (started.status !== 202 || !started.body?.job_id) return fail(typeof started.body?.error === 'string' ? started.body.error : `HTTP ${started.status}`);
+ const id: string = started.body.job_id;
+ let after = 0;
+ for (;;) {
+ const job = await api.job(id, after);
+ if (!live()) return t;
+ if (job.lines?.length) put({ lines: [...t.lines, ...job.lines].slice(-200) });
+ after = typeof job.next === 'number' ? job.next : after;
+ if (job.state === 'done') {
+ put({ state: 'done' });
+ opts.onDone?.();
+ return t;
+ }
+ if (job.state === 'failed') return fail(job.error ?? null);
+ await sleep(pollMs);
+ }
+ } catch (e) {
+ if (!live()) return t;
+ return fail(e instanceof Error ? e.message : null);
+ }
+}
+
+/** Copy details: what went wrong, for a support message. Never shown in the card. */
+export function installDetails(t: InstallTrack): string {
+ return [`Getting ${t.item} ready failed.`, t.error ? `Error: ${t.error}` : null, ...t.lines.slice(-40)].filter(Boolean).join('\n');
+}
+
+/** Re-renders when the stored choice, "kept" or "dismissed" changes in this browser. */
+export const useStartVersion = () => useSyncExternalStore(onStartChange, getStartVersion, getStartVersion);
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 73a0d2b1..3db6cfdb 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -14,6 +14,7 @@ import './styles/devStatus.css';
import './styles/tickets.css';
import './styles/telegram.css';
import './styles/showOnce.css';
+import './styles/gettingStarted.css';
registerServiceWorker();
captureInstallPrompt();
diff --git a/frontend/src/recipe.ts b/frontend/src/recipe.ts
new file mode 100644
index 00000000..541086f4
--- /dev/null
+++ b/frontend/src/recipe.ts
@@ -0,0 +1,260 @@
+// The recipe Smart Results card (0.7.6, next-076/recipe-result/design.md): scaling a leading amount,
+// the ticks and servings kept per message on this device, and the two things the card copies.
+// Every number on the card is the reply's, or the reply's amount times shown / serves (§3). Nothing else
+// is computed.
+
+import { useCallback, useEffect, useState } from 'react';
+import type { RecipeBlock, RecipeIngredient } from './smartResults';
+import { plainText } from './smartResults';
+
+// ---------------------------------------------------------------------------------------------------
+// Scaling (design §3; the reference is scaleQty() in design/recipe.html)
+
+const GLYPH: Record<string, number> = { '¼': 1 / 4, '½': 1 / 2, '¾': 3 / 4, '⅓': 1 / 3, '⅔': 2 / 3, '⅛': 1 / 8 };
+const NUM = '(?:\\d{1,3}(?:,\\d{3})+(?![\\d.,])|\\d+\\s+\\d+\\/\\d+|\\d+\\/\\d+|\\d+(?:[.,]\\d+)?(?:\\s*[¼½¾⅓⅔⅛])?|[¼½¾⅓⅔⅛])';
+const LEAD = new RegExp(`^(${NUM})(?:\\s*[–-]\\s*(${NUM}))?`);
+
+/** The value of one amount as written: "2", "1.5", "1,5", "1/2", "1 1/2", "½", "1½". */
+export function amountValue(s: string): number {
+ const t = s.trim();
+ let m: RegExpMatchArray | null;
+ // "1,000": a comma before exactly three digits is a thousands separator (contract §1); "1,5" is 1.5.
+ if (/^\d{1,3}(?:,\d{3})+$/.test(t)) return +t.replace(/,/g, '');
+ if ((m = t.match(/^(\d+)\s+(\d+)\/(\d+)$/))) return +m[1] + +m[2] / +m[3];
+ if ((m = t.match(/^(\d+)\/(\d+)$/))) return +m[1] / +m[2];
+ if ((m = t.match(/^(\d+(?:[.,]\d+)?)\s*([¼½¾⅓⅔⅛])$/))) return +m[1].replace(',', '.') + GLYPH[m[2]];
+ if (GLYPH[t] !== undefined) return GLYPH[t];
+ return +t.replace(',', '.');
+}
+
+/**
+ * A scaled amount written for a cook: 10 or more is a whole number; under 10 it snaps to ¼ ⅓ ½ ⅔ ¾ (and ⅛
+ * below 1) when within 0.07, written as a whole number plus a glyph; otherwise one decimal with a dot.
+ * A non-zero amount never shows as 0 (F-3): down to 1/16 it reads ⅛; below that there is nothing a cook
+ * can measure, so the result is null and the caller keeps the reply's own amount.
+ */
+export function formatAmount(v: number): string | null {
+ if (v >= 10) return String(Math.round(v));
+ const w = Math.floor(v);
+ const f = v - w;
+ const C: [number, string][] = [[0, ''], ...(w === 0 ? ([[1 / 8, '⅛']] as [number, string][]) : []), [1 / 4, '¼'], [1 / 3, '⅓'], [1 / 2, '½'], [2 / 3, '⅔'], [3 / 4, '¾'], [1, '']];
+ let best = C[0];
+ for (const c of C) if (Math.abs(f - c[0]) < Math.abs(f - best[0])) best = c;
+ if (Math.abs(f - best[0]) > 0.07) return (Math.round(v * 10) / 10).toString();
+ const whole = best[0] === 1 ? w + 1 : w;
+ const out = (whole ? String(whole) : '') + best[1];
+ if (out) return out;
+ if (v <= 0) return '0';
+ return v >= 1 / 16 ? '⅛' : null;
+}
+
+/** 1500 as "1,500" when the reply wrote its amount with a thousands comma ("1,000 g"); otherwise as is. */
+const withThousands = (written: string, out: string) =>
+ /^\d{1,3}(?:,\d{3})+$/.test(written.trim()) && /^\d{4,}$/.test(out) ? out.replace(/\B(?=(\d{3})+$)/g, ',') : out;
+
+// Units flip whatever follows ("1 cup flour" → "2 cups flour"). Things counted flip only when they end
+// the amount's line or a comma or bracket follows ("1 onion, diced"); another word after them is the noun
+// ("1 egg yolk" → "1½ egg yolk", never "eggs yolk"; F-3).
+const UNIT_PLURAL: Record<string, string> = {
+ cup: 'cups', clove: 'cloves', can: 'cans', tablespoon: 'tablespoons', teaspoon: 'teaspoons', slice: 'slices', stick: 'sticks', sprig: 'sprigs',
+};
+const THING_PLURAL: Record<string, string> = { onion: 'onions', lemon: 'lemons', egg: 'eggs', carrot: 'carrots', potato: 'potatoes', tomato: 'tomatoes' };
+const PLURAL: Record<string, string> = { ...UNIT_PLURAL, ...THING_PLURAL };
+const SINGULAR: Record<string, string> = Object.fromEntries(Object.entries(PLURAL).map(([a, b]) => [b, a]));
+const THINGS = new Set([...Object.keys(THING_PLURAL), ...Object.values(THING_PLURAL)]);
+
+/**
+ * An ingredient's leading amount at factor k. Only a leading number, fraction or range changes (both
+ * ends of a range); the word right after it flips singular/plural from a fixed list; everything else
+ * stays exactly as written. `after` is the rest of the line (the ingredient's text), which decides
+ * whether a counted thing is followed by another noun. `scaled` is false when nothing changed hands
+ * (k = 1, nothing to scale, or an amount too small to write).
+ */
+export function scaleQty(qty: string, k: number, after = ''): { qty: string; scaled: boolean } {
+ const m = qty.match(LEAD);
+ if (!m || k === 1) return { qty, scaled: false };
+ const a = amountValue(m[1]) * k;
+ const b = m[2] ? amountValue(m[2]) * k : null;
+ if (!Number.isFinite(a) || (b !== null && !Number.isFinite(b))) return { qty, scaled: false };
+ const fa = formatAmount(a);
+ const fb = b !== null ? formatAmount(b) : null;
+ if (fa === null || (b !== null && fb === null)) return { qty, scaled: false };
+ const top = b ?? a;
+ const nounFollows = /^\s*\p{L}/u.test(after);
+ const rest = qty.slice(m[0].length).replace(/^(\s+)([A-Za-z]+)(?=\s*$|[^A-Za-z])/, (all, sp: string, w: string, _off: number, whole: string) => {
+ const lw = w.toLowerCase();
+ // Another word after a counted thing, in the amount or in the text, makes it a modifier.
+ if (THINGS.has(lw) && (nounFollows || /\p{L}/u.test(whole.slice(sp.length + w.length)))) return all;
+ const to = top > 1 ? PLURAL[lw] : SINGULAR[lw];
+ if (!to) return all;
+ // Keep the reply's case: "Cups" stays capitalised.
+ return sp + (w[0] === w[0].toUpperCase() ? to[0].toUpperCase() + to.slice(1) : to);
+ });
+ return { qty: withThousands(m[1], fa) + (b !== null ? '–' + withThousands(m[2], fb as string) : '') + rest, scaled: true };
+}
+
+/** Can this amount scale at all? (It starts with a number, fraction or glyph.) */
+export const canScale = (qty: string | null) => !!qty && LEAD.test(qty);
+
+/** qty + text is the reply's full line (§11, contract §1): "1 onion" + ", diced"; "2 cups" + "flour". */
+export const joinLine = (qty: string, text: string) => (text.startsWith(',') ? qty + text : `${qty} ${text}`);
+
+export const servesRange = (serves: number) => ({ min: 1, max: Math.max(24, serves) });
+
+/** Does the Serves chip step? Only with `serves` and at least one amount that can scale (design §2). */
+export const isScalable = (block: RecipeBlock) => !!block.serves && block.ingredients.some((i) => canScale(i.qty));
+
+/** The servings the card shows: the chosen number while it can scale, else the recipe's own. */
+export const shownServes = (block: RecipeBlock, chosen: number | null) => (isScalable(block) ? chosen ?? block.serves ?? 1 : block.serves ?? 1);
+
+/** The ingredient line at the shown servings, as plain text. */
+export function ingredientLine(ing: RecipeIngredient, k: number): string {
+ const text = plainText(ing.text);
+ if (!ing.qty) return text;
+ return joinLine(scaleQty(ing.qty, k, text).qty, text);
+}
+
+/** Ungrouped first (no label), then each group in the order the reply first used it. */
+export function groupIngredients(block: RecipeBlock): { group: string | null; items: RecipeIngredient[] }[] {
+ const groups: { group: string | null; items: RecipeIngredient[] }[] = [];
+ const loose = block.ingredients.filter((i) => !i.group);
+ if (loose.length) groups.push({ group: null, items: loose });
+ for (const ing of block.ingredients) {
+ if (!ing.group) continue;
+ let g = groups.find((x) => x.group === ing.group);
+ if (!g) groups.push((g = { group: ing.group, items: [] }));
+ g.items.push(ing);
+ }
+ return groups;
+}
+
+/** The scale factor shown / serves: 1 without `serves`. */
+export const factor = (block: RecipeBlock, shown: number) => (block.serves ? shown / block.serves : 1);
+
+/** "Prep 15 min · Cook 35 min" with "Serves 6" first when the recipe says how many it serves. */
+export function headerLine(block: RecipeBlock, shown: number): string {
+ const parts = [...(block.serves ? [`Serves ${shown}`] : []), ...block.times.map((t) => `${t.label} ${t.text}`)];
+ return parts.join(' · ');
+}
+
+/** Copy recipe (§6): markdown at the shown servings, no ticks. */
+export function recipeMarkdown(block: RecipeBlock, shown: number): string {
+ const k = factor(block, shown);
+ const out: string[] = [`## ${block.title ?? 'Recipe'}`];
+ const head = headerLine(block, shown);
+ if (head) out.push(head);
+ out.push('', '### Ingredients');
+ groupIngredients(block).forEach(({ group, items }, gi) => {
+ if (group) out.push(...(gi > 0 ? [''] : []), `**${group}**`);
+ for (const ing of items) out.push(`- ${ingredientLine(ing, k)}`);
+ });
+ out.push('', '### Method');
+ block.steps.forEach((s, i) => out.push(`${i + 1}. ${plainText(s.text)}`));
+ if (block.notes.length) {
+ out.push('', '### Notes');
+ for (const n of block.notes) out.push(`- ${plainText(n)}`);
+ }
+ return out.join('\n') + '\n';
+}
+
+/** The ingredients still to get: unticked, in the card's order. */
+export function shoppingItems(block: RecipeBlock, have: Set<string>): RecipeIngredient[] {
+ return groupIngredients(block).flatMap((g) => g.items).filter((i) => !have.has(i.id));
+}
+
+/** Copy shopping list (§6): the unticked ingredients, scaled, no groups. "(serves 6)" only with serves. */
+export function shoppingListText(block: RecipeBlock, have: Set<string>, shown: number): string {
+ const k = factor(block, shown);
+ const head = `Shopping list: ${block.title ?? 'Recipe'}${block.serves ? ` (serves ${shown})` : ''}`;
+ return [head, ...shoppingItems(block, have).map((i) => `- ${ingredientLine(i, k)}`)].join('\n') + '\n';
+}
+
+// ---------------------------------------------------------------------------------------------------
+// State: one key per block, kept on this device (§7)
+
+export interface RecipeState {
+ /** The servings shown; the recipe's own number when nothing was chosen. */
+ serves: number | null;
+ have: Set<string>;
+ done: Set<string>;
+}
+
+export const recipeStorageKey = (messageId: string, blockId: string) => `kwnt:recipe:${messageId}:${blockId}`;
+export const RECIPE_CHANGE_EVENT = 'kwnt:recipe-change';
+
+/** What this device kept for the block, ids checked against the block; the reply's state when nothing is kept. */
+export function readRecipeState(messageId: string, block: RecipeBlock): RecipeState {
+ const fresh: RecipeState = { serves: block.serves, have: new Set(), done: new Set() };
+ try {
+ const stored = localStorage.getItem(recipeStorageKey(messageId, block.id));
+ if (stored === null) return fresh;
+ const raw = JSON.parse(stored) as { serves?: unknown; have?: unknown; done?: unknown };
+ const ings = new Set(block.ingredients.map((i) => i.id));
+ const steps = new Set(block.steps.map((s) => s.id));
+ const ids = (v: unknown, ok: Set<string>) => new Set(Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && ok.has(x)) : []);
+ const range = block.serves ? servesRange(block.serves) : null;
+ const serves =
+ range && typeof raw.serves === 'number' && Number.isInteger(raw.serves) && raw.serves >= range.min && raw.serves <= range.max ? raw.serves : block.serves;
+ return { serves, have: ids(raw.have, ings), done: ids(raw.done, steps) };
+ } catch {
+ return fresh;
+ }
+}
+
+export function saveRecipeState(messageId: string, block: RecipeBlock, s: RecipeState) {
+ const key = recipeStorageKey(messageId, block.id);
+ try {
+ if (s.have.size === 0 && s.done.size === 0 && s.serves === block.serves) localStorage.removeItem(key);
+ else {
+ const body: { serves?: number; have: string[]; done: string[] } = { have: [...s.have], done: [...s.done] };
+ if (block.serves && s.serves !== null && s.serves !== block.serves) body.serves = s.serves;
+ localStorage.setItem(key, JSON.stringify(body));
+ }
+ } catch {
+ // Private mode or a full store: the ticks just don't outlast the page.
+ }
+ // The card and its footer (in the action row) share this state.
+ window.dispatchEvent(new CustomEvent(RECIPE_CHANGE_EVENT, { detail: { key } }));
+}
+
+/**
+ * The block's ticks and servings, shared by the card and the footer's shopping-list count. Backed by the
+ * one storage key plus a window event, so both update together (and so do two views of one message).
+ */
+export function useRecipeState(messageId: string, block: RecipeBlock) {
+ const [state, setState] = useState<RecipeState>(() => readRecipeState(messageId, block));
+ const key = recipeStorageKey(messageId, block.id);
+ useEffect(() => {
+ setState(readRecipeState(messageId, block));
+ const on = (e: Event) => {
+ if ((e as CustomEvent<{ key?: string }>).detail?.key === key) setState(readRecipeState(messageId, block));
+ };
+ window.addEventListener(RECIPE_CHANGE_EVENT, on);
+ return () => window.removeEventListener(RECIPE_CHANGE_EVENT, on);
+ // The block is checked again each render; its id and the message decide the key.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [key]);
+
+ const update = useCallback(
+ (fn: (s: RecipeState) => RecipeState) => {
+ const next = fn(readRecipeState(messageId, block));
+ setState(next);
+ saveRecipeState(messageId, block, next);
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [key],
+ );
+ const toggle = (which: 'have' | 'done', id: string) =>
+ update((s) => {
+ const set = new Set(s[which]);
+ if (set.has(id)) set.delete(id);
+ else set.add(id);
+ return { ...s, [which]: set };
+ });
+ return {
+ state,
+ toggleHave: (id: string) => toggle('have', id),
+ toggleDone: (id: string) => toggle('done', id),
+ setServes: (n: number) => update((s) => ({ ...s, serves: n })),
+ };
+}
diff --git a/frontend/src/showOnce.ts b/frontend/src/showOnce.ts
index c2738d8a..e4332bfe 100644
--- a/frontend/src/showOnce.ts
+++ b/frontend/src/showOnce.ts
@@ -1002,6 +1002,17 @@ export function trialOf(msg: { trial?: unknown; meta?: string | null }): TrialRe
return ref;
}
+/**
+ * S-F7 (next-076/copy.md): a trial turn whose reply came back empty says so in the bubble, instead of
+ * leaving it blank above the "still waits for you" card. `family` is the bot's engine family from its
+ * preferred_model; anything that isn't a named engine (auto, Custom API, unknown) reads "The engine".
+ */
+const EMPTY_REPLY_ENGINE: Record<string, string> = { claude: 'Claude', codex: 'Codex', grok: 'Grok', ollama: 'Ollama' };
+export function emptyTrialReplyLine(family: string | null | undefined): string {
+ const who = (family && EMPTY_REPLY_ENGINE[family]) || 'The engine';
+ return `${who} sent back an empty reply, so this try didn't finish. Try it again before you approve.`;
+}
+
/**
* Where a "… still waits for you" card goes: after the last message of each trial that has ended.
* Ended is the SSE `show_once_trial_ended` seen in this tab (the live message lacks `outcome`), or
diff --git a/frontend/src/smartResults.ts b/frontend/src/smartResults.ts
index 0041075f..92abad6e 100644
--- a/frontend/src/smartResults.ts
+++ b/frontend/src/smartResults.ts
@@ -12,7 +12,13 @@ export type Source =
/** `ordered` absent means true (v1). Ordered and unordered lists are counted separately. */
| { kind: 'markdown_list'; index: number; ordered?: boolean }
/** No source in the text: drawn after the reply. */
- | { kind: 'slot' };
+ | { kind: 'slot' }
+ /**
+ * A stretch of the reply (recipe, 0.7.6, contract.md §2): from `lead` top-level blocks before the list
+ * (index, ordered) through the list (last_index, last_ordered). Lists are counted as for markdown_list.
+ * The block is drawn where the stretch was.
+ */
+ | { kind: 'markdown_section'; index: number; ordered: boolean; last_index: number; last_ordered: boolean; lead: number };
export type Provenance =
| { kind: 'reply_text' }
@@ -223,7 +229,35 @@ export interface FilesBlock extends BlockCommon<'files'> {
items: FileItem[];
}
+export interface RecipeTime {
+ /** The reply's own words: "Prep", "Cook", "Total". */
+ label: string;
+ text: string;
+}
+export interface RecipeIngredient {
+ id: string;
+ /** The line after `qty`: qty + text is the reply's full line ("1 onion" + ", diced"). */
+ text: string;
+ /** The leading amount exactly as written ("2 cups", "½", "1–2 tsp"); null when the line has none. */
+ qty: string | null;
+ /** The sub-heading it sits under ("For the sauce"). */
+ group: string | null;
+}
+export interface RecipeStep {
+ id: string;
+ text: string;
+}
+/** 2–40 ingredients, 2–30 steps, 0–3 times, 0–6 notes. */
+export interface RecipeBlock extends BlockCommon<'recipe'> {
+ serves: number | null;
+ times: RecipeTime[];
+ ingredients: RecipeIngredient[];
+ steps: RecipeStep[];
+ notes: string[];
+}
+
export type SmartBlock =
+ | RecipeBlock
| ComparisonBlock
| ChartBlock
| MetricsBlock
@@ -293,6 +327,12 @@ export const isHttpUrl = (v: unknown): v is string => {
export function parseSource(v: unknown): Source | null {
if (!isObj(v)) return null;
if (v.kind === 'slot') return { kind: 'slot' };
+ if (v.kind === 'markdown_section') {
+ const lead = v.lead ?? 0;
+ if (!isIndex(v.index) || typeof v.ordered !== 'boolean' || !isIndex(v.last_index) || typeof v.last_ordered !== 'boolean') return null;
+ if (!isIndex(lead) || lead > 12) return null;
+ return { kind: 'markdown_section', index: v.index, ordered: v.ordered, last_index: v.last_index, last_ordered: v.last_ordered, lead };
+ }
if (!isIndex(v.index)) return null;
if (v.kind === 'markdown_table') return { kind: 'markdown_table', index: v.index };
if (v.kind === 'markdown_list') {
@@ -544,6 +584,47 @@ export interface HastNode {
children?: HastNode[];
properties?: Record<string, unknown>;
data?: Record<string, unknown>;
+ position?: { start: { offset?: number }; end: { offset?: number } };
+}
+
+/** The unchecked block whose source is a stretch of the reply (a recipe), if any. */
+export function sectionBlock(results: unknown): (Record<string, unknown> & { source: Extract<Source, { kind: 'markdown_section' }> }) | null {
+ for (const b of resultBlocks(results)) {
+ const src = parseSource(b.source);
+ if (src?.kind === 'markdown_section') return { ...b, source: src };
+ }
+ return null;
+}
+
+/**
+ * Runs after rehypeSmartIndex. When a block's source is a markdown_section, the reply's top-level blocks
+ * from `lead` before the first list through the last list become one placeholder `div` that carries
+ * that stretch's markdown (data.smartSection), so the block is drawn once in their place and never
+ * repeats them. When the lists aren't where the block says, nothing changes and the reply stays text.
+ */
+export function rehypeSmartSection(markdown: string, results: unknown) {
+ return () => (tree: HastNode) => {
+ const raw = sectionBlock(results);
+ const kids = tree.children;
+ if (!raw || !kids) return;
+ const { index, ordered, last_index, last_ordered, lead } = raw.source;
+ const els = kids.filter((n) => n.type === 'element');
+ const at = (i: number, o: boolean) => els.findIndex((n) => (n.tagName === 'ol' || n.tagName === 'ul') && n.data?.smartIndex === i && n.data.smartOrdered === o);
+ const a = at(index, ordered), z = at(last_index, last_ordered);
+ if (a < 0 || z < a || a - lead < 0) return;
+ const from = els[a - lead], to = els[z];
+ const start = from.position?.start.offset, end = to.position?.end.offset;
+ if (start === undefined || end === undefined) return;
+ const i = kids.indexOf(from), j = kids.indexOf(to);
+ const holder: HastNode = {
+ type: 'element',
+ tagName: 'div',
+ properties: {},
+ children: [],
+ data: { smartSection: true, markdown: markdown.slice(start, end) },
+ };
+ kids.splice(i, j - i + 1, holder);
+ };
}
export const hastText = (n: HastNode | undefined): string =>
diff --git a/frontend/src/styles/gettingStarted.css b/frontend/src/styles/gettingStarted.css
new file mode 100644
index 00000000..8b6be81f
--- /dev/null
+++ b/frontend/src/styles/gettingStarted.css
@@ -0,0 +1,20 @@
+/* O2 Get started card (design next-076/onboarding §13): a step opens with opacity and 4 px of
+ movement over 160 ms; nothing moves under prefers-reduced-motion. */
+.gs-open {
+ animation: gs-open 160ms ease-out both;
+}
+@keyframes gs-open {
+ from {
+ opacity: 0;
+ transform: translateY(4px);
+ }
+ to {
+ opacity: 1;
+ transform: none;
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .gs-open {
+ animation: none;
+ }
+}
diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.css
index ea8ddebf..016df687 100644
--- a/frontend/src/styles/modern.css
+++ b/frontend/src/styles/modern.css
@@ -954,3 +954,15 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord
from { opacity: 0; transform: translateY(24px); }
to { opacity: 1; transform: none; }
}
+
+/* What's new › All changes: the CHANGELOG section (Mira's design.md, All changes) */
+[data-whats-new-all] .markdown-content { font-size: 13.5px; line-height: 21px; color: #bcb7de; }
+[data-whats-new-all] h3 { margin: 18px 0 8px; font-size: 12px; line-height: 18px; font-weight: 600;
+ text-transform: uppercase; letter-spacing: .06em; color: #9a94c4; }
+[data-whats-new-all] .markdown-content > h3:first-child { margin-top: 4px; }
+[data-whats-new-all] ul { margin: 0; }
+[data-whats-new-all] li { line-height: 21px; }
+/* beats Tailwind's .space-y-1 > :not([hidden]) ~ :not([hidden]) (0,3,0) on the renderer's ul */
+[data-whats-new-all] ul > li:not([hidden]) + li:not([hidden]) { margin-top: 8px; }
+[data-whats-new-all] li::marker { color: #5a5383; }
+[data-whats-new-all] strong { color: #ecebfa; }
diff --git a/frontend/src/styles/stream.css b/frontend/src/styles/stream.css
index 468b6044..fa0042cd 100644
--- a/frontend/src/styles/stream.css
+++ b/frontend/src/styles/stream.css
@@ -194,3 +194,6 @@
@media (prefers-reduced-motion: reduce) {
.kws-tip::after { transition: none; transform: none; }
}
+
+/* Recipe card (0.7.6): a step's badge pops once when it becomes done. Applied with motion-safe only. */
+@keyframes kw-step-done { from { transform: scale(.7); opacity: .4; } to { transform: scale(1); opacity: 1; } }
diff --git a/frontend/src/teams/teamTemplates.ts b/frontend/src/teams/teamTemplates.ts
index 86f2c0e5..172562e4 100644
--- a/frontend/src/teams/teamTemplates.ts
+++ b/frontend/src/teams/teamTemplates.ts
@@ -145,6 +145,11 @@ export interface TeamTemplateInfo {
blocked: unknown[];
removes: { bots: string[]; skills: number; routines: number; handle: string };
chat_messages: number;
+ /**
+ * 0.7.6 (teams-api.md §6): the name Undo gives the kept team chat, e.g. `archived-team-inbox-2`; null when
+ * Undo deletes the chat or leaves it alone. Missing from older servers.
+ */
+ archived_chat?: string | null;
/** Other teams a bot it made has joined since; it leaves them too. */
other_teams: { bot: string; team: string }[];
edited_skills: string[];
@@ -564,6 +569,8 @@ export const undoWindowOver = (e: unknown) =>
e instanceof TeamsError ? e.code === 'undo_window_over' || e.code === 'undo_expired' : !!e && typeof e === 'object' && ['undo_window_over', 'undo_expired'].includes((e as { code?: string }).code ?? '');
/** The Can't read block (api.md §4): 422 `cant_read` (424 from the §0 draft too). A 403 means the caller isn't the person, never "can't read". */
+/** N-5: another space already works in that folder; the same folder gets the same answer. */
+export const folderInUse = (e: unknown) => e instanceof TeamsError && e.code === 'folder_in_use';
export const cantRead = (e: unknown) => e instanceof TeamsError && (e.status === 424 || e.code === 'cant_read') && e.status !== 403;
export const readLine = (r: Suggestion['read'], partial: Suggestion['partial']) =>
diff --git a/frontend/src/useBrowserStream.ts b/frontend/src/useBrowserStream.ts
index 20b20047..05472048 100644
--- a/frontend/src/useBrowserStream.ts
+++ b/frontend/src/useBrowserStream.ts
@@ -15,6 +15,20 @@ export interface BrowserFrame {
/** Said when taking control fails because the bot is in the middle of something. */
export const BOT_BUSY_TEXT = 'The bot is finishing a step, try again in a moment.';
+/** Said when taking control fails because the person already holds this browser in another window (code held_by_person). */
+export const HELD_BY_PERSON_TEXT = "You're controlling this browser in another window. Press Hand back there to take over here.";
+
+/**
+ * A refused take_control: `held_by_person` can never win by retrying, so it gets its own sentence.
+ * `bot_busy`, `failed` and an older server's error with no code read as the busy bot, as before;
+ * the text match covers a server that sends the held sentence without a code.
+ */
+export function takeoverRefusedText(message: { code?: unknown; error?: unknown }): string {
+ if (message.code === 'held_by_person') return HELD_BY_PERSON_TEXT;
+ if (message.code === undefined && /another window/i.test(String(message.error ?? ''))) return HELD_BY_PERSON_TEXT;
+ return BOT_BUSY_TEXT;
+}
+
export function useBrowserStream(id: string | undefined, visible: boolean) {
const socket = useRef<WebSocket | null>(null);
const sequence = useRef(0);
@@ -89,7 +103,7 @@ export function useBrowserStream(id: string | undefined, visible: boolean) {
setUnsupported((s) => new Set(s).add(action));
} else if (action === 'take_control' || (takingControl.current && message.id === undefined)) {
takingControl.current = false;
- setError(BOT_BUSY_TEXT);
+ setError(takeoverRefusedText(message));
} else {
const text = streamErrorText(action, message.error);
if (text) setError(text);
diff --git a/frontend/src/whatsNewContent.ts b/frontend/src/whatsNewContent.ts
new file mode 100644
index 00000000..e69d27e5
--- /dev/null
+++ b/frontend/src/whatsNewContent.ts
@@ -0,0 +1,9 @@
+// The bundled "What's new" files and CHANGELOG sections (vite.config.ts builds the virtual module).
+import { changelog, entries } from 'virtual:kwant-whatsnew';
+import { sortEntries, type WhatsNewEntry } from './whatsNewSheet';
+
+/** Every good entry, newest first. The first is the version the sheet shows after an update. */
+export const WHATS_NEW: WhatsNewEntry[] = sortEntries(entries);
+export const latestWhatsNew = (): WhatsNewEntry | null => WHATS_NEW[0] ?? null;
+export const whatsNewFor = (version: string): WhatsNewEntry | null => WHATS_NEW.find((e) => e.version === version) ?? null;
+export const changelogFor = (version: string): string | null => changelog[version] ?? null;
diff --git a/frontend/src/whatsNewSheet.ts b/frontend/src/whatsNewSheet.ts
new file mode 100644
index 00000000..7b1a99e3
--- /dev/null
+++ b/frontend/src/whatsNewSheet.ts
@@ -0,0 +1,205 @@
+// "What's new in kwant X.Y.Z": the sheet shown once per device after an update (0.7.6 on).
+// The content is frontend/src/whatsnew/<version>.json, written in each release commit; the "All changes"
+// view is that version's CHANGELOG section. Both are bundled at build time (see vite.config.ts), so the
+// version shown is the newest bundled file: the web app on a server shows it after the server updates too.
+// This file is the pure part (rules, limits, storage); components/WhatsNewSheet.tsx draws it.
+
+import { parseView, type SpaceView } from './nav';
+import type { KeyValueStore } from './whatsNew';
+
+export interface WhatsNewHighlight {
+ id: string;
+ title: string;
+ text: string;
+ /** A webp in frontend/public/whatsnew/<version>/, or null. */
+ image: string | null;
+ /** An in-app place under /s/<space>/ (a view segment such as "settings/teams"), or null. */
+ open: string | null;
+}
+
+export interface WhatsNewEntry {
+ version: string;
+ /** YYYY-MM-DD */
+ date: string;
+ highlights: WhatsNewHighlight[];
+ fixes: string[];
+}
+
+/** The limits a whatsnew file must keep. scripts/site_release_gate.py checks the same ones at release. */
+export const LIMITS = { highlightsMin: 2, highlightsMax: 6, title: 60, text: 200, fixesMax: 15, fix: 140 } as const;
+
+export const SEEN_KEY = 'kwant:whatsnew:seen';
+/** More fixes than this fold behind "Show N more"; folded, the first FIXES_SHOWN stay visible. */
+export const FIXES_FOLD_OVER = 4;
+export const FIXES_SHOWN = 3;
+export const RELEASES_URL = 'https://github.com/alexsergivan/kwant/releases';
+export const releaseUrl = (version: string) => `${RELEASES_URL}/tag/mac-v${version}`;
+
+const VERSION = /^\d+\.\d+\.\d+$/;
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+const IMAGE = /^[a-z0-9][a-z0-9._-]*\.webp$/;
+
+const isStr = (v: unknown): v is string => typeof v === 'string';
+
+/** Every way `raw` breaks the format or the limits; empty when it's good. */
+export function validateEntry(raw: unknown, fileVersion?: string): string[] {
+ const out: string[] = [];
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return ['not a JSON object'];
+ const e = raw as Record<string, unknown>;
+ if (!isStr(e.version) || !VERSION.test(e.version)) out.push('version must be X.Y.Z');
+ else if (fileVersion && e.version !== fileVersion) out.push(`version ${e.version} doesn't match the file name ${fileVersion}.json`);
+ if (!isStr(e.date) || !DATE.test(e.date)) out.push('date must be YYYY-MM-DD');
+ const hs = e.highlights;
+ if (!Array.isArray(hs)) out.push('highlights must be a list');
+ else {
+ if (hs.length < LIMITS.highlightsMin || hs.length > LIMITS.highlightsMax) {
+ out.push(`highlights: ${hs.length}, needs ${LIMITS.highlightsMin}–${LIMITS.highlightsMax}`);
+ }
+ const ids = new Set<string>();
+ hs.forEach((h: unknown, i) => {
+ const at = `highlights[${i}]`;
+ if (!h || typeof h !== 'object') return void out.push(`${at} must be an object`);
+ const x = h as Record<string, unknown>;
+ if (!isStr(x.id) || !/^[a-z0-9-]+$/.test(x.id)) out.push(`${at}.id must be lowercase letters, digits and dashes`);
+ else if (ids.has(x.id)) out.push(`${at}.id "${x.id}" is used twice`);
+ else ids.add(x.id);
+ if (!isStr(x.title) || !x.title.trim()) out.push(`${at}.title is empty`);
+ else if ([...x.title].length > LIMITS.title) out.push(`${at}.title is ${[...x.title].length} characters, max ${LIMITS.title}`);
+ if (!isStr(x.text) || !x.text.trim()) out.push(`${at}.text is empty`);
+ else if ([...x.text].length > LIMITS.text) out.push(`${at}.text is ${[...x.text].length} characters, max ${LIMITS.text}`);
+ if (x.image !== null && (!isStr(x.image) || !IMAGE.test(x.image))) out.push(`${at}.image must be null or a .webp file name`);
+ if (x.open !== null && (!isStr(x.open) || !parseView(x.open) || parseView(x.open)!.legacy)) {
+ out.push(`${at}.open must be null or an in-app place such as "settings/teams"`);
+ }
+ });
+ }
+ const fx = e.fixes;
+ if (!Array.isArray(fx)) out.push('fixes must be a list');
+ else {
+ if (fx.length > LIMITS.fixesMax) out.push(`fixes: ${fx.length}, max ${LIMITS.fixesMax}`);
+ fx.forEach((f: unknown, i) => {
+ if (!isStr(f) || !f.trim()) out.push(`fixes[${i}] is empty`);
+ else if ([...f].length > LIMITS.fix) out.push(`fixes[${i}] is ${[...f].length} characters, max ${LIMITS.fix}`);
+ });
+ }
+ return out;
+}
+
+/** -1, 0 or 1. Anything that isn't X.Y.Z sorts below every version. */
+export function compareVersions(a: string | null | undefined, b: string | null | undefined): number {
+ const p = (v: string | null | undefined) => (v && VERSION.test(v) ? v.split('.').map(Number) : null);
+ const x = p(a);
+ const y = p(b);
+ if (!x || !y) return x ? 1 : y ? -1 : 0;
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
+ return 0;
+}
+
+/** The good entries, newest first. A broken file is left out (the release gate stops it before it ships). */
+export function sortEntries(raw: unknown[]): WhatsNewEntry[] {
+ return raw
+ .filter((r) => validateEntry(r).length === 0)
+ .map((r) => r as WhatsNewEntry)
+ .sort((a, b) => compareVersions(b.version, a.version));
+}
+
+/** A version's CHANGELOG section ("## [Mac X.Y.Z] - date" up to the next "## "), without its heading. */
+export function changelogSection(changelog: string, version: string): string | null {
+ const lines = changelog.split('\n');
+ const head = lines.findIndex((l) => l.trimEnd().startsWith(`## [Mac ${version}]`));
+ if (head < 0) return null;
+ let end = lines.findIndex((l, i) => i > head && l.startsWith('## '));
+ if (end < 0) end = lines.length;
+ const body = lines.slice(head + 1, end).join('\n').trim();
+ return body || null;
+}
+
+export function shortDate(iso: string): string {
+ const [y, m, d] = iso.split('-').map(Number);
+ if (!y || !m || !d) return iso;
+ return `${['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][m - 1]} ${d}`;
+}
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+/** "6 new things, 4 fixes" */
+export const entrySummary = (e: WhatsNewEntry) =>
+ `${plural(e.highlights.length, 'new thing')}${e.fixes.length ? `, ${plural(e.fixes.length, 'fix', 'fixes')}` : ''}`;
+
+/** The place a highlight's "Show me" opens, or null. */
+export function highlightView(h: WhatsNewHighlight): SpaceView | null {
+ const p = h.open ? parseView(h.open) : null;
+ return p && !p.legacy ? p.view : null;
+}
+
+// ---------- show once ----------
+
+/**
+ * What to do on a load, given the stored version (`seen`), the newest bundled one and whether this is an
+ * existing person: `established` is true when they have used kwant before (an account works, or they have
+ * written in a chat), false for a brand-new person, null while that isn't known yet.
+ * - show: open the sheet (when no dialog is open), then store `latest`.
+ * - record: store `latest` without showing anything (a new person gets Get started instead).
+ * - wait: decide again once `established` is known.
+ * - none: nothing to do.
+ */
+export type OnLoad = 'show' | 'record' | 'wait' | 'none';
+
+export function decideOnLoad(seen: string | null, latest: string | null, established: boolean | null): OnLoad {
+ if (!latest) return 'none';
+ if (seen !== null) return compareVersions(latest, seen) > 0 ? 'show' : 'none';
+ // No key: everyone upgrading from 0.7.5 or earlier. Only a person who has used kwant sees it.
+ if (established === null) return 'wait';
+ return established ? 'show' : 'record';
+}
+
+const defaultStore = (): KeyValueStore | null => {
+ try {
+ return typeof localStorage === 'undefined' ? null : localStorage;
+ } catch {
+ return null;
+ }
+};
+
+export function seenVersion(store: KeyValueStore | null = defaultStore()): string | null {
+ try {
+ return store?.getItem(SEEN_KEY) ?? null;
+ } catch {
+ return null;
+ }
+}
+
+/** Never moves back: an older tab can't make a newer version show again. */
+export function markSeen(version: string, store: KeyValueStore | null = defaultStore()): void {
+ if (!store) return;
+ try {
+ if (compareVersions(version, store.getItem(SEEN_KEY)) > 0) store.setItem(SEEN_KEY, version);
+ } catch {
+ return;
+ }
+}
+
+/** A modal or an alert is open (any dialog but the sheet itself), so the sheet waits. */
+export function otherDialogOpen(doc: Document | null = typeof document === 'undefined' ? null : document): boolean {
+ if (!doc) return false;
+ return [...doc.querySelectorAll('[aria-modal="true"], [role="alertdialog"], dialog[open]')].some((d) => !d.closest('[data-whats-new]'));
+}
+
+// ---------- opening it from elsewhere (the update banner, Settings › About) ----------
+
+export interface OpenRequest {
+ version: string;
+ seq: number;
+}
+let request: OpenRequest | null = null;
+let seq = 0;
+const listeners = new Set<() => void>();
+export const subscribeOpen = (l: () => void) => {
+ listeners.add(l);
+ return () => void listeners.delete(l);
+};
+export const openRequest = () => request;
+/** Ask the mounted sheet host to open `version`'s sheet. */
+export function openWhatsNew(version: string): void {
+ request = { version, seq: ++seq };
+ listeners.forEach((l) => l());
+}
diff --git a/frontend/src/whatsnew/0.7.5.json b/frontend/src/whatsnew/0.7.5.json
new file mode 100644
index 00000000..d28b46b1
--- /dev/null
+++ b/frontend/src/whatsnew/0.7.5.json
@@ -0,0 +1,54 @@
+{
+ "version": "0.7.5",
+ "date": "2026-11-07",
+ "highlights": [
+ {
+ "id": "side-by-side",
+ "title": "This Mac and your servers, side by side",
+ "text": "Every place you use opens in its own window, all at once. Add a server once from the menu bar and it stays listed and signed in.",
+ "image": null,
+ "open": null
+ },
+ {
+ "id": "teams",
+ "title": "Ready-made teams",
+ "text": "Create an Inbox, Sales or Coding team in one step: the bots, the team chat, starter skills and a routine. One Undo removes it all.",
+ "image": null,
+ "open": "settings/teams"
+ },
+ {
+ "id": "jira",
+ "title": "Work from Jira tickets",
+ "text": "Connect Jira in Dev mode. A bot reads each ticket, writes a brief with its questions, and waits for your OK before it starts.",
+ "image": null,
+ "open": null
+ },
+ {
+ "id": "watch-live",
+ "title": "Watch live",
+ "text": "A globe on a chat shows its bot is using the browser right now. Click it to watch the page.",
+ "image": null,
+ "open": null
+ },
+ {
+ "id": "telegram",
+ "title": "Your bots on Telegram",
+ "text": "Pair a Telegram chat to write to your bots and get their replies, questions and approvals on your phone.",
+ "image": null,
+ "open": "settings/connections"
+ },
+ {
+ "id": "show-once",
+ "title": "Show it once",
+ "text": "Show a bot a task once while kwant records the steps. Passwords and codes are never recorded. kwant turns it into a skill you review.",
+ "image": null,
+ "open": null
+ }
+ ],
+ "fixes": [
+ "Install Claude Code, Codex or Grok in one click when it's missing.",
+ "A quieter working line above the message box on the phone.",
+ "The Dev mode switch no longer gets stuck in \"settling\".",
+ "After \"Which is it?\" in a forge form, focus lands on the first choice."
+ ]
+}
diff --git a/frontend/src/whatsnew/content.d.ts b/frontend/src/whatsnew/content.d.ts
new file mode 100644
index 00000000..52928589
--- /dev/null
+++ b/frontend/src/whatsnew/content.d.ts
@@ -0,0 +1,7 @@
+// Built by the kwnt-whats-new plugin in vite.config.ts from src/whatsnew/*.json and ../CHANGELOG.md.
+declare module 'virtual:kwant-whatsnew' {
+ /** Each src/whatsnew/<version>.json as written. */
+ export const entries: unknown[];
+ /** Each of those versions' "## [Mac X.Y.Z]" CHANGELOG section, without its heading (null when missing). */
+ export const changelog: Record<string, string | null>;
+}
diff --git a/frontend/tests/bundle.mjs b/frontend/tests/bundle.mjs
index 65969646..3f0a90ad 100644
--- a/frontend/tests/bundle.mjs
+++ b/frontend/tests/bundle.mjs
@@ -1,10 +1,39 @@
// Bundles a TypeScript module (with its imports) for the node test runner.
import { build } from 'esbuild';
+import { readFileSync, readdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('..', import.meta.url));
-export async function loadBundled(contents) {
+/** The "What's new" content as vite.config.ts builds it: the real files unless a test passes its own. */
+export function whatsNewModule(content) {
+ if (content) return `export const entries = ${JSON.stringify(content.entries)};\nexport const changelog = ${JSON.stringify(content.changelog ?? {})};\n`;
+ const dir = new URL('../src/whatsnew/', import.meta.url);
+ const entries = readdirSync(dir)
+ .filter((n) => /^\d+\.\d+\.\d+\.json$/.test(n))
+ .map((n) => JSON.parse(readFileSync(new URL(n, dir), 'utf8')));
+ const log = readFileSync(new URL('../../CHANGELOG.md', import.meta.url), 'utf8');
+ const section = (v) => {
+ const lines = log.split('\n');
+ const head = lines.findIndex((l) => l.trimEnd().startsWith(`## [Mac ${v}]`));
+ if (head < 0) return null;
+ let end = lines.findIndex((l, i) => i > head && l.startsWith('## '));
+ if (end < 0) end = lines.length;
+ return lines.slice(head + 1, end).join('\n').trim() || null;
+ };
+ return whatsNewModule({ entries, changelog: Object.fromEntries(entries.map((e) => [e.version, section(e.version)])) });
+}
+
+const virtual = (whatsNew) => ({
+ name: 'kwnt-virtual',
+ setup(b) {
+ b.onResolve({ filter: /^virtual:kwant-whatsnew$/ }, (a) => ({ path: a.path, namespace: 'kwnt-virtual' }));
+ b.onLoad({ filter: /.*/, namespace: 'kwnt-virtual' }, () => ({ contents: whatsNewModule(whatsNew), loader: 'js' }));
+ },
+});
+
+/** `opts.whatsNew`: { entries, changelog } to bundle instead of src/whatsnew and CHANGELOG.md. */
+export async function loadBundled(contents, opts = {}) {
const out = await build({
stdin: { contents, resolveDir: root, loader: 'tsx' },
bundle: true,
@@ -14,6 +43,7 @@ export async function loadBundled(contents) {
jsx: 'automatic',
logLevel: 'silent',
define: { 'process.env.NODE_ENV': '"production"' },
+ plugins: [virtual(opts.whatsNew)],
});
return import(`data:text/javascript;base64,${Buffer.from(out.outputFiles[0].text).toString('base64')}`);
}
diff --git a/frontend/tests/fixtures/tickets.mjs b/frontend/tests/fixtures/tickets.mjs
new file mode 100644
index 00000000..d3d4b915
--- /dev/null
+++ b/frontend/tests/fixtures/tickets.mjs
@@ -0,0 +1,6 @@
+// Server sentences the ticket card shows word for word. Kept out of src/ because they are the server's
+// words, not the frontend's (tests/wording.test.mjs scans src/ only).
+
+// D6, next-076/jira-tickets/d6-contract.md: ticket.error.message for code "engine_refused" (as on #427 c355ade).
+export const ENGINE_REFUSED_MESSAGE =
+ "A Jira brief is prepared only on Claude or Codex, with tool checks on. Put the team's lead on one of them, then press Start.";
diff --git a/frontend/tests/gettingStarted.test.mjs b/frontend/tests/gettingStarted.test.mjs
new file mode 100644
index 00000000..461c27a2
--- /dev/null
+++ b/frontend/tests/gettingStarted.test.mjs
@@ -0,0 +1,418 @@
+// 0.7.6 O2: the Get started card (design next-076/onboarding). Step logic (already signed in → steps
+// 1–2 done, 3 open), the install tracker (409 wait, 422 admin step, failures), device-code sign-in
+// with polling and cancel, the Terminal fallback before O3, failure rows, the banner and its strings.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.window.matchMedia = g.window.matchMedia || ((q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {} }));
+g.fetch = g.window.fetch = async () => new Response('{}', { status: 404, headers: { 'Content-Type': 'application/json' } });
+const copied = [];
+Object.defineProperty(g.navigator, 'clipboard', { value: { writeText: async (t) => void copied.push(t) }, configurable: true });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export * from './src/gettingStarted';
+ export * from './src/gettingStartedInstall';
+ export { GetStarted, GetStartedBanner, bannerPhase, hostOf } from './src/components/GetStarted';
+`);
+const { React, createRoot, flushSync } = m;
+const h = React.createElement;
+const settle = async (n = 6) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const engine = (id, over = {}) => ({
+ id, name: id, kind: id.endsWith('_api') ? 'api' : 'cli', status: 'not_installed', detail: null, version: null, models: [], checked_at: null, enabled: true, ready: false, uses: null, ...over,
+});
+const ready = (id) => engine(id, { status: 'ready', ready: true });
+const signedOut = (id) => engine(id, { status: 'signed_out' });
+
+function mount(el) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ flushSync(() => root.render(el));
+ return { host, root, done: () => (root.unmount(), host.remove()) };
+}
+
+// ------------------------------------------------------------------ step logic
+
+test('steps: already signed in → steps 1 and 2 done, step 3 open (D2)', () => {
+ const v = m.stepsView({ engines: [ready('claude'), engine('codex')], chosen: null });
+ assert.deepEqual(v, { open: 3, done1: true, done2: true, choice: 'claude', foundReady: true });
+ assert.equal(m.step1Value(v, [ready('claude')], 'on this Mac'), 'Claude, already signed in on this Mac');
+ assert.deepEqual(m.heroText(v, { mac: true }), { title: 'Claude is ready on this Mac', sub: 'You were already signed in. Pick a team and say hello.' });
+ assert.equal(m.heroText(v, { host: 'vps.example.net' }).title, 'Claude is ready on vps.example.net');
+});
+
+test('steps: nothing chosen → 1; chosen, not signed in → 2; F8 → 3 early; Change → 1; never backwards', () => {
+ assert.equal(m.stepsView({ engines: [engine('claude')], chosen: null }).open, 1);
+ const two = m.stepsView({ engines: [engine('claude')], chosen: 'claude' });
+ assert.deepEqual([two.open, two.done1, two.done2], [2, true, false]);
+ assert.equal(m.step1Value(two, [engine('claude')], 'on this Mac'), 'Claude');
+ assert.equal(m.step1Value(m.stepsView({ engines: [signedOut('codex')], chosen: 'codex' }), [signedOut('codex')], ''), 'ChatGPT, installed');
+ assert.equal(m.stepsView({ engines: [engine('claude')], chosen: 'claude', teamEarly: true }).open, 3);
+ assert.equal(m.stepsView({ engines: [ready('claude')], chosen: 'claude', changing: true }).open, 1);
+ // Codex chosen while Claude works: the card stays on the chosen AI.
+ assert.equal(m.stepsView({ engines: [ready('claude'), signedOut('codex')], chosen: 'codex' }).open, 2);
+ // An API key that works finishes step 2.
+ assert.equal(m.stepsView({ engines: [ready('anthropic_api')], chosen: 'key' }).open, 3);
+ assert.equal(m.readyChoice([ready('xai_api'), ready('codex')]), 'codex', 'engine order: CLIs first');
+});
+
+test('the card shows for a fresh space, never for an older one with history, never once dismissed', () => {
+ const base = { dismissed: false, canRun: true, generalMessages: 0, teams: 0, started: false };
+ assert.equal(m.showCard(base), true);
+ assert.equal(m.showCard({ ...base, generalMessages: 4 }), false);
+ assert.equal(m.showCard({ ...base, teams: 1 }), true, 'the starter team alone is still a fresh install');
+ assert.equal(m.showCard({ ...base, teams: 2 }), false);
+ assert.equal(m.showCard({ ...base, teams: 2, started: true }), true, 'C4: stays until the first message');
+ assert.equal(m.showCard({ ...base, canRun: false, generalMessages: 9 }), true);
+ assert.equal(m.showCard({ ...base, canRun: null }), false, 'not while the engines load');
+ assert.equal(m.showCard({ ...base, canRun: false, dismissed: true }), false);
+});
+
+test('dismiss is kept per space and clears the stored choice', () => {
+ localStorage.clear();
+ m.storeChoice('s1', 'grok');
+ m.markStarted('s1');
+ assert.equal(m.storedChoice('s1'), 'grok');
+ assert.equal(m.wasStarted('s1'), true);
+ m.markStarted('s1', 'kept');
+ assert.equal(m.isKept('s1'), true);
+ m.dismiss('s1');
+ assert.equal(m.isDismissed('s1'), true);
+ assert.equal(m.storedChoice('s1'), null);
+ m.markStarted('s1');
+ assert.equal(m.isDismissed('s1'), true, 'never comes back');
+ assert.equal(m.isDismissed('s2'), false);
+});
+
+// ------------------------------------------------------------------ failures and strings
+
+test('install failures map to four kinds; the raw log never reaches the text', () => {
+ assert.equal(m.installFailKind('curl: (6) Could not resolve host', true), 'network');
+ assert.equal(m.installFailKind('write failed: No space left on device', true), 'disk');
+ assert.equal(m.installFailKind('npm ERR! code EACCES', true), 'permission');
+ assert.equal(m.installFailKind('exit status 3', true), 'other');
+ assert.equal(m.installFailKind('anything', false), 'offline');
+ const off = m.installFailView('offline', 'Claude', 'on this Mac');
+ assert.equal(off.tone, 'warn');
+ assert.equal(off.title, 'You’re offline, so Claude can’t download yet.');
+ assert.equal(m.installFailView('disk', 'Claude', 'on this computer', 'vps.example.net').title, 'Couldn’t get Claude ready on vps.example.net.');
+ assert.equal(m.installFailView('other', 'Codex', '').title, 'Something went wrong while getting Codex ready.');
+});
+
+test('sign-in endings: cancelled is neutral, expired asks for a new code, a rejected account is rose (F3, F4, F6)', () => {
+ assert.deepEqual(
+ [m.signInEnd({ state: 'cancelled', detail: null }, 'codex').tone, m.signInEnd({ state: 'cancelled', detail: null }, 'codex').title],
+ ['neutral', 'Sign-in stopped. Nothing was saved.'],
+ );
+ assert.equal(m.signInEnd({ state: 'expired', detail: null }, 'grok').action, 'Get a new code');
+ assert.equal(m.signInEnd({ state: 'expired', detail: null }, 'claude').title, 'That sign-in timed out.');
+ const f6 = m.signInEnd({ state: 'failed', detail: "This account can't use this account type" }, 'codex');
+ assert.equal(f6.tone, 'bad');
+ assert.equal(f6.title, 'Signed in, but Codex can’t use this account.');
+ assert.equal(m.signInEnd({ state: 'waiting_for_approval', detail: null }, 'codex'), null);
+});
+
+test('device code: read out letter by letter, only https sign-in pages open, the label drops https', () => {
+ assert.equal(m.codeAriaLabel('K7QF-2MXD'), 'Code K 7 Q F, 2 M X D');
+ assert.equal(m.deviceLabel('https://chatgpt.com/device?x=1'), 'chatgpt.com/device');
+ assert.equal(m.isSignInUrl('codex', 'https://auth.openai.com/codex/device'), true);
+ assert.equal(m.isSignInUrl('codex', 'http://chatgpt.com/device'), false);
+ assert.equal(m.isSignInUrl('codex', 'https://evil.example/device'), false);
+ assert.equal(m.isSignInUrl('claude', 'javascript:alert(1)'), false);
+ assert.equal(m.minutesLeft(new Date(Date.now() + 14.2 * 60000).toISOString(), Date.now()), 15);
+ assert.equal(m.minutesLeft(null, Date.now()), null);
+});
+
+test('banner strings outside #general (§7.1)', () => {
+ assert.equal(m.bannerView({ kind: 'choose' }, null).title, 'Getting started · Choose your AI');
+ const inst = m.bannerView({ kind: 'installing', seconds: 9 }, 'claude');
+ assert.deepEqual([inst.title, inst.short, inst.spinner], ['Getting started · Getting Claude ready… 9 s', 'Getting Claude ready… 9 s', true]);
+ const sign = m.bannerView({ kind: 'signin' }, 'codex');
+ assert.deepEqual([sign.title, sign.button], ['Getting started · Sign in to Codex', 'Continue']);
+ assert.equal(m.bannerView({ kind: 'failed' }, 'claude').sub, null);
+ assert.equal(m.bannerPhase([ready('claude')], null, null), null, 'never once step 2 is done');
+ assert.deepEqual(m.bannerPhase([engine('claude')], null, null), { kind: 'choose' });
+ assert.deepEqual(m.bannerPhase([signedOut('claude')], 'claude', null), { kind: 'signin' });
+});
+
+// ------------------------------------------------------------------ the install tracker
+
+const fast = { sleep: async () => {}, online: () => true };
+function setupFake({ busy = 0, start = 202, polls = 2, fail = null, manualReadyAfter = 1 } = {}) {
+ const calls = [];
+ let reads = 0;
+ let statusReads = 0;
+ return {
+ calls,
+ async status() {
+ calls.push('status');
+ statusReads++;
+ return [{ id: 'claude', label: 'Claude Code', state: statusReads >= manualReadyAfter ? 'ready' : 'missing', can_install: true }];
+ },
+ async install(item) {
+ calls.push(`install:${item}`);
+ if (busy-- > 0) return { status: 409, body: { error: 'another install is running', job_id: 'setup-0' } };
+ if (start === 422) return { status: 422, body: { error: 'this part needs a step only you can do', item, manual: [{ label: 'Install', command: 'sudo apt install -y bubblewrap' }] } };
+ if (start === 200) return { status: 200, body: { already_installed: true } };
+ return { status: 202, body: { job_id: 'setup-1', item } };
+ },
+ async job(id, after) {
+ calls.push(`job:${after}`);
+ reads++;
+ if (reads < polls) return { id, state: 'running', error: null, lines: [`line ${reads}`], next: after + 1 };
+ if (fail) return { id, state: 'failed', error: fail, lines: ['last'], next: after + 1 };
+ return { id, state: 'done', error: null, lines: [], next: after + 1 };
+ },
+ };
+}
+
+test('install: waits out 409, follows the job, then done; the card and banner read the same tracker', async () => {
+ const api = setupFake({ busy: 1 });
+ let done = 0;
+ const t = await m.startInstall('i1', 'claude', { ...fast, api, onDone: () => done++ });
+ assert.equal(t.state, 'done');
+ assert.deepEqual(api.calls, ['install:claude', 'install:claude', 'job:0', 'job:1']);
+ assert.equal(done, 1);
+ assert.equal(m.getTrack('i1').state, 'done');
+ m.forgetInstall('i1');
+ assert.equal(m.getTrack('i1'), null);
+});
+
+test('install: a failure keeps its kind and the log only for Copy details', async () => {
+ const t = await m.startInstall('i2', 'claude', { ...fast, api: setupFake({ fail: 'EACCES: permission denied' }) });
+ assert.deepEqual([t.state, t.kind], ['failed', 'permission']);
+ assert.match(m.installDetails(t), /EACCES/);
+ const off = await m.startInstall('i3', 'claude', { ...fast, api: setupFake(), online: () => false });
+ assert.deepEqual([off.state, off.kind], ['failed', 'offline']);
+});
+
+test('install: 422 shows the admin command, then moves on by itself once the part is there (F2c)', async () => {
+ const api = setupFake({ start: 422, manualReadyAfter: 2 });
+ const seen = [];
+ const un = m.subscribeTracks(() => seen.push(m.getTrack('i4')?.state));
+ const t = await m.startInstall('i4', 'claude', { ...fast, api });
+ un();
+ assert.equal(t.state, 'done');
+ assert.ok(seen.includes('needs_admin'));
+ assert.deepEqual(api.calls, ['install:claude', 'status', 'status']);
+});
+
+// ------------------------------------------------------------------ device-code sign-in
+
+function loginFake({ startError = null, polls = 2, end = 'done' } = {}) {
+ const calls = [];
+ let reads = 0;
+ const base = { session_id: 'L1', engine: 'codex', kind: 'device_code', detail: null, url: 'https://chatgpt.com/device', user_code: 'K7QF-2MXD', expires_at: new Date(Date.now() + 15 * 60000).toISOString() };
+ return {
+ calls,
+ async start(e) {
+ calls.push(`start:${e}`);
+ if (startError) throw startError;
+ return { ...base, engine: e, state: 'waiting_for_approval' };
+ },
+ async get(e, sid) {
+ calls.push(`get:${sid}`);
+ reads++;
+ return { ...base, engine: e, state: reads >= polls ? end : 'waiting_for_approval' };
+ },
+ async cancel(e, sid) {
+ calls.push(`cancel:${sid}`);
+ },
+ async submitCode() {
+ throw new Error('not for device codes');
+ },
+ };
+}
+
+test('startOrResume picks up the sign-in already running (409 with its id)', async () => {
+ const api = loginFake();
+ api.start = async () => {
+ throw new m.LoginError('a sign-in is already running', 409, 'L9');
+ };
+ const s = await m.startOrResume(api, 'codex');
+ assert.equal(api.calls[0], 'get:L9');
+ assert.equal(s.state, 'waiting_for_approval');
+});
+
+test('card: ChatGPT signed out → device code, copy-then-open, polls until done and reads engines again', async () => {
+ localStorage.clear();
+ m.storeChoice('d1', 'codex');
+ const api = loginFake({ polls: 1 });
+ let reloads = 0;
+ const opened = [];
+ window.open = (u) => (opened.push(u), null);
+ const r = mount(h(m.GetStarted, { space: 'd1', bots: [], engines: [signedOut('codex')], reloadEngines: () => reloads++, onDismissed() {}, loginApiOverride: api, hostOverride: null }));
+ await settle();
+ const card = r.host.querySelector('[data-get-started]');
+ assert.equal(card.getAttribute('data-open-step'), '2');
+ const code = r.host.querySelector('[data-user-code]');
+ assert.equal(code.textContent, 'K7QF-2MXD');
+ assert.equal(code.getAttribute('aria-label'), 'Code K 7 Q F, 2 M X D');
+ assert.match(r.host.textContent, /Open chatgpt\.com\/device and enter this code/);
+ assert.match(r.host.textContent, /Waiting for you to finish on chatgpt\.com…/);
+ assert.match(r.host.textContent, /The code works for 15 minutes\./);
+ assert.match(r.host.textContent, /ChatGPT, installed/);
+ copied.length = 0;
+ r.host.querySelector('[data-open-device]').click();
+ await settle();
+ assert.deepEqual(copied, ['K7QF-2MXD'], 'C6: the code is copied first');
+ assert.deepEqual(opened, ['https://chatgpt.com/device']);
+ await sleep(1700);
+ await settle();
+ assert.ok(api.calls.includes('get:L1'));
+ assert.ok(reloads >= 1, 'done → engines read again (step 3 opens from them)');
+ r.done();
+});
+
+test('card: Cancel stops the sign-in and shows the neutral F3 row with Start again', async () => {
+ localStorage.clear();
+ m.storeChoice('d2', 'grok');
+ const api = loginFake({ polls: 99 });
+ const r = mount(h(m.GetStarted, { space: 'd2', bots: [], engines: [signedOut('grok')], reloadEngines() {}, onDismissed() {}, loginApiOverride: api, hostOverride: null }));
+ await settle();
+ const cancel = [...r.host.querySelectorAll('button')].find((b) => b.textContent === 'Cancel');
+ cancel.click();
+ await settle();
+ assert.ok(api.calls.includes('cancel:L1'));
+ assert.match(r.host.textContent, /Sign-in stopped\. Nothing was saved\./);
+ assert.equal(r.host.querySelector('[data-fail-row]').getAttribute('data-fail-row'), 'neutral');
+ const again = [...r.host.querySelectorAll('button')].find((b) => b.textContent === 'Start again');
+ assert.ok(again);
+ assert.ok([...r.host.querySelectorAll('button')].some((b) => b.textContent === 'Choose another AI'));
+ again.click();
+ await settle();
+ assert.equal(api.calls.filter((c) => c === 'start:grok').length, 2);
+ r.done();
+});
+
+test('card: no device route on this server (before O3) → "codex login" in Terminal with Copy', async () => {
+ localStorage.clear();
+ m.storeChoice('d3', 'codex');
+ const api = loginFake({ startError: new m.LoginError('HTTP 404', 404) });
+ const r = mount(h(m.GetStarted, { space: 'd3', bots: [], engines: [signedOut('codex')], reloadEngines() {}, onDismissed() {}, loginApiOverride: api, hostOverride: null }));
+ await settle();
+ assert.ok(r.host.querySelector('[data-terminal-signin]'));
+ assert.match(r.host.textContent, /codex login/);
+ assert.doesNotMatch(r.host.textContent, /Re-check/);
+ r.done();
+});
+
+// ------------------------------------------------------------------ the card's other states
+
+test('card: already signed in → hero D2, steps 1–2 done with Change, step 3 open with Keep the starter bots', async () => {
+ localStorage.clear();
+ const r = mount(h(m.GetStarted, { space: 'r1', bots: [{ id: 'a', name: 'Architect' }], engines: [ready('claude')], reloadEngines() {}, onDismissed() {}, hostOverride: null }));
+ await settle();
+ const card = r.host.querySelector('[data-get-started]');
+ assert.equal(card.getAttribute('data-open-step'), '3');
+ assert.match(r.host.querySelector('h2').textContent, /^Claude is ready on this (Mac|computer)$/);
+ const heads = [...r.host.querySelectorAll('h3')].map((x) => x.textContent);
+ assert.match(heads[0], /^Step 1 of 3, Choose your AI, doneClaude, already signed in on this (Mac|computer)$/);
+ assert.equal(heads[1], 'Step 2 of 3, Sign in, doneNothing to do');
+ assert.equal(heads[2], 'Step 3 of 3, Pick a team, open');
+ assert.ok([...r.host.querySelectorAll('button')].some((b) => b.getAttribute('aria-label') === 'Change your AI'));
+ let dismissed = 0;
+ r.done();
+ const r2 = mount(h(m.GetStarted, { space: 'r1', bots: [], engines: [ready('claude')], reloadEngines() {}, onDismissed: () => dismissed++, hostOverride: null }));
+ r2.host.querySelector('[data-keep-starter]').click();
+ await settle();
+ assert.equal(dismissed, 1);
+ assert.equal(m.isDismissed('r1'), true);
+ r2.done();
+});
+
+test('card: step 1 tiles are a radiogroup; arrows move, a tap starts at once; server shows the host', async () => {
+ localStorage.clear();
+ const r = mount(h(m.GetStarted, { space: 't1', bots: [], engines: [engine('claude'), signedOut('codex')], reloadEngines() {}, onDismissed() {}, hostOverride: 'vps.example.net' }));
+ await settle();
+ const group = r.host.querySelector('[role="radiogroup"]');
+ assert.equal(group.getAttribute('aria-label'), 'Choose your AI');
+ const tiles = [...group.querySelectorAll('[role="radio"]')];
+ assert.deepEqual(tiles.map((t) => t.getAttribute('data-ai-tile')), ['claude', 'codex', 'grok', 'key']);
+ assert.deepEqual(tiles.map((t) => t.tabIndex), [0, -1, -1, -1]);
+ assert.match(tiles[1].textContent, /Installed · sign in next/);
+ tiles[0].focus();
+ tiles[0].dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));
+ assert.equal(document.activeElement, tiles[1]);
+ assert.match(r.host.textContent, /Setting up on vps\.example\.net/);
+ assert.match(r.host.textContent, /Tap one\. It gets ready on vps\.example\.net by itself\./);
+ assert.match(r.host.textContent, /It installs on your server, not on this phone\./);
+ flushSync(() => tiles[3].click());
+ await settle();
+ assert.equal(m.storedChoice('t1'), 'key');
+ assert.equal(r.host.querySelector('[data-get-started]').getAttribute('data-open-step'), '2');
+ assert.match(r.host.textContent, /Add your key/);
+ r.done();
+});
+
+test('card: a failed install shows F2 in step 2 with Try again, Copy details and Choose another AI; no log', async () => {
+ localStorage.clear();
+ m.storeChoice('f1', 'claude');
+ await m.startInstall('f1', 'claude', { ...fast, api: setupFake({ fail: 'curl: (56) Recv failure: Connection reset by peer' }) });
+ const r = mount(h(m.GetStarted, { space: 'f1', bots: [], engines: [engine('claude')], reloadEngines() {}, onDismissed() {}, hostOverride: null }));
+ await settle();
+ const row = r.host.querySelector('[data-fail-row]');
+ assert.equal(row.getAttribute('data-fail-row'), 'bad');
+ assert.equal(row.getAttribute('role'), 'alert');
+ assert.match(row.textContent, /Couldn’t get Claude ready\./);
+ assert.match(row.textContent, /The download stopped partway/);
+ const labels = [...row.querySelectorAll('button')].map((b) => b.textContent);
+ assert.deepEqual(labels, ['Try again', 'Copy details', 'Choose another AI']);
+ assert.doesNotMatch(r.host.textContent, /Recv failure|line 1/);
+ m.forgetInstall('f1');
+ r.done();
+});
+
+test('card: the install line counts seconds but only announces the words', async () => {
+ localStorage.clear();
+ m.storeChoice('f2', 'claude');
+ let release;
+ const api = setupFake();
+ api.install = () => new Promise((res) => (release = () => res({ status: 202, body: { job_id: 'j' } })));
+ void m.startInstall('f2', 'claude', { ...fast, api });
+ const r = mount(h(m.GetStarted, { space: 'f2', bots: [], engines: [engine('claude')], reloadEngines() {}, onDismissed() {}, hostOverride: null }));
+ await settle();
+ const live = r.host.querySelector('[data-install-line] [role="status"]');
+ assert.equal(live.textContent, 'Getting Claude ready');
+ assert.match(r.host.querySelector('[data-install-line]').textContent, /Getting Claude ready… 0 s/);
+ assert.match(r.host.textContent, /Next you sign in with your Claude account\./);
+ assert.match(r.host.querySelectorAll('h3')[1].textContent, /Sign in, in progress$/);
+ m.forgetInstall('f2');
+ release();
+ r.done();
+});
+
+test('banner: outside #general it says where getting started is, and Open goes to the card', async () => {
+ localStorage.clear();
+ let opened = 0;
+ const r = mount(h(m.GetStartedBanner, { space: 'b1', engines: [engine('claude')], onOpen: () => opened++ }));
+ assert.match(r.host.textContent, /Getting started · Choose your AI/);
+ assert.match(r.host.textContent, /One tap installs it\./);
+ r.host.querySelector('button').click();
+ assert.equal(opened, 1);
+ r.done();
+ const r2 = mount(h(m.GetStartedBanner, { space: 'b1', engines: [ready('claude')], onOpen() {} }));
+ assert.equal(r2.host.textContent, '', 'never once an account works');
+ r2.done();
+});
+
+test('host: only a real address counts as a server', () => {
+ assert.equal(m.hostOf({ location: { hostname: 'localhost' } }), null);
+ assert.equal(m.hostOf({ location: { hostname: '127.0.0.1' } }), null);
+ assert.equal(m.hostOf({ location: { hostname: 'vps.example.net' } }), 'vps.example.net');
+});
diff --git a/frontend/tests/recipe.test.mjs b/frontend/tests/recipe.test.mjs
new file mode 100644
index 00000000..39fe1de4
--- /dev/null
+++ b/frontend/tests/recipe.test.mjs
@@ -0,0 +1,563 @@
+// Recipe Smart Results card (0.7.6, next-076/recipe-result/design.md): scaling a leading amount (fractions
+// snap, both ends of a range, anything else as written), ticks and servings kept per message under one
+// key, the phone fold (more than 10, show 8), the two copy actions, validRecipe, and the card replacing
+// its stretch of the reply exactly once.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+// The viewport the fold reads; flipped per test.
+let phone = false;
+const listeners = new Set();
+g.window.matchMedia = (q) => ({
+ get matches() {
+ return q.includes('max-width: 639px') ? phone : false;
+ },
+ addEventListener: (_e, cb) => listeners.add(cb),
+ removeEventListener: (_e, cb) => listeners.delete(cb),
+});
+g.matchMedia = g.window.matchMedia;
+const clipboard = { text: null, writeText: async (t) => void (clipboard.text = t) };
+Object.defineProperty(g.navigator, 'clipboard', { value: clipboard, configurable: true });
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * from './src/recipe';
+ export { MarkdownRenderer } from './src/components/MarkdownRenderer';
+ export { Recipe, validRecipe, FOLD_OVER, FOLD_SHOW, TWO_COLUMNS_MIN } from './src/components/results/Recipe';
+ export { RecipeActions } from './src/components/results/RecipeActions';
+ export { recipe, recipeFixture, RECIPE_EDGES, RECIPE_CONTRACT } from './src/components/results/recipeFixtures';
+ export { blockMarkdown } from './src/components/results/exporters';
+`);
+const { React, createRoot } = m;
+const h = React.createElement;
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+const mounted = new Set();
+afterEach(() => {
+ for (const v of mounted) v.done();
+ mounted.clear();
+ localStorage.clear();
+ sessionStorage.clear();
+ clipboard.text = null;
+ phone = false;
+});
+async function mount(el) {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = createRoot(host);
+ root.render(el);
+ await settle();
+ const v = {
+ host,
+ done: () => {
+ root.unmount();
+ host.remove();
+ },
+ };
+ mounted.add(v);
+ return v;
+}
+const click = async (el) => {
+ assert.ok(el, 'element to click');
+ el.click();
+ await settle();
+};
+const stew = () => m.validRecipe(m.recipe.results.blocks[0]);
+const card = (block = stew(), messageId = 'm1') => h(m.Recipe, { block, messageId, reply: null, ask: () => {} });
+// What a sighted cook reads: the screen-reader-only "(was …)" cue left out.
+const seen = (el) => {
+ const c = el.cloneNode(true);
+ c.querySelectorAll('.sr-only').forEach((x) => x.remove());
+ return c.textContent;
+};
+const amounts = (host) => [...host.querySelectorAll('[data-ingredient]')].map(seen);
+const btn = (host, label) => host.querySelector(`button[aria-label="${label}"]`);
+const byText = (host, text) => [...host.querySelectorAll('button')].find((b) => b.textContent.trim() === text);
+
+// ---------------------------------------------------------------------------------------------------
+// Scaling (design §3)
+
+test('scaling: whole numbers, decimals, fractions, mixed numbers and glyphs', () => {
+ const s = (q, k) => m.scaleQty(q, k).qty;
+ assert.equal(s('500 g', 1.5), '750 g', '10 or more rounds to a whole number');
+ assert.equal(s('1 cup', 1.5), '1½ cups', 'snaps to ½ and the unit goes plural');
+ assert.equal(s('1 tbsp', 1.5), '1½ tbsp', 'abbreviations stay as written');
+ assert.equal(s('2 tsp', 0.5), '1 tsp');
+ assert.equal(s('½ cup', 0.5), '¼ cup');
+ assert.equal(s('1/2 cup', 2), '1 cup');
+ assert.equal(s('1 1/2 cups', 2), '3 cups');
+ assert.equal(s('1½ cups', 2), '3 cups');
+ assert.equal(s('1,5 l', 2), '3 l', 'a comma decimal');
+ assert.equal(s('1.5 kg', 3), '4½ kg');
+ assert.equal(s('1 tbsp', 0.25), '¼ tbsp');
+ assert.equal(s('½ tsp', 0.25), '⅛ tsp', '⅛ only below 1');
+ assert.equal(s('1 cup', 1 / 3), '⅓ cup');
+ assert.equal(s('1 cup', 2 / 3), '⅔ cup');
+ assert.equal(s('2 cups', 1.2), '2⅓ cups', 'within 0.07 of a glyph snaps');
+ assert.equal(s('2 cups', 1.45), '2.9 cups', 'off every glyph: one decimal with a dot');
+ assert.equal(s('2 cloves', 0.5), '1 clove', 'plural to singular at 1');
+ assert.equal(s('2 cloves', 0.25), '½ clove', 'singular under 1');
+ assert.equal(s('1 onion', 1.5), '1½ onions');
+ assert.equal(s('2 Cups', 0.5), '1 Cup', "keeps the reply's capital");
+ assert.equal(s('3 potatoes', 1 / 3), '1 potato');
+ assert.equal(s('1,000 g', 1.5), '1,500 g', 'a comma before three digits is a thousands separator (contract §1), and it stays (F-3)');
+ assert.equal(s('1,000 g', 0.5), '500 g', 'under 1,000 there is nothing to separate');
+ assert.equal(s('1000 g', 1.5), '1500 g', 'no separator when the reply wrote none');
+ assert.equal(s('1,5 l', 2), '3 l', 'and before one or two it is a decimal');
+});
+
+test('F-3: a non-zero amount never shows as 0; ⅛ down to 1/16, else the reply’s own amount', () => {
+ const s = (q, k) => m.scaleQty(q, k);
+ assert.deepEqual(s('0.25 tsp', 1 / 4), { qty: '⅛ tsp', scaled: true }, '0.0625 is ⅛, not 0');
+ assert.deepEqual(s('¼ tsp', 1 / 4), { qty: '⅛ tsp', scaled: true });
+ assert.deepEqual(s('0.25 tsp', 1 / 24), { qty: '0.25 tsp', scaled: false }, 'too small to write: kept as written, not marked scaled');
+ assert.deepEqual(s('1–2 pinches', 1 / 24), { qty: '1–2 pinches', scaled: false }, 'a range with an unwritable end stays whole');
+ assert.equal(m.formatAmount(0.0625), '⅛');
+ assert.equal(m.formatAmount(0.03), null);
+ assert.equal(m.formatAmount(0), '0');
+});
+
+test('F-3: a counted thing followed by another noun keeps its form; units and line ends still flip', () => {
+ const s = (q, k, after) => m.scaleQty(q, k, after).qty;
+ assert.equal(s('1 egg', 1.5, 'yolk'), '1½ egg', '"1 egg yolk" → "1½ egg yolk", never "eggs yolk"');
+ assert.equal(s('2 eggs', 0.5, 'whites'), '1 eggs', 'the reply’s own form stays either way');
+ assert.equal(s('1 egg yolk', 3), '3 egg yolk', 'the noun inside the amount counts too');
+ assert.equal(s('1 egg', 2, ''), '2 eggs', '"1 egg" → "2 eggs" still flips');
+ assert.equal(s('1 egg', 2, ', beaten'), '2 eggs', 'a comma after it is not a noun');
+ assert.equal(s('1 onion', 2, ', diced'), '2 onions');
+ assert.equal(s('1 cup', 2, 'flour'), '2 cups', 'a unit flips whatever follows');
+ assert.equal(s('1 can', 2, '(400 g) chopped tomatoes'), '2 cans');
+ const block = { ...stew(), serves: 1, ingredients: [{ id: 'i1', qty: '1 egg', text: 'yolk', group: null }, { id: 'i2', qty: '1 cup', text: 'flour', group: null }] };
+ assert.match(m.shoppingListText(block, new Set(), 3), /- 3 egg yolk\n- 3 cups flour/, 'the shopping list follows the same rule');
+});
+
+test('scaling: both ends of a range scale; nothing else changes', () => {
+ const s = (q, k) => m.scaleQty(q, k);
+ assert.equal(s('1–2 tsp', 1.5).qty, '1½–3 tsp');
+ assert.equal(s('1-2 tsp', 0.25).qty, '¼–½ tsp', 'a hyphen range is written with an en dash once scaled');
+ assert.equal(s('2–3 cups', 2).qty, '4–6 cups', 'the unit follows the top of the range');
+ assert.deepEqual(s('A pinch of flaky salt', 2), { qty: 'A pinch of flaky salt', scaled: false });
+ assert.deepEqual(s('Zest of 1 lemon', 2), { qty: 'Zest of 1 lemon', scaled: false }, 'a number that is not leading stays');
+ assert.deepEqual(s('2 cups', 1), { qty: '2 cups', scaled: false }, 'k = 1 is the reply exactly');
+ assert.equal(m.canScale('Salt to taste'), false);
+ assert.equal(m.canScale(null), false);
+ assert.equal(m.canScale('½'), true);
+ assert.equal(m.formatAmount(0.5), '½');
+ assert.equal(m.formatAmount(12.4), '12');
+ assert.equal(m.formatAmount(0.98), '1', 'snaps up to the next whole number');
+});
+
+test('the card: the stepper scales amounts in sky, Back to restores, and the limits hold', async () => {
+ const v = await mount(card());
+ const out = v.host.querySelector('output');
+ assert.equal(out.textContent, '4');
+ assert.equal(v.host.querySelector('[data-scaled]'), null, 'nothing is marked scaled at the reply’s own number');
+ assert.equal(byText(v.host, 'Back to 4'), undefined);
+ await click(btn(v.host, 'More servings'));
+ await click(btn(v.host, 'More servings'));
+ assert.equal(out.textContent, '6');
+ assert.equal(out.getAttribute('aria-label'), '6 servings');
+ const a = amounts(v.host);
+ assert.ok(a.includes('750 g squash, peeled and cubed'));
+ assert.ok(a.includes('1½ onions, diced'), 'qty + text joins with no space before a comma');
+ assert.ok(a.includes('1½–3 tsp chili flakes'));
+ assert.ok(a.includes('Salt to taste'), 'no qty, as written');
+ const scaled = v.host.querySelector('[data-scaled]');
+ assert.match(scaled.className, /text-sky-200/);
+ assert.match(scaled.className, /font-semibold/);
+ assert.equal(scaled.getAttribute('title'), 'In the reply: 1 tbsp');
+ await click(byText(v.host, 'Back to 4'));
+ assert.equal(out.textContent, '4');
+ assert.ok(amounts(v.host).includes('500 g squash, peeled and cubed'));
+
+ for (let i = 0; i < 5; i++) await click(btn(v.host, 'Fewer servings'));
+ assert.equal(out.textContent, '1');
+ assert.equal(btn(v.host, 'Fewer servings').getAttribute('aria-disabled'), 'true', 'aria-disabled, never disabled');
+ assert.equal(btn(v.host, 'Fewer servings').disabled, false);
+ assert.ok(amounts(v.host).includes('¼–½ tsp chili flakes'));
+ for (let i = 0; i < 30; i++) await click(btn(v.host, 'More servings'));
+ assert.equal(out.textContent, '24', 'the range is 1–24');
+ assert.equal(btn(v.host, 'More servings').getAttribute('aria-disabled'), 'true');
+});
+
+test('F-5: a scaled amount carries a screen-reader cue with the reply’s amount; none at the reply’s own number', async () => {
+ const v = await mount(card());
+ assert.equal(v.host.querySelector('[data-ingredient] .sr-only'), null);
+ await click(btn(v.host, 'More servings'));
+ await click(btn(v.host, 'More servings'));
+ const oil = v.host.querySelector('[data-ingredient="i1"]');
+ assert.equal(oil.querySelector('.sr-only').textContent, ' (was 1 tbsp)');
+ assert.equal(oil.textContent, '1½ tbsp (was 1 tbsp) olive oil', 'read out as: new amount, was, the rest of the line');
+ const salt = [...v.host.querySelectorAll('[data-ingredient]')].find((el) => el.textContent.includes('Salt to taste'));
+ assert.equal(salt.querySelector('.sr-only'), null, 'a line without an amount has no cue');
+});
+
+test('F-1: links, bold and code in ingredients, steps and notes are drawn as the reply wrote them', async () => {
+ const base = stew();
+ const block = {
+ ...base,
+ ingredients: [
+ { id: 'i1', qty: null, text: '**2 cups** flour', group: null },
+ { id: 'i2', qty: '1 cup', text: '[sugar](https://example.com/sugar), sifted', group: null },
+ { id: 'i3', qty: '1 onion', text: ', diced', group: null },
+ ],
+ steps: [
+ { id: 's1', text: 'Mix it **well**.' },
+ { id: 's2', text: 'Bake it; see [the guide](https://example.com/bake) and `200 C`.' },
+ { id: 's3', text: '1. Not a list: <b>raw</b> stays text.' },
+ ],
+ notes: ['Use *cold* butter, see [notes](https://example.com/notes).'],
+ };
+ const v = await mount(card(block));
+ const step = (id) => v.host.querySelector(`[data-step="${id}"]`);
+ const ing = (id) => v.host.querySelector(`[data-ingredient="${id}"]`);
+
+ assert.equal(ing('i1').querySelector('strong')?.textContent, '2 cups', 'bold stays bold in an ingredient');
+ assert.equal(seen(ing('i1')).trim(), '2 cups flour');
+ assert.equal(step('s1').querySelector('strong')?.textContent, 'well', 'bold stays bold in a step');
+
+ const a = step('s2').querySelector('a');
+ assert.equal(a?.getAttribute('href'), 'https://example.com/bake', 'a link keeps its target');
+ assert.equal(a.textContent, 'the guide');
+ assert.equal(a.getAttribute('target'), '_blank', 'opened the way the chat opens a link');
+ assert.equal(a.getAttribute('rel'), 'noopener noreferrer');
+ assert.equal(step('s2').querySelector('code')?.textContent, '200 C', 'code stays code');
+ assert.match(step('s2').textContent, /Bake it; see the guide and 200 C\./);
+
+ assert.equal(step('s3').querySelector('ol, ul, b'), null, 'a leading "1." is text, and raw HTML is never drawn');
+ assert.match(step('s3').textContent, /1\. Not a list:/);
+
+ const note = v.host.querySelector('section > div:last-child li');
+ assert.equal(note.querySelector('em')?.textContent, 'cold');
+ assert.equal(note.querySelector('a')?.getAttribute('href'), 'https://example.com/notes');
+
+ // Scaling changes only the amount; the link in the same line stays a link.
+ await click(btn(v.host, 'More servings'));
+ await click(btn(v.host, 'More servings'));
+ const sugar = ing('i2');
+ assert.equal(sugar.querySelector('[data-scaled]').textContent, '1½ cups');
+ assert.equal(sugar.querySelector('a')?.getAttribute('href'), 'https://example.com/sugar');
+ assert.equal(seen(sugar), '1½ cups sugar, sifted');
+ assert.equal(seen(ing('i3')), '1½ onions, diced', 'a line that starts with a comma gets no space');
+
+ // Clicking the link opens it and does not tick the row.
+ sugar.querySelector('a').addEventListener('click', (e) => e.preventDefault());
+ await click(sugar.querySelector('a'));
+ assert.equal(sugar.closest('label').querySelector('input').checked, false);
+});
+
+test('F-1: the two copy actions stay plain text', () => {
+ const block = {
+ ...stew(),
+ serves: 2,
+ ingredients: [
+ { id: 'i1', qty: null, text: '**2 cups** flour', group: null },
+ { id: 'i2', qty: '1 cup', text: '[sugar](https://example.com/sugar)', group: null },
+ ],
+ steps: [
+ { id: 's1', text: 'Mix it **well**.' },
+ { id: 's2', text: 'Bake it; see [the guide](https://example.com/bake) and `200 C`.' },
+ ],
+ notes: [],
+ };
+ const md = m.recipeMarkdown(block, 4);
+ assert.match(md, /- 2 cups flour\n- 2 cups sugar\n/);
+ assert.match(md, /1\. Mix it well\.\n2\. Bake it; see the guide and 200 C\./);
+ assert.doesNotMatch(md, /\*\*|\]\(|`/);
+ assert.equal(m.shoppingListText(block, new Set(), 4), 'Shopping list: ' + (block.title ?? 'Recipe') + ' (serves 4)\n- 2 cups flour\n- 2 cups sugar\n');
+});
+
+test('F-6: two columns from a 700 px card', () => {
+ assert.equal(m.TWO_COLUMNS_MIN, 700);
+});
+
+test('no serves: no stepper and nothing scales; serves with nothing to scale: a plain chip', async () => {
+ const none = await mount(card(m.validRecipe(m.RECIPE_EDGES.noServes.results.blocks[0])));
+ assert.equal(none.host.querySelector('[role="group"][aria-label="Servings"]'), null);
+ assert.equal(none.host.querySelector('[data-serves-chip]'), null);
+ assert.ok(none.host.textContent.includes('Total'), 'the time chip stays');
+ const flat = await mount(card(m.validRecipe(m.RECIPE_EDGES.nothingScales.results.blocks[0]), 'm2'));
+ assert.equal(flat.host.querySelector('[aria-label="Servings"]'), null);
+ assert.equal(flat.host.querySelector('[data-serves-chip]').textContent.replace(/\s+/g, ' ').trim(), 'Serves 4');
+ const bare = await mount(card(m.validRecipe(m.RECIPE_EDGES.bare.results.blocks[0]), 'm3'));
+ assert.equal(bare.host.querySelector('h3').nextElementSibling.className.includes('border-t'), true, 'E4: the name, then the divider');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Ticks, steps and storage (design §5, §7)
+
+test('ticks, done steps and servings persist per message under one key, by id', async () => {
+ const block = stew();
+ const v = await mount(card(block));
+ const boxes = () => [...v.host.querySelectorAll('[data-ingredient]')].map((el) => el.closest('label').querySelector('input'));
+ await click(boxes()[0]);
+ await click(boxes()[4]);
+ await click(btn(v.host, 'More servings'));
+ await click(v.host.querySelector('[data-step="s1"] input'));
+ const key = m.recipeStorageKey('m1', 'b-recipe');
+ assert.equal(key, 'kwnt:recipe:m1:b-recipe');
+ assert.deepEqual(JSON.parse(localStorage.getItem(key)), { have: ['i1', 'i5'], done: ['s1'], serves: 5 });
+ assert.equal(v.host.textContent.includes('2 of 14'), true, 'the ingredient count');
+ v.done();
+ mounted.delete(v);
+
+ const again = await mount(card(block));
+ assert.equal(again.host.querySelector('output').textContent, '5', 'a reload keeps the servings');
+ assert.equal(again.host.querySelector('[data-ingredient="i1"]').closest('label').querySelector('input').checked, true);
+ assert.match(again.host.querySelector('[data-ingredient="i1"]').className, /line-through/);
+ assert.equal(again.host.querySelector('[data-step="s1"]').dataset.state, 'done');
+
+ const other = await mount(card(block, 'm2'));
+ assert.equal(other.host.querySelector('output').textContent, '4', 'another message has its own key');
+
+ localStorage.setItem(key, JSON.stringify({ have: ['gone', 'i2'], done: [3], serves: 99 }));
+ const st = m.readRecipeState('m1', block);
+ assert.deepEqual([...st.have], ['i2'], 'unknown ids are dropped');
+ assert.deepEqual([...st.done], []);
+ assert.equal(st.serves, 4, 'an out-of-range number falls back to the recipe’s');
+ localStorage.setItem(key, '{not json');
+ assert.equal(m.readRecipeState('m1', block).have.size, 0, 'a broken entry reads as fresh');
+
+ m.saveRecipeState('m1', block, { serves: 4, have: new Set(), done: new Set() });
+ assert.equal(localStorage.getItem(key), null, 'nothing kept when it is back to the reply');
+});
+
+test('method: next appears only after the first done step, out of order picks the lowest; all done in teal; no line-through', async () => {
+ const v = await mount(card());
+ const step = (id) => v.host.querySelector(`[data-step="${id}"]`);
+ assert.equal(v.host.querySelector('[data-state="next"]'), null, 'nothing highlighted at rest');
+ assert.ok(v.host.textContent.includes('7 steps'));
+ await click(step('s1').querySelector('input'));
+ await click(step('s3').querySelector('input'));
+ assert.equal(v.host.querySelector('[data-state="next"]').dataset.step, 's2', 'out of order: the lowest not done');
+ assert.ok(step('s2').textContent.includes('(next)'));
+ assert.ok(v.host.textContent.includes('2 of 7 done'));
+ assert.doesNotMatch(step('s1').innerHTML, /line-through/, 'done steps dim, no strike');
+ assert.match(step('s3').querySelector('[aria-hidden]').className, /motion-safe:animate-\[kw-step-done/, 'the step just ticked pops, reduced motion skips it');
+ for (const id of ['s2', 's4', 's5', 's6', 's7']) await click(step(id).querySelector('input'));
+ assert.equal(v.host.querySelector('[data-state="next"]'), null, 'no next once all are done');
+ assert.ok(v.host.textContent.includes('All 7 done'));
+ assert.match(v.host.querySelector('.text-ok').className, /text-ok/);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Fold (design §4)
+
+test('fold: under 640 px with more than 10 ingredients, 8 show behind "Show all N"; ticks on hidden rows count', async () => {
+ phone = true;
+ const block = stew();
+ const v = await mount(card(block));
+ assert.equal(v.host.querySelectorAll('[data-ingredient]').length, m.FOLD_SHOW);
+ const more = byText(v.host, 'Show all 14');
+ assert.ok(more, 'Show all 14');
+ assert.equal(more.getAttribute('aria-expanded'), 'false');
+ assert.ok(document.getElementById(more.getAttribute('aria-controls')));
+ // Counting runs across groups: 8 of "For the stew" (9 rows) show, so "For the topping" is hidden.
+ assert.ok(v.host.textContent.includes('For the stew'));
+ assert.equal(v.host.textContent.includes('For the topping'), false, 'a group label shows only with a visible row');
+ await click(more);
+ assert.equal(v.host.querySelectorAll('[data-ingredient]').length, 14);
+ await click(v.host.querySelector('[data-ingredient="i14"]').closest('label').querySelector('input'));
+ const fewer = byText(v.host, 'Show fewer');
+ fewer.focus();
+ await click(fewer);
+ assert.equal(document.activeElement, byText(v.host, 'Show all 14'), 'focus stays on the button');
+ assert.ok(v.host.textContent.includes('1 of 14'), 'the count covers hidden rows');
+ assert.equal(sessionStorage.getItem('kwnt:recipe-open:m1:b-recipe'), null);
+});
+
+test('fold: never at 10 or fewer, and never on a wide viewport', async () => {
+ phone = true;
+ const ten = m.validRecipe(m.recipeFixture({}, Array.from({ length: 10 }, (_, i) => [`${i + 1} g`, `thing ${i + 1}`])).results.blocks[0]);
+ const v = await mount(card(ten));
+ assert.equal(v.host.querySelectorAll('[data-ingredient]').length, 10);
+ assert.equal(byText(v.host, 'Show all 10'), undefined);
+ phone = false;
+ const w = await mount(card(stew(), 'm9'));
+ assert.equal(w.host.querySelectorAll('[data-ingredient]').length, 14);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Actions (design §6)
+
+test('Copy recipe: markdown at the shown servings, groups bold, method numbered, notes; no ticks', async () => {
+ const block = stew();
+ localStorage.setItem(m.recipeStorageKey('m1', block.id), JSON.stringify({ serves: 6, have: ['i1'], done: ['s1'] }));
+ const v = await mount(h(m.RecipeActions, { block, messageId: 'm1' }));
+ await click(v.host.querySelector('[data-recipe-copy="recipe"]'));
+ const t = clipboard.text;
+ assert.ok(t.startsWith('## Golden squash and lentil stew\nServes 6 · Prep 15 min · Cook 35 min\n\n### Ingredients\n**For the stew**\n- 1½ tbsp olive oil\n- 1½ onions, diced\n'));
+ assert.ok(t.includes('\n\n**For the topping**\n- ¾ cup plain yogurt\n'));
+ assert.ok(t.includes('- 750 g squash, peeled and cubed'));
+ assert.ok(t.includes('- Salt to taste'));
+ assert.ok(t.includes('### Method\n1. Warm the oil'));
+ assert.ok(t.includes('7. Serve with'));
+ assert.ok(t.endsWith('### Notes\n- Keeps 3 days in the fridge. It thickens, so add a splash of stock when you reheat it.\n- Sweet potato works in place of the squash.\n- Leave out the yogurt for a vegan version.\n'));
+ assert.equal(t.includes('[x]'), false);
+ assert.ok(v.host.textContent.includes('Copied'));
+ assert.ok(v.host.textContent.includes('Copied the recipe for 6 servings'), 'the screen reader line');
+ assert.equal(m.blockMarkdown(block).includes('Serves 4'), true, 'Copy data’s Markdown is the reply’s own number');
+});
+
+test('Copy shopping list: the unticked ingredients, scaled, no groups; the count follows ticks; 0 left is disabled', async () => {
+ const block = stew();
+ const v = await mount(h('div', null, card(block), h(m.RecipeActions, { block, messageId: 'm1' })));
+ const chip = () => v.host.querySelector('[data-recipe-copy="shopping"]');
+ assert.equal(chip().getAttribute('aria-label'), 'Copy shopping list, 14 items');
+ await click(btn(v.host, 'More servings'));
+ await click(btn(v.host, 'More servings'));
+ for (const id of ['i1', 'i2', 'i9']) await click(v.host.querySelector(`[data-ingredient="${id}"]`).closest('label').querySelector('input'));
+ assert.equal(chip().getAttribute('aria-label'), 'Copy shopping list, 11 items', 'the footer count is live');
+ await click(chip());
+ const lines = clipboard.text.trimEnd().split('\n');
+ assert.equal(lines[0], 'Shopping list: Golden squash and lentil stew (serves 6)');
+ assert.equal(lines.length, 12);
+ assert.equal(lines[1], '- 3 cloves garlic, crushed');
+ assert.ok(lines.includes('- 750 g squash, peeled and cubed'));
+ assert.ok(lines.includes('- 1½–3 tsp chili flakes'));
+ assert.equal(lines.some((l) => /For the/.test(l)), false, 'no groups');
+ assert.ok(v.host.textContent.includes('Copied 11 items for 6 servings'));
+
+ for (const ing of block.ingredients) {
+ const box = v.host.querySelector(`[data-ingredient="${ing.id}"]`).closest('label').querySelector('input');
+ if (!box.checked) await click(box);
+ }
+ await new Promise((r) => setTimeout(r, 2100));
+ await settle();
+ assert.equal(chip().getAttribute('aria-disabled'), 'true');
+ assert.equal(chip().getAttribute('title'), 'Everything is ticked.');
+ clipboard.text = null;
+ await click(chip());
+ assert.equal(clipboard.text, null, 'clicking does nothing');
+});
+
+test('shopping list without serves: amounts as written, no "(serves N)"', () => {
+ const b = m.validRecipe(m.RECIPE_EDGES.noServes.results.blocks[0]);
+ assert.equal(m.shoppingListText(b, new Set(['i2']), 4), 'Shopping list: Garlic flatbreads\n- 2 cups flour\n- ¾ cup plain yogurt\n- 2 cloves garlic, grated\n- A good pinch of salt\n');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// validRecipe
+
+test('validRecipe accepts the fixtures and fills defaults', () => {
+ for (const [name, f] of Object.entries({ stew: m.recipe, ...m.RECIPE_EDGES })) assert.ok(m.validRecipe(f.results.blocks[0]), name);
+ const b = { ...m.recipe.results.blocks[0] };
+ delete b.serves;
+ delete b.times;
+ delete b.notes;
+ const v = m.validRecipe(b);
+ assert.equal(v.serves, null);
+ assert.deepEqual(v.times, []);
+ assert.deepEqual(v.notes, []);
+ assert.ok(m.validRecipe({ ...m.recipe.results.blocks[0], title: null }), 'no title: the card says Recipe');
+});
+
+test('validRecipe rejects anything off the contract', () => {
+ const b = m.recipe.results.blocks[0];
+ const no = (over, why) => assert.equal(m.validRecipe({ ...b, ...over }), null, why);
+ no({ type: 'steps' }, 'type');
+ no({ source: { kind: 'markdown_list', index: 0 } }, 'a recipe is always a stretch of the reply');
+ no({ source: { kind: 'slot' } }, 'never a slot (contract §2)');
+ no({ source: { kind: 'markdown_section', index: 0, last_index: 2, last_ordered: false, lead: 4 } }, 'ordered is required');
+ no({ source: { kind: 'markdown_section', first: { index: 0, ordered: false }, last: { index: 2, ordered: false }, lead: 4 } }, 'the flat shape only');
+ no({ source: { ...b.source, lead: 13 } }, 'lead 0–12');
+ no({ serves: 25 }, 'serves ≤ 24');
+ no({ serves: 0 }, 'serves ≥ 1');
+ no({ serves: 2.5 }, 'serves is a whole number');
+ no({ serves: '4' }, 'serves is a number');
+ no({ times: [{ label: 'Prep', text: '1' }, { label: 'Cook', text: '2' }, { label: 'Rest', text: '3' }, { label: 'Total', text: '4' }] }, 'at most 3 times');
+ no({ times: [{ label: 'Prep' }] }, 'a time needs text');
+ no({ ingredients: b.ingredients.slice(0, 1) }, 'at least 2 ingredients');
+ no({ ingredients: Array.from({ length: 41 }, (_, i) => ({ id: `x${i}`, text: 'a', qty: null, group: null })) }, 'at most 40');
+ no({ ingredients: [b.ingredients[0], { ...b.ingredients[1], id: b.ingredients[0].id }] }, 'unique ids');
+ no({ ingredients: [{ ...b.ingredients[0], text: '<img src=x onerror=1>' }, b.ingredients[1]] }, 'no HTML');
+ no({ ingredients: [{ ...b.ingredients[0], text: '' }, b.ingredients[1]] }, 'text is never empty');
+ no({ ingredients: [{ ...b.ingredients[0], qty: 'A pinch' }, b.ingredients[1]] }, 'qty starts with a digit or a fraction glyph');
+ no({ ingredients: [{ ...b.ingredients[0], id: 'x1' }, b.ingredients[1]] }, 'ingredient ids are i{k}');
+ no({ ingredients: [{ ...b.ingredients[0], group: 'g'.repeat(101) }, b.ingredients[1]] }, 'group ≤ 100');
+ no({ steps: [{ id: 'step1', text: 'Stir.' }, b.steps[1]] }, 'step ids are s{k}');
+ no({ steps: [{ id: 's1', text: 'a'.repeat(601) }, b.steps[1]] }, 'step text ≤ 600');
+ no({ ingredients: [{ ...b.ingredients[0], qty: 5 }, b.ingredients[1]] }, 'qty is text');
+ no({ steps: b.steps.slice(0, 1) }, 'at least 2 steps');
+ no({ steps: Array.from({ length: 31 }, (_, i) => ({ id: `s${i}`, text: 'Stir.' })) }, 'at most 30 steps');
+ no({ steps: [{ id: 's1', text: '' }, b.steps[1]] }, 'a blank step');
+ no({ notes: Array(7).fill('Tip.') }, 'at most 6 notes');
+ no({ notes: [3] }, 'notes are text');
+ assert.ok(m.validRecipe({ ...b, steps: [{ id: 's1', text: 'a'.repeat(600) }, b.steps[1]], notes: ['n'.repeat(600)] }), '600 is fine');
+});
+
+// ---------------------------------------------------------------------------------------------------
+// In the reply (design §1, §7)
+
+test('the card replaces its stretch of the reply once; intro and closing stay; no slot title line; Show as text gives it back', async () => {
+ const { reply, results } = m.recipe;
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results, messageId: 'm1' }));
+ const t = v.host.textContent;
+ assert.ok(v.host.querySelector('[data-smart-result="recipe"]'));
+ assert.ok(t.startsWith('Here is a cosy one-pot dinner for tonight.'));
+ assert.ok(t.includes('Want a quick flatbread to go with it?'));
+ assert.equal(t.split('Golden squash and lentil stew').length - 1, 1, 'the dish name shows once');
+ assert.equal(t.split('Sweet potato works').length - 1, 1, 'notes once');
+ assert.equal(v.host.querySelectorAll('h2').length, 0, 'the reply’s heading went into the card');
+ assert.equal(v.host.querySelector('[data-recipe-copy="recipe"]') !== null, true);
+ assert.equal([...v.host.querySelectorAll('button')].some((b) => b.textContent.includes('Copy data')), false, 'Copy data is not shown for a recipe');
+ const asText = [...v.host.querySelectorAll('button')].find((b) => b.textContent.includes('Show as text'));
+ await click(asText);
+ assert.equal(v.host.querySelector('[data-smart-result="recipe"]'), null);
+ assert.equal(v.host.querySelectorAll('h2').length, 1, 'the stretch as written');
+ assert.ok(v.host.textContent.includes('1 tbsp olive oil'));
+ localStorage.clear();
+});
+
+test('a section whose lists are not where it says, or an invalid recipe, leaves the reply as text', async () => {
+ const { reply, results } = m.recipe;
+ const blk = results.blocks[0];
+ const off = { version: 1, blocks: [{ ...blk, source: { ...blk.source, index: 7 } }] };
+ const a = await mount(h(m.MarkdownRenderer, { content: reply, results: off, messageId: 'm1' }));
+ assert.equal(a.host.querySelector('[data-smart-result="recipe"]'), null);
+ assert.equal(a.host.querySelectorAll('h2').length, 1);
+ const bad = { version: 1, blocks: [{ ...blk, steps: [] }] };
+ const b = await mount(h(m.MarkdownRenderer, { content: reply, results: bad, messageId: 'm2' }));
+ assert.equal(b.host.querySelector('[data-smart-result="recipe"]'), null);
+ assert.ok(b.host.textContent.includes('Warm the oil'), 'the reply’s own method');
+ assert.equal(b.host.querySelectorAll('h2').length, 1);
+});
+
+test('edge states render: long name wraps, 30 steps never fold and badges reach 30', async () => {
+ const long = await mount(card(m.validRecipe(m.RECIPE_EDGES.longName.results.blocks[0])));
+ assert.match(long.host.querySelector('h3').className, /overflow-wrap:anywhere/);
+ const thirty = await mount(card(m.validRecipe(m.RECIPE_EDGES.thirty.results.blocks[0]), 'm30'));
+ assert.equal(thirty.host.querySelectorAll('[data-step]').length, 30);
+ assert.ok(thirty.host.querySelector('[data-step="s30"]').textContent.includes('30'));
+ assert.ok(thirty.host.textContent.includes('30 steps'));
+});
+
+test('contract.md §3 exactly: the card sits at root child 1 and hides 1–11; intro and question stay', async () => {
+ const { reply, results } = m.RECIPE_CONTRACT;
+ const blk = m.validRecipe(results.blocks[0]);
+ assert.ok(blk, 'the server’s example passes validRecipe');
+ const v = await mount(h(m.MarkdownRenderer, { content: reply, results, messageId: 'mc' }));
+ const t = v.host.textContent;
+ assert.ok(t.startsWith("Here's a cosy stew for tonight."), 'the intro stays, before the card');
+ assert.ok(t.endsWith('Want a vegan version?'), 'the question stays, after it');
+ assert.ok(v.host.querySelector('[data-smart-result="recipe"]'));
+ assert.equal(v.host.querySelectorAll('h2').length, 0, 'root children 1–11 are not drawn');
+ assert.deepEqual([...v.host.querySelectorAll('h3')].map((e) => e.textContent), ['Golden squash and lentil stew'], 'only the card’s name');
+ assert.equal(t.split('Keeps 3 days').length - 1, 1, 'notes once');
+ assert.deepEqual(amounts(v.host), ['1 tbsp olive oil', '1 onion, diced', '2 cloves garlic, crushed', '500 g squash, peeled and cubed', '1 can (400 g) chopped tomatoes', 'Salt to taste', '½ cup plain yogurt', '1–2 tsp chili flakes'], 'qty + text is each reply line');
+ assert.ok(v.host.textContent.includes('For the topping'));
+ assert.equal(v.host.querySelectorAll('[data-step]').length, 4);
+ await click(btn(v.host, 'More servings'));
+ await click(btn(v.host, 'More servings'));
+ assert.deepEqual(amounts(v.host).slice(0, 2), ['1½ tbsp olive oil', '1½ onions, diced']);
+});
diff --git a/frontend/tests/showOnceTrial.test.mjs b/frontend/tests/showOnceTrial.test.mjs
index 5fa9b9c4..04f184bb 100644
--- a/frontend/tests/showOnceTrial.test.mjs
+++ b/frontend/tests/showOnceTrial.test.mjs
@@ -135,3 +135,38 @@ test('a skill already approved or rejected gets no card; a rejection elsewhere r
assert.equal(card(v.host), null);
v.unmount();
});
+
+test('S-F7: a trial reply that came back empty names the engine in muted text, not an alert', async () => {
+ pending = [skill()];
+ const empty = { ...result, text: '', trial: undefined, meta: JSON.stringify({ trial: { ...tr, outcome: 'failed' } }) };
+ const rook = { id: 'k_rook', name: 'Rook', title: '', avatar_sprite: '', preferred_model: 'claude/claude-opus-5-5' };
+ let v = mount({ messages: [you, sysline, empty], kwants: [rook] });
+ await settle();
+ const bubble = v.host.querySelector('[data-message-id="k1"]');
+ const line = bubble.querySelector('[data-empty-trial-reply]');
+ assert.ok(line, 'the empty-reply line');
+ assert.equal(line.textContent, "Claude sent back an empty reply, so this try didn't finish. Try it again before you approve.");
+ assert.match(line.className, /text-zinc-400/);
+ assert.doesNotMatch(line.className, /red/);
+ assert.equal(line.closest('[role="alert"]'), null, 'not an alert');
+ assert.equal(line.querySelector('svg').getAttribute('aria-hidden'), 'true');
+ assert.ok(card(v.host), 'the trial card still follows with Approve');
+ v.unmount();
+
+ v = mount({ messages: [you, sysline, empty], kwants: [{ ...rook, preferred_model: 'auto' }] });
+ await settle();
+ assert.equal(v.host.querySelector('[data-empty-trial-reply]').textContent, "The engine sent back an empty reply, so this try didn't finish. Try it again before you approve.");
+ v.unmount();
+
+ v = mount({ messages: [you, sysline, { ...result, text: ' ' }, { ...later, text: '' }], kwants: [{ ...rook, preferred_model: 'codex' }] });
+ await settle();
+ assert.match(v.host.querySelector('[data-message-id="k1"]').textContent, /Codex sent back an empty reply/);
+ assert.equal(v.host.querySelector('[data-message-id="k2"] [data-empty-trial-reply]'), null, 'only trial replies');
+ v.unmount();
+
+ v = mount({ messages: [you, sysline, result] });
+ await settle();
+ assert.equal(v.host.querySelector('[data-empty-trial-reply]'), null, 'a reply with text shows the text');
+ assert.match(v.host.querySelector('[data-message-id="k1"]').textContent, /Imported 42 orders\./);
+ v.unmount();
+});
diff --git a/frontend/tests/smartResults.test.mjs b/frontend/tests/smartResults.test.mjs
index 573665d9..73d31d02 100644
--- a/frontend/tests/smartResults.test.mjs
+++ b/frontend/tests/smartResults.test.mjs
@@ -460,7 +460,7 @@ test('a task list only becomes a checklist; nested or quoted lists stay markdown
test('fixtures: one per block type, every block well formed; Pixel’s types render from them', async () => {
const types = new Set(Object.values(m.FIXTURES).map((f) => f.results.blocks[0].type));
- assert.deepEqual([...types].sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'steps', 'verification']);
+ assert.deepEqual([...types].sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'recipe', 'steps', 'verification']);
const strings = (v) => (typeof v === 'string' ? [v] : Array.isArray(v) ? v.flatMap(strings) : v && typeof v === 'object' ? Object.values(v).flatMap(strings) : []);
for (const [name, f] of Object.entries(m.FIXTURES)) {
assert.equal(m.resultBlocks(f.results).length, 1, name);
@@ -471,7 +471,7 @@ test('fixtures: one per block type, every block well formed; Pixel’s types ren
assert.ok(v.host.querySelector('[data-smart-frame]'), `${name} renders`);
}
}
- assert.deepEqual(Object.keys(m.REGISTRY).sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'steps', 'verification']);
+ assert.deepEqual(Object.keys(m.REGISTRY).sort(), ['cards', 'chart', 'comparison', 'facts', 'files', 'findings', 'metrics', 'recipe', 'steps', 'verification']);
});
test('a slot block renders after the reply with its title; Show as text gives its data as markdown', async () => {
@@ -517,7 +517,7 @@ test('generic Copy data: every fixture exports CSV and Markdown with one row per
for (const [name, f] of Object.entries(m.FIXTURES)) {
const block = f.results.blocks[0];
const rows = m.blockRows(block);
- const n = (block.rows ?? block.points ?? block.checks ?? block.items).length;
+ const n = (block.rows ?? block.points ?? block.checks ?? block.items ?? block.ingredients).length;
assert.equal(rows.length, n, name);
assert.equal(m.blockCsv(block).trim().split('\n').length, n + 1, `${name}: header + rows`);
assert.ok(m.blockMarkdown(block).length > 0, name);
diff --git a/frontend/tests/takeoverBlurRelease.test.mjs b/frontend/tests/takeoverBlurRelease.test.mjs
index 195fc6ff..83738b0c 100644
--- a/frontend/tests/takeoverBlurRelease.test.mjs
+++ b/frontend/tests/takeoverBlurRelease.test.mjs
@@ -29,7 +29,7 @@ const act = async (fn) => {
await settle();
};
-async function renderStage() {
+async function renderStage(extra = {}) {
const sent = [];
const stream = {
connected: true, controlling: true, busy: false, error: null, frame: { id: 1, width: 800, height: 600 }, location: null, tapFocus: null,
@@ -41,7 +41,7 @@ async function renderStage() {
const root = m.createRoot(host);
await act(async () => {
root.render(m.React.createElement(m.BrowserTakeoverStage, {
- botName: 'Ada', pageUrl: 'https://www.tiktok.com/login', stream, image: 'data:image/png;base64,AAAA', onHandBack() {}, onRetryControl() {},
+ botName: 'Ada', pageUrl: 'https://www.tiktok.com/login', stream, image: 'data:image/png;base64,AAAA', onHandBack() {}, onRetryControl() {}, ...extra,
}));
});
const stage = document.querySelector('[data-browser-stage]');
@@ -83,3 +83,20 @@ test('every held button is released, and a blur with none held sends nothing', a
assert.equal(s.presses().length, 4);
await s.unmount();
});
+
+// Rigel's F4 (0.7.7 Watch live): during Take over the panel's switcher, and its "Hand back first"
+// tooltip, are under this stage. With other chats browsing, Hand back says it where a mouse and a
+// screen reader reach it; with none it says nothing extra.
+test('F4: with other chats browsing, Hand back says to hand back first to switch browser', async () => {
+ let s = await renderStage({ othersBrowsing: true });
+ let btn = [...document.querySelectorAll('[data-browser-takeover] button')].find((b) => /Hand back/.test(b.textContent));
+ assert.equal(btn.title, 'Hand back first to switch browser');
+ const hint = document.getElementById(btn.getAttribute('aria-describedby'));
+ assert.equal(hint?.textContent, 'Hand back first to switch browser');
+ await s.unmount();
+ s = await renderStage();
+ btn = [...document.querySelectorAll('[data-browser-takeover] button')].find((b) => /Hand back/.test(b.textContent));
+ assert.equal(btn.title, '');
+ assert.equal(btn.getAttribute('aria-describedby'), null);
+ await s.unmount();
+});
diff --git a/frontend/tests/takeoverHeld.test.mjs b/frontend/tests/takeoverHeld.test.mjs
new file mode 100644
index 00000000..a99b0ae6
--- /dev/null
+++ b/frontend/tests/takeoverHeld.test.mjs
@@ -0,0 +1,134 @@
+// 0.7.6 "Takeover refused" (copy.md, Lin's #429): Take over in a second window while the person
+// already holds the browser in another one used to say "@team is finishing a step…" and retry every
+// second, which can never win. The server's refusal now carries code held_by_person: the pane shows
+// Mira's sentence in the same violet box with a static Hand icon, no spinner and no retry. bot_busy
+// and an older server's error with no code keep today's wait-and-retry.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLImageElement', 'Element', 'Node', 'Event', 'FocusEvent', 'MouseEvent', 'KeyboardEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.ResizeObserver = g.window.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} };
+g.window.matchMedia = (q) => ({ matches: false, media: q, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
+g.fetch = g.window.fetch = async () => ({ ok: false, status: 404, json: async () => ({}), text: async () => '' });
+
+const sockets = [];
+class FakeWebSocket {
+ static OPEN = 1;
+ constructor(url) { this.url = url; this.readyState = 1; this.sent = []; this.bufferedAmount = 0; sockets.push(this); }
+ send(text) { this.sent.push(JSON.parse(text)); }
+ close() { this.readyState = 3; }
+ receive(message) { this.onmessage?.({ data: JSON.stringify(message) }); }
+}
+g.WebSocket = g.window.WebSocket = FakeWebSocket;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { flushSync } from 'react-dom';
+ export { VirtualMachinePane, TAKEOVER_RETRY_MS } from './src/components/VirtualMachinePane';
+ export { BOT_BUSY_TEXT, HELD_BY_PERSON_TEXT, takeoverRefusedText } from './src/useBrowserStream';
+`);
+const settle = async () => { for (let i = 0; i < 30; i++) await new Promise((r) => setTimeout(r, 0)); };
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+const HELD = "You're controlling this browser in another window. Press Hand back there to take over here.";
+const BUSY_WIRE = 'Browser is controlled by a person. Retry after control is returned.';
+
+test('the held sentence is Mira\'s copy, word for word', () => {
+ assert.equal(m.HELD_BY_PERSON_TEXT, HELD);
+});
+
+test('a refusal maps by code; no code falls back to the text, then to the busy bot', () => {
+ assert.equal(m.takeoverRefusedText({ code: 'held_by_person', error: HELD }), HELD);
+ assert.equal(m.takeoverRefusedText({ code: 'bot_busy', error: BUSY_WIRE }), m.BOT_BUSY_TEXT);
+ assert.equal(m.takeoverRefusedText({ code: 'failed', error: 'Something else' }), m.BOT_BUSY_TEXT);
+ assert.equal(m.takeoverRefusedText({ error: BUSY_WIRE }), m.BOT_BUSY_TEXT, 'an older server: as today');
+ assert.equal(m.takeoverRefusedText({ error: HELD }), HELD, 'the held sentence without a code still reads as held');
+ // A code wins over the text: bot_busy never turns into the held note
+ assert.equal(m.takeoverRefusedText({ code: 'bot_busy', error: 'in another window' }), m.BOT_BUSY_TEXT);
+});
+
+async function openPane() {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const root = m.createRoot(host);
+ m.flushSync(() => root.render(m.React.createElement(m.VirtualMachinePane, {
+ isOpen: true, onClose: () => {}, teamId: 'k1', teamName: 'Rook', isRunning: true,
+ })));
+ await settle();
+ const ws = sockets.at(-1);
+ assert.ok(ws, 'the pane opened a live-view socket');
+ ws.onopen?.();
+ ws.receive({ type: 'location', url: 'https://example.com/', title: 'Example' });
+ ws.receive({ type: 'frame', id: 1, image: 'AAAA', width: 1280, height: 800 });
+ await settle();
+ const takeOver = host.querySelector('[data-takeover-button]');
+ assert.ok(takeOver && /Take over/.test(takeOver.textContent), 'the pane offers Take over');
+ takeOver.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ const takes = () => ws.sent.filter((s) => s.action === 'take_control').length;
+ assert.equal(takes(), 1, 'pressing Take over asks once');
+ return { host, root, ws, takes };
+}
+
+test('held_by_person: the sentence in the violet box, a static Hand, no spinner and no retry', async () => {
+ const { host, root, ws, takes } = await openPane();
+ ws.receive({ type: 'error', error: HELD, code: 'held_by_person' });
+ await settle();
+
+ const box = host.querySelector('[data-takeover-wait]');
+ assert.ok(box, 'the takeover notice shows');
+ assert.ok(box.hasAttribute('data-takeover-held'));
+ assert.equal(box.getAttribute('role'), 'status');
+ assert.ok(box.textContent.includes(HELD));
+ assert.ok(!/finishing a step/i.test(box.textContent));
+ assert.ok(!/Trying every second/i.test(host.textContent), 'no "Trying every second" line');
+ assert.equal(box.querySelector('.animate-spin'), null, 'no spinner');
+ assert.ok(box.querySelector('svg.lucide-hand'), 'the static Hand icon');
+ assert.ok(!host.querySelector('[role="alert"]')?.textContent.includes(HELD), 'not also shown as a red error');
+ assert.ok(box.querySelector('[aria-label="Close"]'), 'the × close stays');
+
+ await sleep(m.TAKEOVER_RETRY_MS * 2.5);
+ await settle();
+ assert.equal(takes(), 1, 'no retry while the other window holds it');
+
+ // The other window hands back: nothing moves here until the person presses Take over again
+ ws.receive({ type: 'control', active: false });
+ await settle();
+ await sleep(m.TAKEOVER_RETRY_MS * 1.5);
+ assert.equal(takes(), 1, 'this window does not take over by itself');
+
+ box.querySelector('[aria-label="Close"]').dispatchEvent(new window.MouseEvent('click', { bubbles: true }));
+ await settle();
+ assert.equal(host.querySelector('[data-takeover-held]'), null, '× closes the note');
+ root.unmount();
+});
+
+for (const [name, message] of [
+ ['bot_busy', { type: 'error', error: BUSY_WIRE, code: 'bot_busy' }],
+ ['no code (an older server)', { type: 'error', error: BUSY_WIRE }],
+]) {
+ test(`${name}: still "finishing a step" with the spinner, and it retries`, async () => {
+ const { host, root, ws, takes } = await openPane();
+ ws.receive(message);
+ await settle();
+ const box = host.querySelector('[data-takeover-wait]');
+ assert.ok(box, 'the takeover notice shows');
+ assert.equal(box.hasAttribute('data-takeover-held'), false);
+ assert.ok(/Rook is finishing a step/.test(box.textContent));
+ assert.ok(box.querySelector('.animate-spin'), 'the spinner');
+ assert.ok(/Trying every second/.test(box.textContent));
+
+ await sleep(m.TAKEOVER_RETRY_MS + 300);
+ await settle();
+ assert.ok(takes() >= 2, 'it asked again after a second');
+ root.unmount();
+ });
+}
diff --git a/frontend/tests/teamTemplates.test.mjs b/frontend/tests/teamTemplates.test.mjs
index e9823842..2be0dee0 100644
--- a/frontend/tests/teamTemplates.test.mjs
+++ b/frontend/tests/teamTemplates.test.mjs
@@ -44,7 +44,7 @@ const m = await loadBundled(`
export * as fx from './src/teams/suggestFixtures';
export { TEMPLATES_FIXTURE, TEMPLATES_WIRE } from './src/teams/templateFixtures';
export { TeamPreviewSheet } from './src/components/TeamPreviewSheet';
- export { TeamNeedsCard, TeamCreatedToast, UndoTeamConfirm } from './src/components/TeamNeedsCard';
+ export { TeamNeedsCard, TeamCreatedToast, UndoTeamConfirm, archivedChatLine } from './src/components/TeamNeedsCard';
export { TemplateWelcome, TemplateTiles, TemplateSidebarBox } from './src/components/TeamTemplatePicks';
export { ReadyTeamsProvider, TeamNeedsTop, madeFromRow, useNeedsContext } from './src/components/ReadyTeams';
export { ReadyTeamsTiles, SuggestMembersButton, ReadyTeamsSidebarBox } from './src/components/ReadyTeamsEntry';
@@ -77,7 +77,7 @@ const mount = async (el) => {
return { host, root, rerender: async (e) => (root.render(e), await settle()), unmount: () => (root.unmount(), host.remove()) };
};
const byText = (root, sel, re) => [...root.querySelectorAll(sel)].find((el) => re.test(el.textContent ?? ''));
-const primary = (root) => byText(root, 'button', /^(Create team|Add \d|Add bots|Try again|Creating)/);
+const primary = (root) => byText(root, 'button', /^(Create team|Add \d|Add bots|Try again|Pick another folder|Creating)/);
const use = (opts) => {
const calls = [];
m.setTeamsTransport(fx.fixtureTransport(opts, calls));
@@ -633,6 +633,55 @@ test('the Undo confirm says where a chat with messages goes: under Channels as #
v.unmount();
});
+test('N-6: the Undo confirm names the chat the server gives back, -2 included, and drops the line on null', async () => {
+ const props = { label: 'Inbox', handle: 'inbox', teamName: 'inbox', botNames: ['Drafter'], skills: 1, routine: false, messages: 4, onKeep() {}, onUndo() {} };
+ // #archived-team-inbox is taken, so the server's preview says -2: the line must say -2 too.
+ const v = await mount(h(m.UndoTeamConfirm, { ...props, archivedChat: 'archived-team-inbox-2' }));
+ let d = document.querySelector('[data-undo-confirm]');
+ assert.match(d.textContent, /The chat has 4 messages, so it’s kept, not deleted: it moves under Channels as #archived-team-inbox-2\./);
+ assert.equal(d.querySelector('[data-archived-chat]').dataset.archivedChat, 'archived-team-inbox-2');
+ // A server name is used as is, never rebuilt from the team name.
+ await v.rerender(h(m.UndoTeamConfirm, { ...props, teamName: 'Inbox', archivedChat: 'ARCHIVED-team-inbox-3' }));
+ assert.match(document.querySelector('[data-undo-confirm]').textContent, /as #ARCHIVED-team-inbox-3\./);
+ // null: Undo deletes the chat or leaves it alone, so there's no archive line at all.
+ await v.rerender(h(m.UndoTeamConfirm, { ...props, archivedChat: null }));
+ d = document.querySelector('[data-undo-confirm]');
+ assert.equal(d.querySelector('[data-archived-chat]'), null);
+ assert.doesNotMatch(d.textContent, /archived|kept, not deleted/);
+ // An older server without the field: the old guess, only when the chat has messages.
+ await v.rerender(h(m.UndoTeamConfirm, { ...props }));
+ assert.match(document.querySelector('[data-undo-confirm]').textContent, /as #archived-team-inbox\./);
+ v.unmount();
+
+ assert.equal(m.archivedChatLine('archived-team-inbox-2', 4, 'inbox'), 'archived-team-inbox-2');
+ assert.equal(m.archivedChatLine('#archived-team-inbox-2', 4, 'inbox'), 'archived-team-inbox-2', 'no double #');
+ assert.equal(m.archivedChatLine(null, 4, 'inbox'), null);
+ assert.equal(m.archivedChatLine(' ', 4, 'inbox'), null);
+ assert.equal(m.archivedChatLine(undefined, 0, 'inbox'), null);
+ assert.equal(m.archivedChatLine(undefined, 2, 'inbox'), 'archived-team-inbox');
+});
+
+test('N-6: Undo through the provider reads archived_chat from the preview and shows it in the confirm', async () => {
+ const info = { template_id: 'inbox', action_id: 'act_i', created_at: new Date(Date.now() - 60_000).toISOString(), undo_until: new Date(Date.now() + 3_600_000).toISOString(), can_undo: true, blocked: [], removes: { bots: ['Drafter'], skills: 1, routines: 0, handle: 'inbox' }, chat_messages: 3, archived_chat: 'archived-team-inbox-2', also_in: [], edited_skills: [], needs_done: [] };
+ m.setTeamsTransport(async (url) => {
+ if (url.startsWith('/api/team-templates?')) return { status: 200, body: { templates: m.TEMPLATES_WIRE } };
+ if (url.startsWith('/api/teams/team_i/template')) return { status: 200, body: info };
+ return { status: 404, body: { code: 'not_a_template_team', error: 'no' } };
+ });
+ const team = { id: 'team_i', name: 'inbox' };
+ const v = await mount(h(m.ReadyTeamsProvider, { space: 'spc_demo', bots: [], teams: [team], onChanged() {}, onOpenTeam() {} }, h(m.TeamNeedsTop, { team, canRun: true, personPosts: 0, onAddAccount() {}, onOpenNeed() {} })));
+ await settle(30);
+ const undo = document.querySelector('[aria-label="Undo team @inbox"]');
+ assert.ok(undo, 'the Needs card offers Undo');
+ await click(undo);
+ await settle(30);
+ const d = document.querySelector('[data-undo-confirm]');
+ assert.ok(d, 'a chat with messages asks first');
+ assert.match(d.textContent, /moves under Channels as #archived-team-inbox-2\./);
+ assert.doesNotMatch(d.textContent, /#archived-team-inbox\./);
+ v.unmount();
+});
+
test('T5: the Needs card lists what is open, opens each, and offers Undo for a day', async () => {
const inbox = m.TEMPLATES_FIXTURE.find((t) => t.id === 'inbox');
const opened = [];
@@ -793,3 +842,39 @@ test('U-5: Suggest refused with folder_in_use (or bad_path) shows the server’s
assert.doesNotMatch(root.textContent, /The server stopped/);
v.unmount();
});
+
+test('N-5: after folder_in_use the main button picks another folder instead of "Try again"', async () => {
+ const said = 'that folder overlaps team f8 in the space "Lab"; spaces never share a folder';
+ // Suggest refused: Pick another folder, and it calls onPickFolder (no second read of the same folder).
+ let calls = failing(400, { error: said, code: 'folder_in_use', field: 'workspace_path' }, { failSuggest: true });
+ let picked = 0;
+ let v = await mount(sheet({ kind: 'suggest', workspace_path: '/tmp/example-projects/f8' }, { onPickFolder: () => picked++ }).el);
+ let root = document.querySelector('[data-team-sheet="suggest"]');
+ let btn = primary(root);
+ assert.equal(btn.textContent, 'Pick another folder');
+ assert.equal(btn.disabled, false);
+ const reads = calls.filter((c) => c.url.startsWith('/api/teams/suggest')).length;
+ await click(btn);
+ assert.equal(picked, 1);
+ assert.equal(calls.filter((c) => c.url.startsWith('/api/teams/suggest')).length, reads, 'the same folder is not read again');
+ v.unmount();
+ // Create refused after a good read: the same.
+ calls = failing(400, { error: said, code: 'folder_in_use', field: 'workspace_path' });
+ picked = 0;
+ v = await mount(sheet({ kind: 'suggest', workspace_path: '/tmp/example-projects/f8' }, { onPickFolder: () => picked++ }).el);
+ root = document.querySelector('[data-team-sheet="suggest"]');
+ await click(primary(root));
+ assert.match(root.textContent, /Couldn’t create the team\. Nothing was created\./);
+ btn = primary(root);
+ assert.equal(btn.textContent, 'Pick another folder');
+ await click(btn);
+ assert.equal(picked, 1);
+ assert.equal(creates(calls).length, 1, 'no second create with the same folder');
+ v.unmount();
+ // Any other refusal still offers Try again.
+ failing(400, { error: 'that isn’t an absolute path to a folder kwant can read', code: 'bad_path', field: 'workspace_path' }, { failSuggest: true });
+ v = await mount(sheet({ kind: 'suggest', workspace_path: '/tmp/example-projects/f8' }, { onPickFolder: () => picked++ }).el);
+ root = document.querySelector('[data-team-sheet="suggest"]');
+ assert.match(primary(root).textContent, /Try again/);
+ v.unmount();
+});
diff --git a/frontend/tests/tickets.test.mjs b/frontend/tests/tickets.test.mjs
index 9276ecb0..ae5172f3 100644
--- a/frontend/tests/tickets.test.mjs
+++ b/frontend/tests/tickets.test.mjs
@@ -6,6 +6,7 @@ import assert from 'node:assert/strict';
import test, { afterEach } from 'node:test';
import { JSDOM } from 'jsdom';
import { loadBundled } from './bundle.mjs';
+import { ENGINE_REFUSED_MESSAGE } from './fixtures/tickets.mjs';
const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });
const g = globalThis;
@@ -639,3 +640,36 @@ test('Off: a 409 jira_off from Start shows the plain sentence on the card, never
assert.equal(n.getAttribute('role'), 'alert');
assert.doesNotMatch(host.textContent, /jira_off|HTTP 409/);
});
+
+// ---------------------------------------------------------------------------------------------------
+// 0.7.6 follow-ups: D8's last two names, D6's engine_refused
+
+test('D8: the brief’s own toggle and "See the review" name their ticket too', async () => {
+ const host = await mount(m.TicketCard, { ...N, ticket: T('brief_ready'), brief: B(fx.BRIEF_ANSWERED) });
+ const toggle = host.querySelector('.tk-brief header button');
+ assert.ok(toggle, 'the brief toggle');
+ const was = toggle.getAttribute('aria-label');
+ assert.match(was, /^(Show|Hide) brief TRAIL-142$/);
+ await click(toggle);
+ const now = host.querySelector('.tk-brief header button').getAttribute('aria-label');
+ assert.notEqual(now, was, 'it says which way it goes');
+ assert.match(now, /^(Show|Hide) brief TRAIL-142$/);
+ const review = html(m.TicketCard, { ...N, ticket: T('landed', { work: { matches: 'not_met' } }), onOpenReview: () => {} });
+ assert.match(review, /aria-label="See the review TRAIL-142"[^>]*>\s*See the review/);
+ // Without a key (older callers) the toggle keeps its visible words as its name.
+ assert.doesNotMatch(html(m.TicketBrief, { brief: B(fx.BRIEF_ANSWERED) }), /aria-label="(Show|Hide) brief/);
+});
+
+test('D6: an engine_refused card shows the server’s sentence word for word, with Try again', () => {
+ const t = m.parseTicket(fx.TICKET_ENGINE_REFUSED(ENGINE_REFUSED_MESSAGE));
+ assert.equal(t.error.code, 'engine_refused');
+ const out = html(m.TicketCard, { ...N, ticket: t, onRetry: () => {} });
+ const plain = out.replace(/<[^>]+>/g, '').replace(/&#x27;/g, "'");
+ assert.ok(plain.includes(ENGINE_REFUSED_MESSAGE), 'the message, unchanged');
+ assert.equal(t.error.message, ENGINE_REFUSED_MESSAGE, 'under the 300-character cap, so not cut');
+ assert.match(out, /aria-label="Try again TRAIL-142"/);
+ assert.doesNotMatch(plain, /Jira didn’t answer|Work on TRAIL-142 stopped/);
+ // Any code the card doesn't know still shows its message as is.
+ const other = m.parseTicket(fx.ticket('failed', { error: { code: 'something_new', message: 'A sentence kwant wrote.' } }));
+ assert.match(html(m.TicketCard, { ...N, ticket: other }), /A sentence kwant wrote\./);
+});
diff --git a/frontend/tests/whatsNew076.test.mjs b/frontend/tests/whatsNew076.test.mjs
new file mode 100644
index 00000000..7ce75e5d
--- /dev/null
+++ b/frontend/tests/whatsNew076.test.mjs
@@ -0,0 +1,324 @@
+// 0.7.6 "What's new in kwant X.Y.Z" (next-076/whats-new/spec.md): the content checks, the show-once rules
+// (an upgrade shows it, a brand-new person never sees it, an existing person with no key does, it waits
+// while a dialog is open, once per version), the sheet, the update banner's button and Settings › About.
+import assert from 'node:assert/strict';
+import test, { afterEach } from 'node:test';
+import { readFileSync, readdirSync } from 'node:fs';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_default', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+
+const dir = new URL('../src/whatsnew/', import.meta.url);
+const files = readdirSync(dir).filter((n) => n.endsWith('.json'));
+const real = Object.fromEntries(files.map((n) => [n.slice(0, -5), JSON.parse(readFileSync(new URL(n, dir), 'utf8'))]));
+
+const hl = (id, over = {}) => ({ id, title: `Title ${id}`, text: `Text for ${id}.`, image: null, open: null, ...over });
+const v076 = {
+ version: '0.7.6',
+ date: '2026-11-14',
+ highlights: [hl('recipe', { open: 'settings/teams' }), hl('goals'), hl('phone')],
+ fixes: ['Fix one.', 'Fix two.', 'Fix three.', 'Fix four.', 'Fix five.', 'Fix six.'],
+};
+const content = {
+ entries: [real['0.7.5'], v076],
+ changelog: { '0.7.6': '### Added\n- **Recipe cards.** Example text.', '0.7.5': '### Fixed\n- Older.' },
+};
+
+const s = await loadBundled(`export * from './src/whatsNewSheet';`);
+const ui = await loadBundled(
+ `
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export { renderToStaticMarkup } from 'react-dom/server.browser';
+ export { WhatsNewHost, WhatsNewSheetView, WhatsNewAboutView, WhatsNewAbout, hasWhatsNew } from './src/components/WhatsNewSheet';
+ export { AppUpdateBannerView } from './src/components/AppUpdateBanner';
+ export { openWhatsNew, SEEN_KEY } from './src/whatsNewSheet';
+ export { WHATS_NEW } from './src/whatsNewContent';
+`,
+ { whatsNew: content },
+);
+const { React, createRoot } = ui;
+// React is bundled as a production build (no act): render, then let effects and timers run.
+const act = async (fn) => {
+ await fn();
+};
+
+const memStore = (init = {}) => {
+ const m = new Map(Object.entries(init));
+ return { m, getItem: (k) => m.get(k) ?? null, setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k) };
+};
+
+// ---------- content ----------
+
+test('validator: every bundled whatsnew file keeps the limits, its name matches its version, and every "open" is an app place', () => {
+ assert.ok(files.includes('0.7.5.json'), 'the 0.7.5 backfill ships');
+ for (const [v, e] of Object.entries(real)) {
+ assert.deepEqual(s.validateEntry(e, v), [], `${v}.json`);
+ for (const h of e.highlights) if (h.open) assert.ok(s.highlightView(h), `${v} ${h.id}: ${h.open}`);
+ }
+ assert.equal(real['0.7.5'].highlights.find((h) => h.id === 'teams').open, 'settings/teams');
+ assert.equal(real['0.7.5'].highlights.find((h) => h.id === 'telegram').open, 'settings/connections');
+});
+
+test('validator: names each broken limit', () => {
+ const ok = { version: '0.7.6', date: '2026-11-14', highlights: [hl('a'), hl('b')], fixes: [] };
+ assert.deepEqual(s.validateEntry(ok), []);
+ const bad = (over) => s.validateEntry({ ...ok, ...over });
+ assert.match(bad({ highlights: [hl('a')] })[0], /highlights: 1, needs 2–6/);
+ assert.match(bad({ highlights: 'abcdefg'.split('').map((x) => hl(x)) })[0], /highlights: 7/);
+ assert.match(bad({ highlights: [hl('a', { title: 'x'.repeat(61) }), hl('b')] })[0], /title is 61 characters, max 60/);
+ assert.deepEqual(bad({ highlights: [hl('a', { title: 'é'.repeat(60) }), hl('b')] }), [], 'characters, not bytes');
+ assert.match(bad({ highlights: [hl('a', { text: 'x'.repeat(201) }), hl('b')] })[0], /text is 201 characters, max 200/);
+ assert.match(bad({ highlights: [hl('a'), hl('a')] })[0], /used twice/);
+ assert.match(bad({ highlights: [hl('a', { image: 'a.png' }), hl('b')] })[0], /\.webp/);
+ assert.match(bad({ highlights: [hl('a', { open: 'settings/nope' }), hl('b')] })[0], /in-app place/);
+ assert.match(bad({ highlights: [hl('a', { open: 'members' }), hl('b')] })[0], /in-app place/, 'old aliases are not allowed');
+ assert.match(bad({ fixes: Array(16).fill('x') })[0], /fixes: 16, max 15/);
+ assert.match(bad({ fixes: ['x'.repeat(141)] })[0], /fixes\[0\] is 141 characters, max 140/);
+ assert.match(bad({ version: '0.7' })[0], /X\.Y\.Z/);
+ assert.match(s.validateEntry(ok, '0.7.5')[0], /doesn't match the file name/);
+ assert.deepEqual(s.validateEntry([]), ['not a JSON object']);
+});
+
+test('the newest good file is the one shown; broken ones are left out', () => {
+ const list = s.sortEntries([real['0.7.5'], { ...v076, version: '0.7.10' }, v076, { version: '9.9.9' }]);
+ assert.deepEqual(list.map((e) => e.version), ['0.7.10', '0.7.6', '0.7.5']);
+ assert.equal(s.compareVersions('0.7.10', '0.7.9'), 1);
+ assert.equal(s.compareVersions('0.7.5', '0.7.5'), 0);
+ assert.equal(s.compareVersions('0.7.5', null), 1);
+ assert.deepEqual(ui.WHATS_NEW.map((e) => e.version), ['0.7.6', '0.7.5']);
+});
+
+test('All changes is only that version’s CHANGELOG section', () => {
+ const log = '# Changelog\n\n## Unreleased\n- soon\n\n## [Mac 0.7.6] - 2026-11-14\n\n### Added\n- New.\n\n## [Mac 0.7.5] - 2026-11-07\n- Old.\n';
+ assert.equal(s.changelogSection(log, '0.7.6'), '### Added\n- New.');
+ assert.equal(s.changelogSection(log, '0.7.5'), '- Old.');
+ assert.equal(s.changelogSection(log, '0.7.4'), null);
+ const repo = readFileSync(new URL('../../CHANGELOG.md', import.meta.url), 'utf8');
+ assert.match(s.changelogSection(repo, '0.7.5'), /^### Added\n- \*\*This Mac and your servers, side by side\.\*\*/);
+});
+
+// ---------- show once: the rules ----------
+
+test('show-once: an upgrade (a newer version than this device saw) shows it', () => {
+ assert.equal(s.decideOnLoad('0.7.5', '0.7.6', null), 'show', "doesn't wait on the account check");
+ assert.equal(s.decideOnLoad('0.7.5', '0.7.6', false), 'show');
+});
+
+test('show-once: a brand-new person never sees it; the version is recorded silently', () => {
+ assert.equal(s.decideOnLoad(null, '0.7.6', false), 'record');
+ const store = memStore();
+ s.markSeen('0.7.6', store);
+ assert.equal(s.decideOnLoad(s.seenVersion(store), '0.7.6', true), 'none', 'and not later either');
+});
+
+test('show-once: an existing person with no key yet (upgrading from 0.7.5) does see it', () => {
+ assert.equal(s.decideOnLoad(null, '0.7.6', true), 'show');
+ assert.equal(s.decideOnLoad(null, '0.7.6', null), 'wait', 'until the space has loaded');
+});
+
+test('show-once: once per version, per device; the stored version never moves back', () => {
+ const store = memStore();
+ s.markSeen('0.7.6', store);
+ assert.equal(store.m.get('kwant:whatsnew:seen'), '0.7.6');
+ assert.equal(s.decideOnLoad(s.seenVersion(store), '0.7.6', true), 'none');
+ s.markSeen('0.7.5', store);
+ assert.equal(store.m.get('kwant:whatsnew:seen'), '0.7.6', 'an older tab cannot reset it');
+ assert.equal(s.decideOnLoad(s.seenVersion(store), '0.7.7', true), 'show', 'the next version shows again');
+ assert.equal(s.decideOnLoad('0.7.6', null, true), 'none', 'nothing bundled');
+});
+
+test('otherDialogOpen sees modals, alerts and open <dialog>s, but not the sheet itself', () => {
+ const d = new JSDOM('<body><div data-whats-new><div role="dialog" aria-modal="true"></div></div></body>').window.document;
+ assert.equal(s.otherDialogOpen(d), false);
+ d.body.insertAdjacentHTML('beforeend', '<div role="alertdialog"></div>');
+ assert.equal(s.otherDialogOpen(d), true);
+ const d2 = new JSDOM('<body><dialog open></dialog></body>').window.document;
+ assert.equal(s.otherDialogOpen(d2), true);
+});
+
+// ---------- show once: in the app ----------
+
+let mounted = [];
+afterEach(async () => {
+ for (const r of mounted) await act(async () => r.unmount());
+ mounted = [];
+ document.body.innerHTML = '';
+ localStorage.clear();
+});
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));
+};
+async function host(props) {
+ const el = document.createElement('div');
+ document.body.append(el);
+ const root = createRoot(el);
+ mounted.push(root);
+ const render = async (p) => {
+ await act(async () => root.render(React.createElement(ui.WhatsNewHost, { onOpen: () => {}, ...props, ...p })));
+ await settle();
+ };
+ await render({});
+ return render;
+}
+const sheet = () => document.querySelector('[data-whats-new] [role="dialog"]');
+const click = async (el) => {
+ await act(async () => el.dispatchEvent(new MouseEvent('click', { bubbles: true })));
+ await settle();
+};
+
+test('host: an upgrade shows "What’s new in kwant bots 0.7.6" once, "Updated from 0.7.5", and stores the version', async () => {
+ localStorage.setItem(ui.SEEN_KEY, '0.7.5');
+ await host({ established: null });
+ assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 0.7.6');
+ assert.match(document.querySelector('[data-whats-new-eyebrow]').textContent, /^Updated from 0\.7\.5 · Nov 14$/);
+ assert.equal(localStorage.getItem(ui.SEEN_KEY), '0.7.6');
+ assert.equal(document.activeElement, sheet(), 'focus moves into the sheet');
+ await click(document.querySelector('[data-whats-new-done]'));
+ assert.equal(sheet(), null, 'Got it closes it');
+ await host({ established: true });
+ assert.equal(sheet(), null, 'and the next load shows nothing');
+});
+
+test('host: a brand-new person never sees it, and the version is recorded', async () => {
+ const render = await host({ established: null });
+ assert.equal(sheet(), null, 'waits while unknown');
+ assert.equal(localStorage.getItem(ui.SEEN_KEY), null);
+ await render({ established: false });
+ assert.equal(sheet(), null);
+ assert.equal(localStorage.getItem(ui.SEEN_KEY), '0.7.6');
+ await render({ established: true });
+ assert.equal(sheet(), null, 'adding an account later does not bring it up');
+});
+
+test('host: an existing person with no key sees it, with "Updated" and no earlier version named', async () => {
+ const render = await host({ established: null });
+ assert.equal(sheet(), null);
+ await render({ established: true });
+ assert.ok(sheet());
+ assert.match(document.querySelector('[data-whats-new-eyebrow]').textContent, /^Updated · Nov 14$/);
+});
+
+test('host: waits while another dialog is open, then opens when it closes', async () => {
+ localStorage.setItem(ui.SEEN_KEY, '0.7.5');
+ const other = document.createElement('div');
+ other.setAttribute('role', 'dialog');
+ other.setAttribute('aria-modal', 'true');
+ document.body.append(other);
+ await host({ established: true });
+ assert.equal(sheet(), null, 'not on top of a dialog');
+ assert.equal(localStorage.getItem(ui.SEEN_KEY), '0.7.5', 'not counted as seen yet');
+ const alert = document.createElement('div');
+ alert.setAttribute('role', 'alertdialog');
+ document.body.append(alert);
+ other.remove();
+ await settle();
+ assert.equal(sheet(), null, 'an approval still blocks it');
+ alert.remove();
+ await settle();
+ assert.ok(sheet(), 'opens once nothing is open');
+ assert.equal(localStorage.getItem(ui.SEEN_KEY), '0.7.6');
+});
+
+test('host: the banner and Settings open a version by hand; Show me opens the place and closes the sheet', async () => {
+ localStorage.setItem(ui.SEEN_KEY, '0.7.6');
+ const opened = [];
+ await host({ established: true, onOpen: (v) => opened.push(v) });
+ assert.equal(sheet(), null);
+ await act(async () => ui.openWhatsNew('0.7.5'));
+ await settle();
+ assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 0.7.5');
+ assert.equal(document.querySelector('[data-whats-new-eyebrow]').textContent, 'Released Nov 7', 'opened by hand: Released + date');
+ const show = [...sheet().querySelectorAll('button')].find((b) => b.getAttribute('aria-label') === 'Show me: Ready-made teams');
+ await click(show);
+ assert.deepEqual(opened, [{ kind: 'settings', scope: 'space', tab: 'teams' }]);
+ assert.equal(sheet(), null);
+ await act(async () => ui.openWhatsNew('0.6.0'));
+ await settle();
+ assert.equal(sheet(), null, 'a version with no file opens nothing');
+});
+
+// ---------- the sheet ----------
+
+const view = (props) =>
+ ui.renderToStaticMarkup(
+ React.createElement(ui.WhatsNewSheetView, { entry: v076, changelog: content.changelog['0.7.6'], phone: false, updatedFrom: '0.7.5', onClose() {}, onOpen() {}, ...props }),
+ );
+
+test('sheet: highlights, Show me only where there is a place, folded fixes, one main button', () => {
+ const html = view({});
+ assert.match(html, /role="dialog" aria-modal="true"/);
+ assert.equal((html.match(/data-highlight=/g) ?? []).length, 3);
+ assert.equal((html.match(/>Show me /g) ?? []).length, 1);
+ assert.match(html, /Smaller changes and fixes: 6/);
+ assert.equal((html.match(/Fix (one|two|three|four|five|six)\./g) ?? []).length, 3, 'more than 4 fixes: 3 shown');
+ assert.match(html, /Show 3 more/);
+ assert.equal((html.match(/Got it/g) ?? []).length, 1);
+ assert.match(html, /All changes/);
+ const four = view({ entry: { ...v076, fixes: v076.fixes.slice(0, 4) } });
+ assert.equal((four.match(/Fix (one|two|three|four)\./g) ?? []).length, 4, '4 fixes: not folded');
+ assert.doesNotMatch(four, /more/);
+ assert.doesNotMatch(view({ entry: { ...v076, fixes: [] } }), /Smaller changes/);
+ assert.doesNotMatch(view({ changelog: null }), /All changes/, 'no CHANGELOG section: no All changes');
+});
+
+test('sheet: All changes renders the CHANGELOG section as markdown, with the GitHub release link', () => {
+ const html = view({ initialPage: 'all' });
+ assert.match(html, /All changes in 0\.7\.6/);
+ assert.match(html, /<strong[^>]*>Recipe cards\.<\/strong>/);
+ assert.match(html, /href="https:\/\/github\.com\/alexsergivan\/kwant\/releases\/tag\/mac-v0\.7\.6"/);
+ assert.match(html, /What’s new<\/button>/, 'a way back');
+});
+
+test('sheet: phone is a bottom sheet with 44 px+ targets', () => {
+ const html = view({ phone: true });
+ assert.match(html, /flex items-end/);
+ assert.match(html, /rounded-t-\[20px\]/);
+ assert.match(html, /max-h-\[88vh\]/);
+ assert.match(html, /h-11 w-11/, 'close');
+ assert.match(html, /h-12 min-w-\[120px\][^"]*flex-1/, 'Got it fills the row');
+});
+
+test('sheet: the first picture leads, the others are thumbnails, all from /whatsnew/<version>/', () => {
+ const entry = { ...v076, highlights: [hl('a'), hl('b', { image: 'b.webp' }), hl('c', { image: 'c.webp' })] };
+ const html = view({ entry });
+ assert.match(html, /src="\/whatsnew\/0\.7\.6\/b\.webp" alt="" class="mb-3 block aspect-\[2\/1\]/);
+ assert.match(html, /src="\/whatsnew\/0\.7\.6\/c\.webp" alt="" class="mt-1 block aspect-\[16\/10\]/);
+});
+
+// ---------- the banner and Settings › About ----------
+
+test('banner: "See what’s new" on the "Updated to" bar only, and only when that version has a sheet', () => {
+ const banner = (v, onWhatsNew) => ui.renderToStaticMarkup(React.createElement(ui.AppUpdateBannerView, { view: v, onUpdate() {}, onDismiss() {}, onWhatsNew }));
+ assert.match(banner({ kind: 'updated', version: '0.7.6' }, () => {}), /Updated to kwant bots 0\.7\.6\..*data-see-whats-new[^>]*>See what’s new</s);
+ assert.doesNotMatch(banner({ kind: 'updated', version: '0.7.6' }), /See what’s new/);
+ assert.equal(ui.hasWhatsNew('0.7.6'), true);
+ assert.equal(ui.hasWhatsNew('0.7.4'), false);
+});
+
+test('Settings › About: What’s new in the latest version, then earlier versions, then GitHub', async () => {
+ const html = ui.renderToStaticMarkup(React.createElement(ui.WhatsNewAboutView, { entries: ui.WHATS_NEW, onPick() {} }));
+ assert.match(html, /What’s new in 0\.7\.6<\/b><span[^>]*>Nov 14 · 3 new things, 6 fixes/);
+ assert.match(html, /Earlier versions/);
+ assert.match(html, /0\.7\.5<\/span><span[^>]*>Nov 7<\/span><span[^>]*>6 new things, 4 fixes/);
+ assert.match(html, /Older releases on GitHub/);
+ assert.equal(ui.renderToStaticMarkup(React.createElement(ui.WhatsNewAboutView, { entries: [], onPick() {} })), '');
+
+ // Picking a row opens that version's sheet through the host.
+ localStorage.setItem(ui.SEEN_KEY, '0.7.6');
+ await host({ established: true });
+ const el = document.createElement('div');
+ document.body.append(el);
+ const root = createRoot(el);
+ mounted.push(root);
+ await act(async () => root.render(React.createElement(ui.WhatsNewAbout)));
+ await settle();
+ await click(el.querySelector('button[aria-label="What’s new in 0.7.5"]'));
+ assert.equal(sheet()?.querySelector('h2')?.textContent, 'What’s new in kwant bots 0.7.5');
+});
diff --git a/frontend/tests/whatsNewEstablished.test.mjs b/frontend/tests/whatsNewEstablished.test.mjs
new file mode 100644
index 00000000..13312ef2
--- /dev/null
+++ b/frontend/tests/whatsNewEstablished.test.mjs
@@ -0,0 +1,68 @@
+// 0.7.6 F-1: Get started wins over What's new. A brand-new person whose AI is already signed in gets
+// the Get started card and never the sheet; a 0.7.5 user who wrote in a chat still gets it; until the
+// space and the open chat have loaded, the answer waits.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ export { showCard, whatsNewEstablished } from './src/gettingStarted';
+ export { decideOnLoad } from './src/whatsNewSheet';
+`);
+
+// What App.tsx does: the card decision feeds the What's new decision.
+const decide = ({ canRun, messages = [], teams = 1, dismissed = false, started = false, loaded = true, messagesLoaded = true }) => {
+ const getStartedShowing = m.showCard({ dismissed, canRun, generalMessages: messages.length, teams, started });
+ const wroteHere = messages.some((x) => x.sender_role === 'user');
+ return { getStartedShowing, established: m.whatsNewEstablished({ loaded, messagesLoaded, canRun, wroteHere, getStartedShowing }) };
+};
+
+test('new person with a signed-in AI: Get started shows, What\'s new is recorded silently', () => {
+ const r = decide({ canRun: true, messages: [], teams: 1 });
+ assert.equal(r.getStartedShowing, true);
+ assert.equal(r.established, false);
+ assert.equal(m.decideOnLoad(null, '0.7.6', r.established), 'record');
+});
+
+test('new person with no AI yet: not established either', () => {
+ const r = decide({ canRun: false });
+ assert.equal(r.getStartedShowing, true);
+ assert.equal(r.established, false);
+});
+
+test('0.7.5 user who wrote in the chat gets the sheet', () => {
+ const r = decide({ canRun: true, messages: [{ sender_role: 'user' }, { sender_role: 'bot' }], teams: 1 });
+ assert.equal(r.getStartedShowing, false);
+ assert.equal(r.established, true);
+ assert.equal(m.decideOnLoad(null, '0.7.6', r.established), 'show');
+});
+
+test('0.7.5 user whose AI works and has more teams gets the sheet even in an empty chat', () => {
+ assert.equal(decide({ canRun: true, teams: 3 }).established, true);
+});
+
+test('signed-in AI but Get started was dismissed: established', () => {
+ assert.equal(decide({ canRun: true, dismissed: true }).established, true);
+});
+
+test('signed-in AI with Get started in progress: not established', () => {
+ assert.equal(decide({ canRun: true, teams: 4, started: true }).established, false);
+});
+
+test('waits until the space has loaded', () => {
+ assert.equal(decide({ canRun: true, loaded: false }).established, null);
+ assert.equal(m.decideOnLoad(null, '0.7.6', null), 'wait');
+});
+
+test('waits until the engines answer', () => {
+ assert.equal(decide({ canRun: null }).established, null);
+});
+
+test('waits until the open chat\'s messages have loaded, so an upgrading user is never recorded as new', () => {
+ assert.equal(decide({ canRun: true, teams: 1, messagesLoaded: false }).established, null);
+ assert.equal(decide({ canRun: false, messagesLoaded: false }).established, null);
+});
+
+test('a message written here counts even before everything else has loaded', () => {
+ assert.equal(m.whatsNewEstablished({ loaded: false, messagesLoaded: false, canRun: null, wroteHere: true, getStartedShowing: false }), true);
+});
diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts
index e7226d48..16198e77 100644
--- a/frontend/vite.config.ts
+++ b/frontend/vite.config.ts
@@ -3,6 +3,7 @@ import react from '@vitejs/plugin-react';
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync } from 'node:fs';
import { join, relative } from 'node:path';
+import { changelogSection } from './src/whatsNewSheet';
const files = (dir: string): string[] =>
readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : [join(dir, e.name)]));
@@ -44,8 +45,34 @@ function pwaServiceWorker(): Plugin {
};
}
+const WHATS_NEW = 'virtual:kwant-whatsnew';
+
+/** "What's new" content: every src/whatsnew/<version>.json and only those versions' CHANGELOG sections,
+ * so the bundle carries what the sheet shows and nothing more. See src/whatsNewSheet.ts. */
+function whatsNewContent(): Plugin {
+ const dir = new URL('./src/whatsnew/', import.meta.url);
+ const changelog = new URL('../CHANGELOG.md', import.meta.url);
+ return {
+ name: 'kwnt-whats-new',
+ resolveId: (id) => (id === WHATS_NEW ? `\0${WHATS_NEW}` : null),
+ load(id) {
+ if (id !== `\0${WHATS_NEW}`) return null;
+ const names = readdirSync(dir).filter((n) => /^\d+\.\d+\.\d+\.json$/.test(n));
+ const entries = names.map((n) => {
+ const file = new URL(n, dir);
+ this.addWatchFile(file.pathname);
+ return JSON.parse(readFileSync(file, 'utf8'));
+ });
+ this.addWatchFile(changelog.pathname);
+ const log = readFileSync(changelog, 'utf8');
+ const sections = Object.fromEntries(names.map((n) => n.slice(0, -5)).map((v) => [v, changelogSection(log, v)]));
+ return `export const entries = ${JSON.stringify(entries)};\nexport const changelog = ${JSON.stringify(sections)};\n`;
+ },
+ };
+}
+
export default defineConfig({
- plugins: [react(), pwaServiceWorker()],
+ plugins: [react(), whatsNewContent(), pwaServiceWorker()],
server: {
port: 5199,
proxy: {
diff --git a/scripts/site_release_gate.py b/scripts/site_release_gate.py
index a173353c..bda46941 100644
--- a/scripts/site_release_gate.py
+++ b/scripts/site_release_gate.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
-"""kwant.si and the GitHub README must show the newest release before that release counts as done.
+"""kwant.si, the GitHub README and the in-app "What's new" must cover the newest release before it counts as done.
-Reads the newest `## [Mac X.Y.Z]` heading in CHANGELOG.md and checks site-src/ and README.md:
+Reads the newest `## [Mac X.Y.Z]` heading in CHANGELOG.md and checks site-src/, README.md and frontend/src/whatsnew/:
1. features.html has a "New in" section for it: `id="new-<id>"`, where <id> is the version without dots or a
trailing .0 (0.7.0 -> new-07, 0.7.1 -> new-071, 0.6.11 -> new-0611), or any section whose `data-covers` lists
@@ -13,12 +13,17 @@ Reads the newest `## [Mac X.Y.Z]` heading in CHANGELOG.md and checks site-src/ a
5. README.md has a `## New in X.Y` section for the release's minor version, and that section names the release
(0.7.2 as "(0.7.2)" on a bullet, say). A small fix release with no bullet of its own can be named in an HTML
comment in the section: `<!-- covers: 0.7.3 -->`.
+6. frontend/src/whatsnew/X.Y.Z.json exists and keeps the limits of the in-app "What's new" sheet: 2-6 highlights
+ (title 60 characters or fewer, text 200 or fewer, image null or a .webp of 80 KB or less in
+ frontend/public/whatsnew/X.Y.Z/, open null or an in-app place such as "settings/teams") and 0-15 fixes of 140
+ characters or fewer. frontend/src/whatsNewSheet.ts checks the same limits in the app.
Usage: python3 scripts/site_release_gate.py [--warn]
Exit 0 when kwant.si and the README are current, else 1 with one line per gap. --warn prints the gaps and exits 0:
check_site.py uses it, because the release PR bumps CHANGELOG.md before the site PR lands. The release script uses
the strict form, so a release isn't done until the site and the README are.
"""
+import json
import re
import sys
from pathlib import Path
@@ -75,6 +80,91 @@ def media_files(name):
return [f"{name}-1440.webp", f"{name}-2880.webp"]
+# The "What's new" limits, as in frontend/src/whatsNewSheet.ts (LIMITS).
+WN_HIGHLIGHTS = (2, 6)
+WN_TITLE, WN_TEXT, WN_FIXES, WN_FIX = 60, 200, 15, 140
+WN_IMAGE_BYTES = 80 * 1024
+WN_TOP = {"inbox", "inbox/loose-ends", "board", "parallel", "dev", "jar", "settings/app"}
+
+
+def whatsnew_places(root):
+ """The in-app places a highlight's "open" may name: the views in frontend/src/nav.ts."""
+ nav = root / "frontend" / "src" / "nav.ts"
+ tabs = re.search(r"SPACE_SETTINGS_TABS = \[([^\]]*)\]", nav.read_text()) if nav.exists() else None
+ return WN_TOP | {f"settings/{t}" for t in re.findall(r"'([a-z-]+)'", tabs[1] if tabs else "")}
+
+
+def whatsnew_gaps(version, root=ROOT):
+ """Every way frontend/src/whatsnew/<version>.json is missing or breaks the sheet's limits."""
+ rel = f"frontend/src/whatsnew/{version}.json"
+ path = root / rel
+ if not path.exists():
+ return [f"{rel} is missing: write the in-app \"What's new in kwant {version}\" from the CHANGELOG entry "
+ f"(2-6 highlights and the fixes; see next-076/whats-new/spec.md)"]
+ try:
+ e = json.loads(path.read_text())
+ except ValueError as err:
+ return [f"{rel} isn't valid JSON ({err})"]
+ if not isinstance(e, dict):
+ return [f"{rel} must be a JSON object"]
+ out = []
+ say = lambda msg: out.append(f"{rel}: {msg}")
+ if e.get("version") != version:
+ say(f"version is {e.get('version')!r}, should be {version!r}")
+ if not isinstance(e.get("date"), str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", e["date"]):
+ say("date must be YYYY-MM-DD")
+ hs = e.get("highlights")
+ places = whatsnew_places(root)
+ if not isinstance(hs, list):
+ say("highlights must be a list")
+ hs = []
+ elif not WN_HIGHLIGHTS[0] <= len(hs) <= WN_HIGHLIGHTS[1]:
+ say(f"{len(hs)} highlights, needs {WN_HIGHLIGHTS[0]}-{WN_HIGHLIGHTS[1]}")
+ ids = set()
+ for i, h in enumerate(hs):
+ at = f"highlights[{i}]"
+ if not isinstance(h, dict):
+ say(f"{at} must be an object")
+ continue
+ hid = h.get("id")
+ if not isinstance(hid, str) or not re.fullmatch(r"[a-z0-9-]+", hid):
+ say(f"{at}.id must be lowercase letters, digits and dashes")
+ elif hid in ids:
+ say(f"{at}.id {hid!r} is used twice")
+ ids.add(hid)
+ for key, limit in (("title", WN_TITLE), ("text", WN_TEXT)):
+ v = h.get(key)
+ if not isinstance(v, str) or not v.strip():
+ say(f"{at}.{key} is empty")
+ elif len(v) > limit:
+ say(f"{at}.{key} is {len(v)} characters, max {limit}")
+ img = h.get("image")
+ if img is not None:
+ if not isinstance(img, str) or not re.fullmatch(r"[a-z0-9][a-z0-9._-]*\.webp", img):
+ say(f"{at}.image must be null or a .webp file name")
+ else:
+ f = root / "frontend" / "public" / "whatsnew" / version / img
+ if not f.exists():
+ say(f"{at}.image: frontend/public/whatsnew/{version}/{img} is missing")
+ elif f.stat().st_size > WN_IMAGE_BYTES:
+ say(f"{at}.image: {img} is {f.stat().st_size / 1024:.1f} KB, max 80 KB")
+ place = h.get("open")
+ if place is not None and (not isinstance(place, str) or place.strip("/").lower() not in places):
+ say(f"{at}.open {place!r} isn't an in-app place (null, or one of: {', '.join(sorted(places))})")
+ fixes = e.get("fixes")
+ if not isinstance(fixes, list):
+ say("fixes must be a list")
+ else:
+ if len(fixes) > WN_FIXES:
+ say(f"{len(fixes)} fixes, max {WN_FIXES}")
+ for i, f in enumerate(fixes):
+ if not isinstance(f, str) or not f.strip():
+ say(f"fixes[{i}] is empty")
+ elif len(f) > WN_FIX:
+ say(f"fixes[{i}] is {len(f)} characters, max {WN_FIX}")
+ return out
+
+
def gaps(root=ROOT):
src, media = root / "site-src", root / "site" / "assets" / "media"
version, entry = newest((root / "CHANGELOG.md").read_text())
@@ -115,6 +205,7 @@ def gaps(root=ROOT):
gap = readme_gap(version, readme.read_text()) if readme.exists() else "README.md is missing"
if gap:
out.append(gap)
+ out += whatsnew_gaps(version, root)
return out
@@ -125,7 +216,7 @@ def main():
for g in found:
print(("WARN " if warn else "GAP ") + g)
if not found:
- print(f"kwant.si and README.md cover {version}")
+ print(f"kwant.si, README.md and What's new cover {version}")
sys.exit(0 if warn or not found else 1)
diff --git a/scripts/test_install_sh.inner.sh b/scripts/test_install_sh.inner.sh
new file mode 100755
index 00000000..472c36b9
--- /dev/null
+++ b/scripts/test_install_sh.inner.sh
@@ -0,0 +1,197 @@
+#!/bin/sh
+# Runs inside a clean container for scripts/test_install_sh.sh, as root. /t (read only) holds
+# install.sh and the mock release folders good/, v2/ and bad/.
+set -eu
+
+export DEBIAN_FRONTEND=noninteractive
+apt-get update -qq >/dev/null
+apt-get install -y -qq --no-install-recommends curl ca-certificates python3 procps >/dev/null
+
+# The mock release server, on the container's own loopback
+(cd /t/release && exec python3 -m http.server 18080 --bind 127.0.0.1) >/tmp/http.log 2>&1 &
+i=0
+until curl -fsS -o /dev/null http://127.0.0.1:18080/good/ 2>/dev/null; do
+ i=$((i + 1))
+ [ "$i" -lt 50 ] || { echo "mock release server didn't start"; cat /tmp/http.log; exit 1; }
+ sleep 0.2
+done
+
+# A sudo that only records being called: install.sh must never call it
+cat >/usr/local/bin/sudo <<'EOF'
+#!/bin/sh
+echo "sudo $*" >>/tmp/sudo-called
+exit 1
+EOF
+chmod 755 /usr/local/bin/sudo
+
+useradd -m -s /bin/sh tester
+home=/home/tester
+
+pass=0
+check() { # check DESCRIPTION COMMAND...
+ d=$1
+ shift
+ if "$@"; then
+ echo " ok $d"
+ pass=$((pass + 1))
+ else
+ echo " FAIL $d"
+ echo "--- output"
+ cat /tmp/out 2>/dev/null || true
+ echo "--- kwnt.log"
+ tail -n 30 "$home/.kwnt/kwnt.log" 2>/dev/null || true
+ exit 1
+ fi
+}
+
+# install RELEASE_DIR [EXTRA_PATH]: `cat install.sh | sh` as tester, the way `curl … | sh` runs it
+install() {
+ extra=${2:-}
+ su tester -c "cd && cat /t/install.sh | env PATH='$extra/usr/local/bin:/usr/bin:/bin' \
+ KWNT_INSTALL_BASE_URL=http://127.0.0.1:18080/$1 KWNT_INSTALL_SETUP_FLAGS=--dry-run \
+ KWNT_LAYA_MANAGED=0 KWNT_PORT=18799 sh" >/tmp/out 2>&1
+}
+
+sha() { sha256sum "$1" | awk '{print $1}'; }
+health() { curl -fsS --max-time 3 http://127.0.0.1:18799/api/health 2>/dev/null | grep -q '"app":"kwnt"'; }
+v1=$(cd /tmp && tar -xzf /t/release/good/kwnt-linux-*.tar.gz kwnt -O | sha256sum | awk '{print $1}')
+v2=$(cd /tmp && tar -xzf /t/release/v2/kwnt-linux-*.tar.gz kwnt -O | sha256sum | awk '{print $1}')
+
+echo "- a bad checksum installs nothing"
+rc=0
+install bad || rc=$?
+check "the install fails" [ "$rc" -ne 0 ]
+check "it says nothing was installed" grep -q "didn't match its checksum, so nothing was installed" /tmp/out
+check "no kwnt in ~/.local/bin" [ ! -e "$home/.local/bin/kwnt" ]
+check "nothing is listening" sh -c '! curl -fsS --max-time 2 http://127.0.0.1:18799/api/health >/dev/null 2>&1'
+
+echo "- a good install (no systemd: runs in the background)"
+install good
+check "kwnt is in ~/.local/bin" [ -x "$home/.local/bin/kwnt" ]
+check "it is the released binary" [ "$(sha "$home/.local/bin/kwnt")" = "$v1" ]
+check "/api/health says app kwnt" health
+check "first line names kwant and the arch" grep -Eq '^✓ kwant [0-9][^ ]* for Linux (x86_64|arm64)$' /tmp/out
+check "says it runs in the background" grep -q '^✓ Runs in the background' /tmp/out
+check "Mira's background line" grep -qx '✓ Laya and a browser for the bots are getting ready in the background' /tmp/out
+link_line='^Open http://127\.0\.0\.1:18799/#kwnt_token=[A-Za-z0-9._-]{16,} in a browser on this machine\.$'
+check "the one-time link, to open on this machine" grep -Eq "$link_line" /tmp/out
+check "on a server: the ssh tunnel first" grep -qx 'On a server? On your laptop, first run:' /tmp/out
+check "the tunnel uses the port and this user" grep -qx ' ssh -N -L 18799:127.0.0.1:18799 tester@<this-server>' /tmp/out
+check "then the same link; HTTPS for a phone" grep -qx 'then open the same link there. For a phone (HTTPS), see https://kwant.si/docs/install' /tmp/out
+check "how long the link lasts" grep -qx 'The link works once, for 15 minutes.' /tmp/out
+check "no 'phone or laptop' for a loopback link" sh -c '! grep -q "Open this on your phone or laptop" /tmp/out'
+check "no QR code for a loopback link" sh -c '! grep -q "█" /tmp/out'
+check "not running outside the installer" sh -c '! grep -q "already running outside this installer" /tmp/out'
+check "Mira's closing lines" grep -qx 'There you choose your AI and sign in. Nothing else to type here.' /tmp/out
+check "how to get another link" grep -Eq '^Lost the link\? Run: .*kwnt signin-link$' /tmp/out
+check "no kwnt serve banner in the output" sh -c '! grep -q "To sign in from another device" /tmp/out'
+pid1=$(cat "$home/.kwnt/kwnt.pid")
+check "the pid file names a running kwnt" grep -q kwnt "/proc/$pid1/cmdline"
+i=0
+while [ ! -s "$home/.kwnt/setup.log" ] && [ "$i" -lt 30 ]; do sleep 1; i=$((i + 1)); done
+check "kwnt setup ran in the background" [ -s "$home/.kwnt/setup.log" ]
+
+echo "- running it again upgrades in place"
+install v2
+check "the binary is the new one" [ "$(sha "$home/.local/bin/kwnt")" = "$v2" ]
+check "/api/health answers" health
+pid2=$(cat "$home/.kwnt/kwnt.pid")
+check "kwnt was restarted" [ "$pid2" != "$pid1" ]
+check "the old process is gone" sh -c "! kill -0 $pid1 2>/dev/null"
+check "a new link was printed" grep -Eq "$link_line" /tmp/out
+check "only one kwnt serve runs" [ "$(pgrep -f 'kwnt serve' | wc -l)" -eq 1 ]
+check "not running outside the installer" sh -c '! grep -q "already running outside this installer" /tmp/out'
+kill "$pid2"
+i=0
+while kill -0 "$pid2" 2>/dev/null && [ "$i" -lt 20 ]; do sleep 0.5; i=$((i + 1)); done
+
+# stop_all: every kwnt this user runs, by the installer or by hand
+stop_all() {
+ pkill -u tester -f 'kwnt(-hand)? serve' 2>/dev/null || true
+ i=0
+ while pgrep -u tester -f 'kwnt(-hand)? serve' >/dev/null && [ "$i" -lt 20 ]; do sleep 0.5; i=$((i + 1)); done
+}
+outside_line='kwnt is already running outside this installer. Restart it to use the new version.'
+
+echo "- a kwnt started by hand (no pid file): found by its process"
+rm -f "$home/.kwnt/kwnt.pid"
+su tester -c "cd && KWNT_DATA_DIR=$home/hand KWNT_PORT=18800 KWNT_LAYA_MANAGED=0 nohup $home/.local/bin/kwnt serve >/tmp/hand.log 2>&1 </dev/null &"
+i=0
+until curl -fsS --max-time 2 http://127.0.0.1:18800/api/health 2>/dev/null | grep -q '"app":"kwnt"'; do
+ i=$((i + 1))
+ [ "$i" -lt 60 ] || { cat /tmp/hand.log; exit 1; }
+ sleep 0.5
+done
+install good
+check "says it runs outside the installer" grep -qx "$outside_line" /tmp/out
+check "doesn't say updated" sh -c '! grep -q "(updated from" /tmp/out'
+check "the hand-started kwnt still runs" curl -fsS --max-time 2 -o /dev/null http://127.0.0.1:18800/api/health
+check "the link is still printed" grep -Eq "$link_line" /tmp/out
+stop_all
+
+echo "- a kwnt started by hand under another name: found by its port"
+rm -f "$home/.kwnt/kwnt.pid"
+su tester -c "cp $home/.local/bin/kwnt $home/kwnt-hand && cd && KWNT_PORT=18799 KWNT_LAYA_MANAGED=0 nohup $home/kwnt-hand serve >/tmp/hand.log 2>&1 </dev/null &"
+i=0
+until health; do
+ i=$((i + 1))
+ [ "$i" -lt 60 ] || { cat /tmp/hand.log; exit 1; }
+ sleep 0.5
+done
+install v2
+check "says it runs outside the installer" grep -qx "$outside_line" /tmp/out
+check "doesn't say updated" sh -c '! grep -q "(updated from" /tmp/out'
+check "the hand-started kwnt still answers" health
+stop_all
+
+echo "- with a systemd user session: a service, and the linger command when it needs admin"
+mkdir -p /tmp/stubs
+# systemctl and loginctl stand-ins: the user manager "runs" ExecStart in the background
+cat >/tmp/stubs/systemctl <<'EOF'
+#!/bin/sh
+echo "systemctl $*" >>"$HOME/systemctl.calls"
+[ "$1" = --user ] || exit 1
+case "$2" in
+ show-environment | daemon-reload | enable) exit 0 ;;
+ restart)
+ unit="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$3"
+ [ -f "$unit" ] || exit 1
+ if [ -f "$HOME/unit.pid" ]; then kill "$(cat "$HOME/unit.pid")" 2>/dev/null; sleep 1; fi
+ exe=$(sed -n 's/^ExecStart=//p' "$unit" | sed "s#%h#$HOME#g")
+ # shellcheck disable=SC2086
+ nohup $exe >>"$HOME/unit.log" 2>&1 </dev/null &
+ echo $! >"$HOME/unit.pid"
+ ;;
+ *) exit 1 ;;
+esac
+EOF
+cat >/tmp/stubs/loginctl <<'EOF'
+#!/bin/sh
+echo "loginctl $*" >>"$HOME/loginctl.calls"
+case "$1" in
+ show-user) echo "Linger=no" ;;
+ enable-linger) echo "Access denied" >&2; exit 1 ;;
+esac
+EOF
+chmod 755 /tmp/stubs/systemctl /tmp/stubs/loginctl
+rm -f "$home/.kwnt/kwnt.pid"
+install good /tmp/stubs:
+unit="$home/.config/systemd/user/kwnt.service"
+check "the unit file is written" [ -f "$unit" ]
+check "it runs ~/.local/bin/kwnt serve" grep -qx 'ExecStart=%h/.local/bin/kwnt serve' "$unit"
+check "it reads ~/.kwnt/kwnt.env if present" grep -qx 'EnvironmentFile=-%h/.kwnt/kwnt.env' "$unit"
+check "it is enabled and restarted" sh -c "grep -q 'enable kwnt.service' $home/systemctl.calls && grep -q 'restart kwnt.service' $home/systemctl.calls"
+check "linger was tried without a password prompt" grep -q 'enable-linger --no-ask-password tester' "$home/loginctl.calls"
+check "says it runs as a service" grep -qx '✓ Runs as a service for this user' /tmp/out
+check "prints the one admin command" grep -q 'runs once: sudo loginctl enable-linger tester$' /tmp/out
+check "/api/health answers" health
+check "the downgrade back to v1 replaced the binary" [ "$(sha "$home/.local/bin/kwnt")" = "$v1" ]
+check "the link is printed" grep -Eq "$link_line" /tmp/out
+kill "$(cat "$home/unit.pid")" 2>/dev/null || true
+
+echo "- never sudo"
+check "sudo was never called" [ ! -e /tmp/sudo-called ]
+# Every line that says sudo is a comment or text it prints, never a command it runs
+check "install.sh runs no sudo" sh -c "! grep -n sudo /t/install.sh | grep -Ev '^[0-9]+: *#|linger_cmd=\"sudo |# Never uses sudo'"
+
+echo "PASS: $pass checks"
diff --git a/scripts/test_install_sh.sh b/scripts/test_install_sh.sh
new file mode 100755
index 00000000..c080054f
--- /dev/null
+++ b/scripts/test_install_sh.sh
@@ -0,0 +1,65 @@
+#!/bin/sh
+# Runs site/install.sh in clean containers against a local mock release server that serves a real
+# kwnt build, and checks: a bad checksum installs nothing, a good install starts kwnt and prints the
+# sign-in link and Mira's lines, a second run upgrades in place, the systemd user-service path, and
+# that sudo is never called. Nothing is downloaded from a real release; no host port is opened.
+#
+# scripts/test_install_sh.sh path/to/kwnt [image ...] (default images: ubuntu:22.04 debian:12)
+#
+# The kwnt binary must match the container's architecture (the host's, without emulation).
+set -eu
+
+[ $# -ge 1 ] || { echo "usage: $0 path/to/kwnt [image ...]" >&2; exit 2; }
+bin=$1
+shift
+[ -x "$bin" ] || { echo "not an executable: $bin" >&2; exit 2; }
+[ $# -gt 0 ] || set -- ubuntu:22.04 debian:12
+
+root=$(cd "$(dirname "$0")/.." && pwd)
+work=$(mktemp -d)
+names=""
+cleanup() {
+ for n in $names; do docker rm -f "$n" >/dev/null 2>&1 || true; done
+ rm -rf "$work"
+}
+trap cleanup EXIT
+
+# The mock release: good/ (v1), v2/ (the same program with bytes appended, so its checksum differs
+# and it still runs) and bad/ (v1 with a wrong .sha256)
+case "$(uname -m)" in
+ x86_64 | amd64) arch=x86_64 ;;
+ aarch64 | arm64) arch=aarch64 ;;
+ *) echo "no prebuilt kwnt for $(uname -m)" >&2; exit 2 ;;
+esac
+tarball="kwnt-linux-$arch.tar.gz"
+pack() { # pack DIR BINARY
+ mkdir -p "$work/release/$1" "$work/stage-$1"
+ cp "$2" "$work/stage-$1/kwnt"
+ chmod 755 "$work/stage-$1/kwnt"
+ tar -czf "$work/release/$1/$tarball" -C "$work/stage-$1" kwnt
+ (cd "$work/release/$1" && sha256sum "$tarball" >"$tarball.sha256")
+}
+pack good "$bin"
+cp "$bin" "$work/kwnt-v2"
+printf 'kwant install test v2' >>"$work/kwnt-v2"
+pack v2 "$work/kwnt-v2"
+pack bad "$bin"
+printf '%064d %s\n' 0 "$tarball" >"$work/release/bad/$tarball.sha256"
+cp "$root/site/install.sh" "$work/install.sh"
+cp "$root/scripts/test_install_sh.inner.sh" "$work/inner.sh"
+# mktemp -d is private (700); the installs run as an ordinary user in the container
+chmod -R a+rX "$work"
+
+fails=0
+for image in "$@"; do
+ name="kwnt-install-test-$$-$(printf '%s' "$image" | tr -c 'a-z0-9' '-')"
+ names="$names $name"
+ echo "=== $image"
+ if docker run --rm --name "$name" --network bridge -v "$work:/t:ro" "$image" sh /t/inner.sh; then
+ echo "=== $image: PASS"
+ else
+ echo "=== $image: FAIL"
+ fails=$((fails + 1))
+ fi
+done
+[ "$fails" -eq 0 ]
diff --git a/scripts/test_site_release_gate.py b/scripts/test_site_release_gate.py
index 69b0ca7d..a0e5d6cb 100644
--- a/scripts/test_site_release_gate.py
+++ b/scripts/test_site_release_gate.py
@@ -1,4 +1,6 @@
-"""The release gate's README check: README.md's "New in X.Y" section must name the newest release."""
+"""The release gate's README and What's new checks: README.md's "New in X.Y" section must name the newest release,
+and frontend/src/whatsnew/<version>.json must exist and keep the sheet's limits."""
+import json
import tempfile
import unittest
from pathlib import Path
@@ -9,6 +11,23 @@ CHANGELOG = "# Changelog\n\n## Unreleased\n\n## [Mac 0.7.2] - 2026-11-06\n\n###
"## [Mac 0.7.1] - 2026-11-06\n"
+NAV = "export const SPACE_SETTINGS_TABS = ['general', 'accounts', 'bots', 'teams', 'connections'] as const;\n"
+
+
+def whatsnew(**over):
+ entry = {
+ "version": "0.7.2",
+ "date": "2026-11-06",
+ "highlights": [
+ {"id": "teams", "title": "Ready-made teams", "text": "One step.", "image": None, "open": "settings/teams"},
+ {"id": "jira", "title": "Jira", "text": "Tickets.", "image": None, "open": None},
+ ],
+ "fixes": ["A fix."],
+ }
+ entry.update(over)
+ return entry
+
+
def readme(section):
return "# kwant\n\nIntro.\n\n---\n\n" + section + "\n---\n\n## Why kwant\n\n- 0.7.2 is mentioned here too.\n"
@@ -39,8 +58,12 @@ class ReadmeGap(unittest.TestCase):
class Gaps(unittest.TestCase):
- def tree(self, readme_text):
+ def tree(self, readme_text, wn=None):
root = Path(self.tmp.name)
+ (root / "frontend" / "src" / "whatsnew").mkdir(parents=True)
+ (root / "frontend" / "src" / "nav.ts").write_text(NAV)
+ if wn is not False:
+ (root / "frontend" / "src" / "whatsnew" / "0.7.2.json").write_text(json.dumps(wn or whatsnew()))
(root / "site-src").mkdir()
(root / "site" / "assets" / "media").mkdir(parents=True)
(root / "CHANGELOG.md").write_text(CHANGELOG)
@@ -68,5 +91,78 @@ class Gaps(unittest.TestCase):
self.assertEqual(gate.gaps(self.tree(None)), ["README.md is missing"])
+class WhatsNew(unittest.TestCase):
+ """Check 6: a release fails without frontend/src/whatsnew/<version>.json, or with one that breaks the limits."""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.root = Path(self.tmp.name)
+ Gaps.tree(self, readme("## New in 0.7\n\n- **A** (0.7.2).\n"), wn=False)
+
+ def tearDown(self):
+ self.tmp.cleanup()
+
+ def write(self, entry):
+ (self.root / "frontend" / "src" / "whatsnew" / "0.7.2.json").write_text(json.dumps(entry))
+
+ def test_missing_file_fails_the_release(self):
+ found = gate.gaps(self.root)
+ self.assertEqual(len(found), 1)
+ self.assertTrue(found[0].startswith("frontend/src/whatsnew/0.7.2.json is missing"))
+
+ def test_good_file_passes(self):
+ self.write(whatsnew())
+ self.assertEqual(gate.gaps(self.root), [])
+
+ def test_wrong_version_and_bad_json(self):
+ self.write(whatsnew(version="0.7.1"))
+ self.assertIn("version is '0.7.1'", gate.whatsnew_gaps("0.7.2", self.root)[0])
+ (self.root / "frontend" / "src" / "whatsnew" / "0.7.2.json").write_text("{nope")
+ self.assertIn("isn't valid JSON", gate.whatsnew_gaps("0.7.2", self.root)[0])
+
+ def test_limits(self):
+ h = whatsnew()["highlights"][0]
+ cases = [
+ (whatsnew(highlights=[h]), "1 highlights, needs 2-6"),
+ (whatsnew(highlights=[dict(h, id=f"h{i}") for i in range(7)]), "7 highlights, needs 2-6"),
+ (whatsnew(highlights=[dict(h, title="x" * 61), dict(h, id="b")]), "title is 61 characters, max 60"),
+ (whatsnew(highlights=[dict(h, text="x" * 201), dict(h, id="b")]), "text is 201 characters, max 200"),
+ (whatsnew(highlights=[h, h]), "is used twice"),
+ (whatsnew(fixes=["x"] * 16), "16 fixes, max 15"),
+ (whatsnew(fixes=["x" * 141]), "fixes[0] is 141 characters, max 140"),
+ (whatsnew(highlights=[dict(h, open="settings/nope"), dict(h, id="b")]), "isn't an in-app place"),
+ (whatsnew(highlights=[dict(h, image="pic.png"), dict(h, id="b")]), "image must be null or a .webp"),
+ (whatsnew(highlights=[dict(h, image="pic.webp"), dict(h, id="b")]), "whatsnew/0.7.2/pic.webp is missing"),
+ ]
+ for entry, want in cases:
+ with self.subTest(want=want):
+ self.write(entry)
+ found = gate.whatsnew_gaps("0.7.2", self.root)
+ self.assertEqual(len(found), 1, found)
+ self.assertIn(want, found[0])
+
+ def test_limits_count_characters_not_bytes(self):
+ h = whatsnew()["highlights"][0]
+ self.write(whatsnew(highlights=[dict(h, title="é" * 60), dict(h, id="b")]))
+ self.assertEqual(gate.whatsnew_gaps("0.7.2", self.root), [])
+
+ def test_image_over_80_kb_fails(self):
+ pics = self.root / "frontend" / "public" / "whatsnew" / "0.7.2"
+ pics.mkdir(parents=True)
+ (pics / "small.webp").write_bytes(b"x" * 80 * 1024)
+ (pics / "big.webp").write_bytes(b"x" * (80 * 1024 + 1))
+ h = whatsnew()["highlights"][0]
+ self.write(whatsnew(highlights=[dict(h, image="small.webp"), dict(h, id="b", image="big.webp")]))
+ found = gate.whatsnew_gaps("0.7.2", self.root)
+ self.assertEqual(len(found), 1, found)
+ self.assertIn("big.webp is 80.0 KB, max 80 KB", found[0])
+
+ def test_every_open_in_the_repo_file_is_an_app_place(self):
+ # The real files: the gate reads the real nav.ts, so a renamed tab fails here first.
+ for f in sorted((gate.ROOT / "frontend" / "src" / "whatsnew").glob("*.json")):
+ with self.subTest(file=f.name):
+ self.assertEqual(gate.whatsnew_gaps(f.stem, gate.ROOT), [])
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/site-src/docs-install.html b/site-src/docs-install.html
index 1ddb7142..07d83b45 100644
--- a/site-src/docs-install.html
+++ b/site-src/docs-install.html
@@ -17,7 +17,24 @@ card_art: avatar:devops
<h2 id="mac">The Mac app</h2>
<p><a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_universal.dmg" rel="noopener">Download the Mac app</a> (a universal <code>.dmg</code> for Apple silicon and Intel), open it and drag kwant to Applications. It runs its own kwant bots on your Mac, with the same data folder as <code>kwnt serve</code> (<code>~/.kwnt</code>), and keeps running in the menu bar when you close the window.</p>
-<p class="note warn">The app is signed ad hoc, not notarized by Apple, so macOS stops it the first time with “Apple could not verify…”. Click Done, open <b>System Settings › Privacy &amp; Security</b>, scroll down and click <b>Open Anyway</b> next to kwant. On macOS 14 or earlier, right-click the app and choose <b>Open</b> instead. After that it opens normally.</p>
+<p>The app is signed ad hoc, not notarized by Apple yet, so macOS asks once, the first time you open it:</p>
+<div class="mac-first-doc">
+ <ol class="mf-steps">
+ <li><span>Drag kwant to Applications and open it. When macOS says it couldn't verify it, click <b>Done</b>.</span></li>
+ <li><span>Open <b>System Settings › Privacy &amp; Security</b> and scroll down to <b>Security</b>.</span></li>
+ <li><span>Click <b>Open Anyway</b> next to “kwant” was blocked, then <b>Open Anyway</b> again, and enter your Mac password or use Touch ID.</span></li>
+ </ol>
+ <figure class="mf-fig">
+ <a class="zoom" href="{{root}}assets/media/open-anyway-wide.svg" data-caption="A mock-up of macOS 15: the “kwant” Not Opened alert (click Done), System Settings › Privacy &amp; Security, and Open Anyway under Security.">
+ <picture>
+ <source media="(max-width: 640px)" srcset="{{root}}assets/media/open-anyway-phone.svg">
+ <img src="{{root}}assets/media/open-anyway-wide.svg" width="560" height="360" loading="lazy" decoding="async"
+ alt="A mock-up of the three macOS steps: the “kwant” Not Opened alert with Done marked, System Settings › Privacy &amp; Security, and the Security row “kwant” was blocked to protect your Mac with Open Anyway marked.">
+ </picture>
+ </a>
+ </figure>
+ <p class="mf-after">You only do this once. On macOS 14 or earlier, right-click kwant in Applications and choose <b>Open</b> instead.</p>
+</div>
<p>When a bot needs you, with a question or an approval, the menu-bar icon plays a short animation once and a small note drops under it; click it to open that chat. The Linux app changes its tray icon and shows a notification. Untick <b>Show nudges</b> in the icon's menu to turn them off.</p>
diff --git a/site-src/index.html b/site-src/index.html
index e235d2de..1a48241d 100644
--- a/site-src/index.html
+++ b/site-src/index.html
@@ -16,7 +16,32 @@ card_art: scene
<a class="btn btn-soft" href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_amd64.deb" rel="noopener">Download for Linux <span class="beta">beta</span></a>
<p class="cta-alt"><a href="docs/quickstart.html">A VPS or Docker? Get started <span aria-hidden="true">→</span></a></p>
</div>
- <p class="mac-dl">Free, for Apple silicon and Intel. <a href="docs/install.html#mac">First open</a> needs one extra step. Linux: a <code>.deb</code> for Ubuntu and Debian on x86_64, or the <a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_x86_64.AppImage" rel="noopener">AppImage</a> (<a href="docs/install.html#linux">how to install</a>).</p>
+ <details class="mac-first" id="mac-first">
+ <summary>
+ <span class="mf-ico" aria-hidden="true"><svg viewBox="0 0 20 20" fill="currentColor"><path d="M4 4h12v1H4zM3 5h1v8H3zM16 5h1v8h-1zM4 12h12v1H4zM1 14h18v2H1z"/><path d="M5 6h10v6H5z" opacity=".22"/><path d="M8 8h1v2H8zM11 8h1v2h-1z"/></svg></span>
+ <span class="mf-sum"><b>First time on a Mac?</b><span>macOS asks once, because kwant isn't notarized by Apple yet.</span></span>
+ <svg class="mf-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
+ </summary>
+ <div class="mf-body">
+ <ol class="mf-steps">
+ <li><span>Drag kwant to Applications and open it. When macOS says it couldn't verify it, click <b>Done</b>.</span></li>
+ <li><span>Open <b>System Settings › Privacy &amp; Security</b> and scroll down to <b>Security</b>.</span></li>
+ <li><span>Click <b>Open Anyway</b> next to “kwant” was blocked, then <b>Open Anyway</b> again, and enter your Mac password or use Touch ID.</span></li>
+ </ol>
+ <figure class="mf-fig">
+ <a class="zoom" href="{{root}}assets/media/open-anyway-wide.svg" data-caption="A mock-up of macOS 15: the “kwant” Not Opened alert (click Done), System Settings › Privacy &amp; Security, and Open Anyway under Security.">
+ <picture>
+ <source media="(max-width: 640px)" srcset="{{root}}assets/media/open-anyway-phone.svg">
+ <img src="{{root}}assets/media/open-anyway-wide.svg" width="560" height="360" loading="lazy" decoding="async"
+ alt="A mock-up of the three macOS steps: the “kwant” Not Opened alert with Done marked, System Settings › Privacy &amp; Security, and the Security row “kwant” was blocked to protect your Mac with Open Anyway marked.">
+ </picture>
+ </a>
+ </figure>
+ <p class="mf-after">You only do this once. On macOS 14 or earlier, right-click kwant in Applications and choose <b>Open</b> instead.</p>
+ <p class="mf-term" data-term="soon"><span class="soon">Soon</span>A one-line Terminal install that skips this step.</p>
+ </div>
+ </details>
+ <p class="mac-dl">Free, for Apple silicon and Intel. Linux: a <code>.deb</code> for Ubuntu and Debian on x86_64, or the <a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_x86_64.AppImage" rel="noopener">AppImage</a> (<a href="docs/install.html#linux">how to install</a>).</p>
{{install:hero}}
{{releases}}
</div>
diff --git a/site/404.html b/site/404.html
index 042ce8fa..a630b28e 100644
--- a/site/404.html
+++ b/site/404.html
@@ -30,7 +30,7 @@
<link rel="apple-touch-icon" href="/apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="/assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="/assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="/assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-404">
<a class="skip" href="#main">Skip to content</a>
@@ -106,7 +106,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="/assets/js/site.js?v=63f328cd53" defer></script>
+<script src="/assets/js/site.js?v=9846e390c8" defer></script>
<script src="/assets/js/pixel.js?v=ce88473d7b" defer></script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
</body>
diff --git a/site/_headers b/site/_headers
index a29fd307..3b1c4b5c 100644
--- a/site/_headers
+++ b/site/_headers
@@ -24,3 +24,8 @@
/assets/js/*
Cache-Control: public, max-age=3600, must-revalidate
+
+# The one-line install (curl -fsSL https://kwant.si/install.sh | sh): plain text, so a browser shows it, and a fix reaches people within minutes
+/install.sh
+ Content-Type: text/plain; charset=utf-8
+ Cache-Control: public, max-age=300, must-revalidate
diff --git a/site/alternatives/grok-bot.html b/site/alternatives/grok-bot.html
index e14ea346..ba07086e 100644
--- a/site/alternatives/grok-bot.html
+++ b/site/alternatives/grok-bot.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-alternatives">
<a class="skip" href="#main">Skip to content</a>
@@ -186,7 +186,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://kwant.si/alternatives/grok-bot","name":"Grok Bot Alternative: Open-Source & Self-Hosted","description":"kwant is an open-source, self-hosted alternative to Grok Bot. Run a team of AI bots on your own machine and import your Grok Bot in minutes.","url":"https://kwant.si/alternatives/grok-bot","image":"https://kwant.si/assets/og/alternatives-grok-bot.png?v=d6512a1080","inLanguage":"en","dateModified":"2026-10-29","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Grok Bot Alternative","item":"https://kwant.si/alternatives/grok-bot"}]},{"@type":"FAQPage","@id":"https://kwant.si/alternatives/grok-bot#faq","url":"https://kwant.si/alternatives/grok-bot","mainEntity":[{"@type":"Question","name":"What is the best open-source alternative to Grok Bot?","acceptedAnswer":{"@type":"Answer","text":"It depends on what you need, but kwant is an open-source (AGPL-3.0), self-hosted option: a team of AI bots in one binary that runs on your laptop, a VPS or Docker, with bots that hand work to each other with @mentions."}},{"@type":"Question","name":"Can I self-host a Grok Bot?","acceptedAnswer":{"@type":"Answer","text":"Check xAI's site for what Grok Bot offers. If you want your bots on your own machine, kwant runs on a laptop, a VPS or Docker, and it can import a Grok Bot export to recreate your bot there."}},{"@type":"Question","name":"Can I import my Grok Bot into kwant?","acceptedAnswer":{"@type":"Answer","text":"Yes. kwant's import reads a Grok Bot export file and recreates the bot with its name, role, instructions, memories, skills, scheduled routines and plugin list. Plugins come across as setup notes, not working connections. If the export only holds the bot's details, kwant warns you that the instructions may be missing. You can also use a prompt kwant gives you: send it to your existing Grok bot and paste the reply back."}},{"@type":"Question","name":"Do I need a Grok account to use kwant?","acceptedAnswer":{"@type":"Answer","text":"No. kwant bots can run on a Claude, Codex or Grok CLI login, an API key, local Ollama or any OpenAI-compatible server. A Grok login is one option among several."}},{"@type":"Question","name":"Is kwant free?","acceptedAnswer":{"@type":"Answer","text":"The software is free under the AGPL-3.0, and commercial licenses are available. You pay for whatever model accounts or API keys you connect. kwant sends no telemetry to its developers."}},{"@type":"Question","name":"What is kwnt?","acceptedAnswer":{"@type":"Answer","text":"It is the program you install and run for kwant. Start it with kwnt serve."}}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/assets/css/site.css b/site/assets/css/site.css
index 699e6be1..fe0e922e 100644
--- a/site/assets/css/site.css
+++ b/site/assets/css/site.css
@@ -631,3 +631,59 @@ td code { white-space: nowrap; }
@media (prefers-reduced-motion: reduce) {
.kw-sticker { --mx: 30% !important; --my: 20% !important; transition: none; }
}
+
+/* O7a: "First time on a Mac" block, under the hero's Download for Mac. Goes into site.css as is. */
+.mac-first { margin-top: 16px; max-width: 600px; background: #fff; border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); }
+.mac-first > summary { display: flex; align-items: center; gap: 12px; min-height: 60px; padding: 10px 14px; border-radius: 13px; list-style: none; cursor: pointer; }
+.mac-first > summary::-webkit-details-marker { display: none; }
+.mac-first > summary:hover { background: #faf9ff; }
+.mac-first > summary:focus-visible { outline: 3px solid var(--v5); outline-offset: 2px; border-radius: 13px; }
+.mf-ico { flex: none; display: grid; place-items: center; width: 34px; height: 34px; border-radius: 9px; background: var(--bg-2); color: var(--v4); }
+.mf-ico svg { width: 20px; height: 20px; shape-rendering: crispEdges; }
+.mf-sum { flex: 1; min-width: 0; display: grid; gap: 1px; }
+.mf-sum b { font: 600 15px/20px var(--sans); color: var(--ink); }
+.mf-sum span { font: 400 13.5px/19px var(--sans); color: var(--dim); }
+.mf-chev { flex: none; width: 20px; height: 20px; color: var(--v4); }
+.mac-first[open] .mf-chev { transform: rotate(180deg); }
+
+.mf-body { padding: 14px 18px 18px; border-top: 1px solid var(--line); }
+.mf-steps { margin: 0; padding: 0; list-style: none; counter-reset: mf; display: grid; gap: 10px; }
+.mf-steps li { counter-increment: mf; display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 10px; font: 400 15px/22px var(--sans); color: var(--ink); }
+.mf-steps li::before { content: counter(mf); display: grid; place-items: center; width: 24px; height: 24px; margin-top: -1px; border-radius: 4px; background: var(--v4); color: #fff; font: 700 13px/1 var(--sans); }
+.mf-steps b { font-weight: 600; }
+.mf-fig { margin: 14px 0 0; border: 1px solid var(--line); border-radius: 10px; overflow: hidden; background: #efebfd; }
+.mf-fig a { display: block; }
+.mf-fig a:focus-visible { outline-offset: -3px; border-radius: 10px; }
+.mf-fig img { display: block; width: 100%; height: auto; }
+.mf-after { margin: 12px 0 0; font-size: 14px; line-height: 21px; color: var(--muted); }
+.mf-term { margin: 14px 0 0; padding-top: 12px; border-top: 1px dashed var(--line-2); font-size: 13.5px; line-height: 20px; color: var(--dim); }
+.mf-term .soon { margin-right: 6px; padding: 1px 6px; border: 1px solid var(--line-2); border-radius: 6px; font: 600 11px var(--sans); letter-spacing: .04em; text-transform: uppercase; color: var(--dim); vertical-align: 1px; }
+.mf-term .cmd { margin-top: 8px; min-height: 42px; }
+.mf-term .cmd code { font-size: 13px; padding: 11px 0; }
+
+/* Desktop: while open, the CRT stops re-centring on the taller column. */
+@media (min-width: 1001px) {
+ .hero-grid:has(.mac-first[open]) { align-items: start; }
+ .hero-grid:has(.mac-first[open]) .hero-crt { margin-top: 72px; }
+}
+.hero .mac-first + .mac-dl { margin-top: 12px; }
+
+@media (prefers-reduced-motion: no-preference) {
+ .mf-chev { transition: transform 160ms ease-out; }
+ .mac-first[open] .mf-body { animation: mf-in 160ms ease-out; }
+ @keyframes mf-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }
+}
+@media (max-width: 640px) {
+ .mac-first > summary { padding: 10px 12px; }
+ .mf-body { padding: 12px 14px 16px; }
+ .mf-steps li { font-size: 15px; }
+}
+/* The same steps and picture in docs/install#mac. */
+.mac-first-doc { max-width: 600px; margin: 0 0 24px; }
+.prose .mac-first-doc .mf-steps { margin: 14px 0 0; padding: 0; }
+.prose .mac-first-doc .mf-steps li { margin: 0; }
+.prose .mac-first-doc .mf-fig { margin: 14px 0 0; }
+.prose .mac-first-doc .mf-after { margin: 12px 0 0; color: var(--muted); }
+.prose .mac-first-doc .mf-steps li { font-size: 17px; line-height: 26px; }
+.prose .mac-first-doc .mf-steps li::before { margin-top: 1px; }
+.prose .mac-first-doc .mf-after { font-size: 15px; line-height: 24px; }
diff --git a/site/assets/js/site.js b/site/assets/js/site.js
index 4f99b963..75ca6510 100644
--- a/site/assets/js/site.js
+++ b/site/assets/js/site.js
@@ -182,3 +182,12 @@
});
});
})();
+
+// O7a: opening the dmg download also opens the Mac first-open steps, so they're there when macOS asks.
+(function () {
+ var d = document.getElementById("mac-first");
+ if (!d) return;
+ document.querySelectorAll('a[href$="kwant_universal.dmg"]').forEach(function (a) {
+ a.addEventListener("click", function () { d.open = true; });
+ });
+})();
diff --git a/site/assets/media/open-anyway-phone.svg b/site/assets/media/open-anyway-phone.svg
new file mode 100644
index 00000000..a386d9ed
--- /dev/null
+++ b/site/assets/media/open-anyway-phone.svg
@@ -0,0 +1,42 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 340 452" width="340" height="452" role="img" aria-labelledby="t">
+ <title id="t">Mock-up of the three macOS screens. Step 1: the alert “kwant” Not Opened, with Done marked. Step 2: System Settings, Privacy and Security. Step 3: under Security, “kwant” was blocked to protect your Mac, with the Open Anyway button marked.</title>
+ <defs>
+ <filter id="sh" x="-20%" y="-20%" width="140%" height="150%"><feDropShadow dx="0" dy="4" stdDeviation="6" flood-color="#1b1033" flood-opacity=".18"/></filter>
+ <g id="badge"><rect x="-12" y="-12" width="24" height="24" rx="4" fill="#4024a8" stroke="#fff" stroke-width="2"/></g>
+ </defs>
+ <rect width="340" height="452" fill="#efebfd"/>
+
+ <!-- 1: the alert -->
+ <g filter="url(#sh)"><rect x="40" y="18" width="260" height="168" rx="14" fill="#fbfaff"/></g>
+ <rect x="40.5" y="18.5" width="259" height="167" rx="13.5" fill="none" stroke="#d8d4e6"/>
+ <rect x="152" y="30" width="36" height="36" rx="8" fill="#4024a8"/>
+ <rect x="160" y="41" width="6" height="7" fill="#fff"/><rect x="174" y="41" width="6" height="7" fill="#fff"/>
+ <rect x="163" y="54" width="14" height="3" fill="#b8a9fb"/>
+ <text x="170" y="90" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px" font-weight="700">“kwant” Not Opened</text>
+ <text x="170" y="110" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="13px">Apple could not verify “kwant”…</text>
+ <rect x="54" y="134" width="110" height="34" rx="8" fill="#fff" stroke="#cfcbdc"/>
+ <text x="109" y="156" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="13.5px">Move to Trash</text>
+ <rect x="176" y="134" width="110" height="34" rx="8" fill="#3d3a4d"/>
+ <text x="231" y="156" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="14px" font-weight="600">Done</text>
+ <rect x="170.5" y="128.5" width="121" height="45" rx="11" fill="none" stroke="#5c3fd0" stroke-width="3"/>
+ <use href="#badge" x="40" y="18"/><text x="40" y="23" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="13.5px" font-weight="800" text-anchor="middle">1</text>
+
+ <!-- 2: where to go -->
+ <rect x="20" y="206" width="300" height="44" rx="10" fill="#fff" stroke="#d8d4e6"/>
+ <text x="40" y="233" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px">System Settings</text>
+ <text x="153" y="233" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="13px">›</text>
+ <text x="167" y="233" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px" font-weight="700">Privacy &amp; Security</text>
+ <use href="#badge" x="20" y="206"/><text x="20" y="211" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="13.5px" font-weight="800" text-anchor="middle">2</text>
+
+ <!-- 3: the Security row -->
+ <rect x="20" y="270" width="300" height="164" rx="12" fill="#fff" stroke="#d8d4e6"/>
+ <text x="40" y="298" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="12.5px" font-weight="700">Security</text>
+ <rect x="34" y="308" width="272" height="112" rx="9" fill="#f7f6fa" stroke="#e6e3ef"/>
+ <path d="M56 322 l9 3.5 v7 c0 5.5 -4 9 -9 11 c-5 -2 -9 -5.5 -9 -11 v-7 z" fill="#8f8aa6"/>
+ <text x="76" y="336" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px">“kwant” was blocked to</text>
+ <text x="76" y="354" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px">protect your Mac.</text>
+ <rect x="168" y="370" width="124" height="34" rx="8" fill="#fff" stroke="#cfcbdc"/>
+ <text x="230" y="392" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px" font-weight="600">Open Anyway</text>
+ <rect x="162.5" y="364.5" width="135" height="45" rx="11" fill="none" stroke="#5c3fd0" stroke-width="3"/>
+ <use href="#badge" x="20" y="270"/><text x="20" y="275" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="13.5px" font-weight="800" text-anchor="middle">3</text>
+</svg>
diff --git a/site/assets/media/open-anyway-wide.svg b/site/assets/media/open-anyway-wide.svg
new file mode 100644
index 00000000..fde8a742
--- /dev/null
+++ b/site/assets/media/open-anyway-wide.svg
@@ -0,0 +1,69 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 560 360" width="560" height="360" role="img" aria-labelledby="t">
+ <title id="t">Mock-up of macOS System Settings, Privacy and Security. Under Security it says “kwant” was blocked to protect your Mac, with an Open Anyway button (step 3). Privacy and Security is selected in the sidebar (step 2). In front, the first alert, “kwant” Not Opened, with Done marked (step 1).</title>
+ <defs>
+ <filter id="sh" x="-20%" y="-20%" width="140%" height="150%"><feDropShadow dx="0" dy="6" stdDeviation="8" flood-color="#1b1033" flood-opacity=".22"/></filter>
+ <filter id="sh2" x="-10%" y="-10%" width="120%" height="130%"><feDropShadow dx="0" dy="2" stdDeviation="3" flood-color="#1b1033" flood-opacity=".10"/></filter>
+ <clipPath id="win"><rect x="12" y="12" width="536" height="300" rx="12"/></clipPath>
+ <g id="badge"><rect x="-11" y="-11" width="22" height="22" rx="4" fill="#4024a8" stroke="#fff" stroke-width="2"/></g>
+ </defs>
+
+ <rect width="560" height="360" fill="#efebfd"/>
+
+ <!-- Settings window -->
+ <g filter="url(#sh2)"><rect x="12" y="12" width="536" height="300" rx="12" fill="#fff"/></g>
+ <g clip-path="url(#win)">
+ <rect x="12" y="12" width="160" height="300" fill="#f4f3f8"/>
+ <line x1="172" y1="12" x2="172" y2="312" stroke="#e4e1ee"/>
+ <line x1="172" y1="58" x2="548" y2="58" stroke="#e4e1ee"/>
+ </g>
+ <rect x="12.5" y="12.5" width="535" height="299" rx="11.5" fill="none" stroke="#d8d4e6"/>
+ <circle cx="32" cy="32" r="5.5" fill="#ee6a5f"/><circle cx="48" cy="32" r="5.5" fill="#f4bf4f"/><circle cx="64" cy="32" r="5.5" fill="#61c454"/>
+
+ <!-- Sidebar -->
+ <g class="side">
+ <rect x="26" y="62" width="16" height="16" rx="4" fill="#b9b5c8"/><text x="50" y="75" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">General</text>
+ <rect x="26" y="92" width="16" height="16" rx="4" fill="#b9b5c8"/><text x="50" y="105" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">Appearance</text>
+ <rect x="22" y="116" width="144" height="28" rx="7" fill="#dedbea"/>
+ <rect x="26" y="122" width="16" height="16" rx="4" fill="#7c7891"/><text x="50" y="135" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px" font-weight="700">Privacy &amp; Security</text>
+ <rect x="26" y="152" width="16" height="16" rx="4" fill="#b9b5c8"/><text x="50" y="165" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">Desktop &amp; Dock</text>
+ <rect x="26" y="182" width="16" height="16" rx="4" fill="#b9b5c8"/><text x="50" y="195" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">Displays</text>
+ </g>
+
+ <!-- Pane header -->
+ <text x="188" y="40" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="15px">‹ ›</text>
+ <text x="222" y="40" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="14px" font-weight="700">Privacy &amp; Security</text>
+
+ <!-- Security group -->
+ <text x="190" y="86" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="12px" font-weight="700">Security</text>
+ <rect x="186" y="96" width="346" height="104" rx="8" fill="#f7f6fa" stroke="#e6e3ef"/>
+ <text x="200" y="121" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">Allow applications from</text>
+ <text x="518" y="121" text-anchor="end" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="11.5px">App Store &amp; Known Developers ⌄</text>
+ <line x1="200" y1="134" x2="518" y2="134" stroke="#e6e3ef"/>
+ <!-- shield -->
+ <path d="M208 148 l8 3 v6 c0 5 -3.5 8 -8 10 c-4.5 -2 -8 -5 -8 -10 v-6 z" fill="#8f8aa6"/>
+ <text x="226" y="161" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">“kwant” was blocked to</text>
+ <text x="226" y="177" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px">protect your Mac.</text>
+ <rect x="418" y="153" width="100" height="28" rx="7" fill="#fff" stroke="#cfcbdc"/>
+ <text x="468" y="171.5" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px" font-weight="600">Open Anyway</text>
+ <rect x="412.5" y="147.5" width="111" height="39" rx="10" fill="none" stroke="#5c3fd0" stroke-width="3"/>
+ <use href="#badge" x="524" y="148"/><text x="524" y="152.5" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="12.5px" font-weight="800" text-anchor="middle">3</text>
+
+ <!-- step 2 badge on the sidebar item -->
+ <use href="#badge" x="14" y="130"/><text x="14" y="134.5" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="12.5px" font-weight="800" text-anchor="middle">2</text>
+
+ <!-- First alert, in front -->
+ <g filter="url(#sh)"><rect x="34" y="206" width="226" height="146" rx="12" fill="#fbfaff"/></g>
+ <rect x="34.5" y="206.5" width="225" height="145" rx="11.5" fill="none" stroke="#d8d4e6"/>
+ <!-- our own pixel app icon -->
+ <rect x="132" y="216" width="30" height="30" rx="7" fill="#4024a8"/>
+ <rect x="139" y="225" width="5" height="6" fill="#fff"/><rect x="150" y="225" width="5" height="6" fill="#fff"/>
+ <rect x="141" y="236" width="12" height="3" fill="#b8a9fb"/>
+ <text x="147" y="266" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12.5px" font-weight="700">“kwant” Not Opened</text>
+ <text x="147" y="284" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#5d5873" font-size="11.5px">Apple could not verify “kwant”…</text>
+ <rect x="46" y="306" width="96" height="28" rx="7" fill="#fff" stroke="#cfcbdc"/>
+ <text x="94" y="324.5" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#1b1033" font-size="12px">Move to Trash</text>
+ <rect x="152" y="306" width="96" height="28" rx="7" fill="#3d3a4d"/>
+ <text x="200" y="324.5" text-anchor="middle" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="12.5px" font-weight="600">Done</text>
+ <rect x="146.5" y="300.5" width="107" height="39" rx="10" fill="none" stroke="#5c3fd0" stroke-width="3"/>
+ <use href="#badge" x="254" y="301"/><text x="254" y="305.5" font-family="-apple-system, 'SF Pro Text', 'Inter', system-ui, sans-serif" fill="#fff" font-size="12.5px" font-weight="800" text-anchor="middle">1</text>
+</svg>
diff --git a/site/blog/claude-code-on-a-vps.html b/site/blog/claude-code-on-a-vps.html
index a4beddba..e95ab68d 100644
--- a/site/blog/claude-code-on-a-vps.html
+++ b/site/blog/claude-code-on-a-vps.html
@@ -37,7 +37,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-blog">
<a class="skip" href="#main">Skip to content</a>
@@ -152,7 +152,7 @@ docker compose exec kwnt kwnt signin-link</code></pre>
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"BlogPosting","@id":"https://kwant.si/blog/claude-code-on-a-vps#post","headline":"Run Claude Code on a VPS and reach it from your phone","description":"Three ways to run Claude Code on a VPS and reach it from your phone: SSH and tmux, Anthropic's Remote Control, or a self-hosted AI agent team with kwant.","url":"https://kwant.si/blog/claude-code-on-a-vps","mainEntityOfPage":"https://kwant.si/blog/claude-code-on-a-vps","image":"https://kwant.si/assets/og/blog-claude-code-on-a-vps.png?v=3dd3b9e0c8","inLanguage":"en","datePublished":"2026-10-31","dateModified":"2026-10-31","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"wordCount":1406,"isPartOf":{"@id":"https://kwant.si/blog/#blog"},"about":{"@id":"https://kwant.si/#app"},"keywords":["claude-code","vps","self-hosted","how-to","ai-agents"]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://kwant.si/blog/"},{"@type":"ListItem","position":3,"name":"Run Claude Code on a VPS and reach it from your phone","item":"https://kwant.si/blog/claude-code-on-a-vps"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/blog/claude-code-scheduled-tasks-compared.html b/site/blog/claude-code-scheduled-tasks-compared.html
index 0c826abc..9e2656e3 100644
--- a/site/blog/claude-code-scheduled-tasks-compared.html
+++ b/site/blog/claude-code-scheduled-tasks-compared.html
@@ -37,7 +37,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-blog">
<a class="skip" href="#main">Skip to content</a>
@@ -146,7 +146,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"BlogPosting","@id":"https://kwant.si/blog/claude-code-scheduled-tasks-compared#post","headline":"Claude Code scheduled tasks: cloud vs desktop vs /loop","description":"Claude Code can schedule work in the cloud, on your desktop or inside a session. Here is how the three differ, plus a self-hosted AI agent option.","url":"https://kwant.si/blog/claude-code-scheduled-tasks-compared","mainEntityOfPage":"https://kwant.si/blog/claude-code-scheduled-tasks-compared","image":"https://kwant.si/assets/og/blog-claude-code-scheduled-tasks-compared.png?v=2a4f6ad47a","inLanguage":"en","datePublished":"2026-10-31","dateModified":"2026-10-31","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"wordCount":1138,"isPartOf":{"@id":"https://kwant.si/blog/#blog"},"about":{"@id":"https://kwant.si/#app"},"keywords":["claude-code","scheduled-tasks","routines","self-hosted","comparison"]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://kwant.si/blog/"},{"@type":"ListItem","position":3,"name":"Claude Code scheduled tasks: cloud vs desktop vs /loop","item":"https://kwant.si/blog/claude-code-scheduled-tasks-compared"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/blog/index.html b/site/blog/index.html
index b040153a..d2bb5044 100644
--- a/site/blog/index.html
+++ b/site/blog/index.html
@@ -30,7 +30,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-blog">
<a class="skip" href="#main">Skip to content</a>
@@ -99,7 +99,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"Blog","@id":"https://kwant.si/blog/#blog","name":"kwant blog","description":"Guides, comparisons and notes on running a self-hosted team of AI agents with kwant.","url":"https://kwant.si/blog/","inLanguage":"en","publisher":{"@id":"https://kwant.si/#org"},"isPartOf":{"@id":"https://kwant.si/#website"},"blogPost":[{"@type":"BlogPosting","@id":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud#post","headline":"Self-host a Grok Bot alternative for free on Oracle Cloud","url":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud","datePublished":"2026-11-05","dateModified":"2026-11-06"},{"@type":"BlogPosting","@id":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant#post","headline":"OpenClaw vs Hermes Agent vs kwant: self-hosted AI agents","url":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant","datePublished":"2026-11-01","dateModified":"2026-11-01"},{"@type":"BlogPosting","@id":"https://kwant.si/blog/claude-code-scheduled-tasks-compared#post","headline":"Claude Code scheduled tasks: cloud vs desktop vs /loop","url":"https://kwant.si/blog/claude-code-scheduled-tasks-compared","datePublished":"2026-10-31","dateModified":"2026-10-31"},{"@type":"BlogPosting","@id":"https://kwant.si/blog/claude-code-on-a-vps#post","headline":"Run Claude Code on a VPS and reach it from your phone","url":"https://kwant.si/blog/claude-code-on-a-vps","datePublished":"2026-10-31","dateModified":"2026-10-31"}]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://kwant.si/blog/"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/blog/openclaw-vs-hermes-agent-vs-kwant.html b/site/blog/openclaw-vs-hermes-agent-vs-kwant.html
index a3a4e07c..55338ad7 100644
--- a/site/blog/openclaw-vs-hermes-agent-vs-kwant.html
+++ b/site/blog/openclaw-vs-hermes-agent-vs-kwant.html
@@ -38,7 +38,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-blog">
<a class="skip" href="#main">Skip to content</a>
@@ -158,7 +158,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"BlogPosting","@id":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant#post","headline":"OpenClaw vs Hermes Agent vs kwant: self-hosted AI agents","description":"A fair look at OpenClaw, Hermes Agent and kwant, three self-hosted AI agents. What each is built for, where each is the better pick, and how they install.","url":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant","mainEntityOfPage":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant","image":"https://kwant.si/assets/og/blog-openclaw-vs-hermes-agent-vs-kwant.png?v=9aa173965e","inLanguage":"en","datePublished":"2026-11-01","dateModified":"2026-11-01","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"wordCount":1682,"isPartOf":{"@id":"https://kwant.si/blog/#blog"},"about":{"@id":"https://kwant.si/#app"},"keywords":["openclaw","hermes-agent","kwant","self-hosted","comparison","ai-agents"]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://kwant.si/blog/"},{"@type":"ListItem","position":3,"name":"OpenClaw vs Hermes Agent vs kwant: self-hosted AI agents","item":"https://kwant.si/blog/openclaw-vs-hermes-agent-vs-kwant"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/blog/self-host-grok-bot-alternative-free-oracle-cloud.html b/site/blog/self-host-grok-bot-alternative-free-oracle-cloud.html
index 3273b286..ec414e42 100644
--- a/site/blog/self-host-grok-bot-alternative-free-oracle-cloud.html
+++ b/site/blog/self-host-grok-bot-alternative-free-oracle-cloud.html
@@ -40,7 +40,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-blog">
<a class="skip" href="#main">Skip to content</a>
@@ -270,7 +270,7 @@ Steps 1 to 3 happen in Oracle's web console, so guide me through them and wait f
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"BlogPosting","@id":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud#post","headline":"Self-host a Grok Bot alternative for free on Oracle Cloud","description":"Run kwant free on Oracle Cloud's Always Free Arm server with Docker, connect Claude, ChatGPT, Grok or another model, and bring your Grok bots across.","url":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud","mainEntityOfPage":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud","image":"https://kwant.si/assets/og/blog-self-host-grok-bot-alternative-free-oracle-cloud.png?v=b7f7b9673f","inLanguage":"en","datePublished":"2026-11-05","dateModified":"2026-11-06","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"wordCount":4508,"isPartOf":{"@id":"https://kwant.si/blog/#blog"},"about":{"@id":"https://kwant.si/#app"},"keywords":["grok","claude","chatgpt","self-hosted","how-to","vps","oracle-cloud","ai-agents"]},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://kwant.si/blog/"},{"@type":"ListItem","position":3,"name":"Self-host a Grok Bot alternative for free on Oracle Cloud","item":"https://kwant.si/blog/self-host-grok-bot-alternative-free-oracle-cloud"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/contact.html b/site/contact.html
index 0898a36f..7cd10378 100644
--- a/site/contact.html
+++ b/site/contact.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-contact">
<a class="skip" href="#main">Skip to content</a>
@@ -108,7 +108,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"ContactPage","@id":"https://kwant.si/contact","name":"Contact","description":"How to reach the people behind kwant. Email [email protected] for questions, a commercial license, privacy requests or press. Bugs and ideas go to GitHub issues, security problems to a private GitHub report.","url":"https://kwant.si/contact","image":"https://kwant.si/assets/og/contact.png?v=232b45aa77","inLanguage":"en","dateModified":"2026-11-06","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Contact","item":"https://kwant.si/contact"}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/accounts.html b/site/docs/accounts.html
index 0fe97566..96b806b1 100644
--- a/site/docs/accounts.html
+++ b/site/docs/accounts.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -157,7 +157,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/accounts#article","headline":"Multiple Claude, Codex & Grok accounts","description":"Add several logins or API keys per engine, plus OpenAI- or Anthropic-compatible servers, in one order to use, with automatic failover across engines when one runs out of usage.","url":"https://kwant.si/docs/accounts","mainEntityOfPage":"https://kwant.si/docs/accounts","image":"https://kwant.si/assets/og/docs-accounts.png?v=4f7b1b0e06","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-04","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Accounts & profiles","item":"https://kwant.si/docs/accounts"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/agents-connect.html b/site/docs/agents-connect.html
index b8a57ec7..e065178e 100644
--- a/site/docs/agents-connect.html
+++ b/site/docs/agents-connect.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -181,7 +181,7 @@ bearer_token_env_var = "KWANT_AGENT_TOKEN"</code></pre>
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/agents-connect#article","headline":"Use kwant from Claude Code, Codex or Cursor over MCP","description":"Let Claude Code, Codex, Cursor and other MCP clients ask your self-hosted kwant bots for work and get the reply back. One token per connection, only the bots you pick, can't approve anything, revoked at once.","url":"https://kwant.si/docs/agents-connect","mainEntityOfPage":"https://kwant.si/docs/agents-connect","image":"https://kwant.si/assets/og/docs-agents-connect.png?v=b56566b450","inLanguage":"en","datePublished":"2026-11-07","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Coding agents","item":"https://kwant.si/docs/agents-connect"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/approvals.html b/site/docs/approvals.html
index e926f7e2..57b3324a 100644
--- a/site/docs/approvals.html
+++ b/site/docs/approvals.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -169,7 +169,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/approvals#article","headline":"Human approval for AI agent actions","description":"kwant asks before bots run commands or edit outside their folder. Three approval modes per space or bot, plus saved passwords in a vault or Bitwarden.","url":"https://kwant.si/docs/approvals","mainEntityOfPage":"https://kwant.si/docs/approvals","image":"https://kwant.si/assets/og/docs-approvals.png?v=188ab5dbec","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Approvals & passwords","item":"https://kwant.si/docs/approvals"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/bots-and-teams.html b/site/docs/bots-and-teams.html
index ec7495a0..3f19f744 100644
--- a/site/docs/bots-and-teams.html
+++ b/site/docs/bots-and-teams.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -256,7 +256,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/bots-and-teams#article","headline":"AI agent teams: bots, leads & handoffs","description":"Create bots from persona presets, give each a soul and a model, group them into teams with a lead, and let them hand work to each other with @mentions.","url":"https://kwant.si/docs/bots-and-teams","mainEntityOfPage":"https://kwant.si/docs/bots-and-teams","image":"https://kwant.si/assets/og/docs-bots-and-teams.png?v=b027504528","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Bots & teams","item":"https://kwant.si/docs/bots-and-teams"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/browser.html b/site/docs/browser.html
index abdcb27d..56b39771 100644
--- a/site/docs/browser.html
+++ b/site/docs/browser.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -255,7 +255,7 @@ docker build -t kwnt-executor:v1 -f docker/executor.Dockerfile docker</code></pr
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/browser#article","headline":"AI agent browser: your Chrome or Docker","description":"Watch your bots browse live in the app. Run the browser on your own Chrome in Local mode, or isolated in a Docker container in VM mode.","url":"https://kwant.si/docs/browser","mainEntityOfPage":"https://kwant.si/docs/browser","image":"https://kwant.si/assets/og/docs-browser.png?v=7175e8f75c","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Browser","item":"https://kwant.si/docs/browser"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/dev-mode.html b/site/docs/dev-mode.html
index 799b889a..91bf3446 100644
--- a/site/docs/dev-mode.html
+++ b/site/docs/dev-mode.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -256,7 +256,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/dev-mode#article","headline":"Dev mode: AI code review and a production safety floor","description":"Point a kwant space at its git repos, on GitHub, GitLab, Gitea, Forgejo or any git server. Bots explain every merge in plain words, review each pull request with a second bot, and every push to main or deploy asks you first.","url":"https://kwant.si/docs/dev-mode","mainEntityOfPage":"https://kwant.si/docs/dev-mode","image":"https://kwant.si/assets/og/docs-dev-mode.png?v=4b20e5912f","inLanguage":"en","datePublished":"2026-11-06","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Dev mode","item":"https://kwant.si/docs/dev-mode"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/flight-school.html b/site/docs/flight-school.html
index ccf315fe..ff629970 100644
--- a/site/docs/flight-school.html
+++ b/site/docs/flight-school.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -188,7 +188,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/flight-school#article","headline":"Flight School: earned freedom for AI agents","description":"Set each bot's tier per kind of work: Observe, Sandbox or Act. Bots earn a step up with a scorecard, only you grant it, payments always ask, and you can revoke a tier in a click.","url":"https://kwant.si/docs/flight-school","mainEntityOfPage":"https://kwant.si/docs/flight-school","image":"https://kwant.si/assets/og/docs-flight-school.png?v=3182073a3c","inLanguage":"en","datePublished":"2026-10-28","dateModified":"2026-11-06","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Flight School","item":"https://kwant.si/docs/flight-school"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/goals.html b/site/docs/goals.html
index 3d2c18b8..75561bf4 100644
--- a/site/docs/goals.html
+++ b/site/docs/goals.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -158,7 +158,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/goals#article","headline":"Goals: keep a site, a service or a file working with AI agents","description":"A kwant goal checks that a page answers, a command succeeds or a file exists. When it breaks, a bot looks into it and offers one fix. Nothing runs until you create or approve a goal.","url":"https://kwant.si/docs/goals","mainEntityOfPage":"https://kwant.si/docs/goals","image":"https://kwant.si/assets/og/docs-goals.png?v=4c121eb96a","inLanguage":"en","datePublished":"2026-11-03","dateModified":"2026-11-05","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Goals","item":"https://kwant.si/docs/goals"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/idea-jar.html b/site/docs/idea-jar.html
index db9ea67a..53a1e6c1 100644
--- a/site/docs/idea-jar.html
+++ b/site/docs/idea-jar.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -165,7 +165,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/idea-jar#article","headline":"Idea jar: drop an idea, a free AI agent writes its take","description":"Drop an idea in kwant's Idea jar. When a bot is free, it writes a take: worth it or not, the effort, the risks and a short plan. Do it turns it into a draft mission you approve.","url":"https://kwant.si/docs/idea-jar","mainEntityOfPage":"https://kwant.si/docs/idea-jar","image":"https://kwant.si/assets/og/docs-idea-jar.png?v=dfa065b378","inLanguage":"en","datePublished":"2026-11-06","dateModified":"2026-11-06","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Idea jar","item":"https://kwant.si/docs/idea-jar"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/install.html b/site/docs/install.html
index 2104ce30..f54b73c4 100644
--- a/site/docs/install.html
+++ b/site/docs/install.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -67,7 +67,24 @@
<h2 id="mac">The Mac app</h2>
<p><a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_universal.dmg" rel="noopener">Download the Mac app</a> (a universal <code>.dmg</code> for Apple silicon and Intel), open it and drag kwant to Applications. It runs its own kwant bots on your Mac, with the same data folder as <code>kwnt serve</code> (<code>~/.kwnt</code>), and keeps running in the menu bar when you close the window.</p>
-<p class="note warn">The app is signed ad hoc, not notarized by Apple, so macOS stops it the first time with “Apple could not verify…”. Click Done, open <b>System Settings › Privacy &amp; Security</b>, scroll down and click <b>Open Anyway</b> next to kwant. On macOS 14 or earlier, right-click the app and choose <b>Open</b> instead. After that it opens normally.</p>
+<p>The app is signed ad hoc, not notarized by Apple yet, so macOS asks once, the first time you open it:</p>
+<div class="mac-first-doc">
+ <ol class="mf-steps">
+ <li><span>Drag kwant to Applications and open it. When macOS says it couldn't verify it, click <b>Done</b>.</span></li>
+ <li><span>Open <b>System Settings › Privacy &amp; Security</b> and scroll down to <b>Security</b>.</span></li>
+ <li><span>Click <b>Open Anyway</b> next to “kwant” was blocked, then <b>Open Anyway</b> again, and enter your Mac password or use Touch ID.</span></li>
+ </ol>
+ <figure class="mf-fig">
+ <a class="zoom" href="../assets/media/open-anyway-wide.svg?v=1ba6501944" data-caption="A mock-up of macOS 15: the “kwant” Not Opened alert (click Done), System Settings › Privacy &amp; Security, and Open Anyway under Security.">
+ <picture>
+ <source media="(max-width: 640px)" srcset="../assets/media/open-anyway-phone.svg?v=f4ad17b0e1">
+ <img src="../assets/media/open-anyway-wide.svg?v=1ba6501944" width="560" height="360" loading="lazy" decoding="async"
+ alt="A mock-up of the three macOS steps: the “kwant” Not Opened alert with Done marked, System Settings › Privacy &amp; Security, and the Security row “kwant” was blocked to protect your Mac with Open Anyway marked.">
+ </picture>
+ </a>
+ </figure>
+ <p class="mf-after">You only do this once. On macOS 14 or earlier, right-click kwant in Applications and choose <b>Open</b> instead.</p>
+</div>
<p>When a bot needs you, with a question or an approval, the menu-bar icon plays a short animation once and a small note drops under it; click it to open that chat. The Linux app changes its tray icon and shows a notification. Untick <b>Show nudges</b> in the icon's menu to turn them off.</p>
@@ -240,7 +257,7 @@ docker compose exec kwnt kwnt doctor</code></pre>
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/install#article","headline":"Install kwnt: self-host AI agents on a VPS or Docker","description":"Build the kwnt binary and run your AI bots on your laptop, on a VPS with systemd, or with Docker Compose behind an HTTPS reverse proxy.","url":"https://kwant.si/docs/install","mainEntityOfPage":"https://kwant.si/docs/install","image":"https://kwant.si/assets/og/docs-install.png?v=8675f78476","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Install & run","item":"https://kwant.si/docs/install"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/lessons.html b/site/docs/lessons.html
index d2eaa347..a02c2fd0 100644
--- a/site/docs/lessons.html
+++ b/site/docs/lessons.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -135,7 +135,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/lessons#article","headline":"Lessons: AI agents that learn from their earlier tasks","description":"In kwant, a bot's failed checks, stalled turns, your send-backs and goals that stopped holding become short lessons it sees before similar work. They come from kwant's own records, so a bot can't write its own.","url":"https://kwant.si/docs/lessons","mainEntityOfPage":"https://kwant.si/docs/lessons","image":"https://kwant.si/assets/og/docs-lessons.png?v=3c2efd7314","inLanguage":"en","datePublished":"2026-11-03","dateModified":"2026-11-03","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Lessons","item":"https://kwant.si/docs/lessons"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/loose-ends.html b/site/docs/loose-ends.html
index 61becc9d..e684a69a 100644
--- a/site/docs/loose-ends.html
+++ b/site/docs/loose-ends.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -151,7 +151,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/loose-ends#article","headline":"Loose ends: AI that finds unfinished follow-ups","description":"kwant finds threads you never finished in chats, email and GitHub, and reads letters you photograph. It drafts the next step and never sends anything.","url":"https://kwant.si/docs/loose-ends","mainEntityOfPage":"https://kwant.si/docs/loose-ends","image":"https://kwant.si/assets/og/docs-loose-ends.png?v=4b2c634102","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Loose ends & letters","item":"https://kwant.si/docs/loose-ends"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/mcp.html b/site/docs/mcp.html
index c7d2683a..6be49a39 100644
--- a/site/docs/mcp.html
+++ b/site/docs/mcp.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -152,7 +152,7 @@ curl -X POST http://127.0.0.1:8799/api/mcp/servers \
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/mcp#article","headline":"MCP tools for AI agents: a self-hosted client","description":"Connect Model Context Protocol servers to your kwant bots, with per-bot access, masked secrets, OAuth sign-in and approval before risky tool calls.","url":"https://kwant.si/docs/mcp","mainEntityOfPage":"https://kwant.si/docs/mcp","image":"https://kwant.si/assets/og/docs-mcp.png?v=1e10ed37cf","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-01","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"MCP tools","item":"https://kwant.si/docs/mcp"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/memory-skills.html b/site/docs/memory-skills.html
index 5f8cdaa9..6cfece89 100644
--- a/site/docs/memory-skills.html
+++ b/site/docs/memory-skills.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -146,7 +146,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/memory-skills#article","headline":"AI agent memory, skills & chat search","description":"What kwant bots remember and how you edit it, skills bots propose and you approve, and search across every chat in a space. Local and editable.","url":"https://kwant.si/docs/memory-skills","mainEntityOfPage":"https://kwant.si/docs/memory-skills","image":"https://kwant.si/assets/og/docs-memory-skills.png?v=54eaa67648","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-03","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Memory, skills & search","item":"https://kwant.si/docs/memory-skills"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/mission-board.html b/site/docs/mission-board.html
index bba36889..848b2802 100644
--- a/site/docs/mission-board.html
+++ b/site/docs/mission-board.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -257,7 +257,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/mission-board#article","headline":"Mission board: AI agent tasks with proof","description":"One board for all bot work. A task is Verified only when a check passes. Leads review hand-offs, AutoFix retries safely, Insights shows verified results and their cost.","url":"https://kwant.si/docs/mission-board","mainEntityOfPage":"https://kwant.si/docs/mission-board","image":"https://kwant.si/assets/og/docs-mission-board.png?v=cb9229cc7c","inLanguage":"en","datePublished":"2026-10-28","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Mission board","item":"https://kwant.si/docs/mission-board"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/models.html b/site/docs/models.html
index e4c69b95..57ff9d0e 100644
--- a/site/docs/models.html
+++ b/site/docs/models.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -140,7 +140,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/models#article","headline":"Models & routing: Claude, Codex, Grok, Ollama","description":"Run bots on the Claude, Codex or Grok CLIs, API keys, local Ollama or any OpenAI-compatible server. The Laya router picks who answers, and which model.","url":"https://kwant.si/docs/models","mainEntityOfPage":"https://kwant.si/docs/models","image":"https://kwant.si/assets/og/docs-models.png?v=f251eb8e2d","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Models & routing","item":"https://kwant.si/docs/models"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/parallel-universe.html b/site/docs/parallel-universe.html
index 5f8f7b47..e91edd47 100644
--- a/site/docs/parallel-universe.html
+++ b/site/docs/parallel-universe.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -141,7 +141,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/parallel-universe#article","headline":"Parallel Universe: compare deployment options","description":"Load-test up to three ways to deploy an app in sealed Docker containers, next to a dated price estimate. No cloud account and no spending.","url":"https://kwant.si/docs/parallel-universe","mainEntityOfPage":"https://kwant.si/docs/parallel-universe","image":"https://kwant.si/assets/og/docs-parallel-universe.png?v=9fd9b01114","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-10-29","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Parallel Universe","item":"https://kwant.si/docs/parallel-universe"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/quickstart.html b/site/docs/quickstart.html
index 694e9267..f2a036b5 100644
--- a/site/docs/quickstart.html
+++ b/site/docs/quickstart.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -173,7 +173,7 @@ cd frontend &amp;&amp; npm test <span class="c"># web app tests</span></code></
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/quickstart#article","headline":"Quickstart: run a team of AI agents locally","description":"Download the kwant app for Mac or Linux, add a Claude, Codex or Grok login or an API key, and ask your first team of AI bots a question.","url":"https://kwant.si/docs/quickstart","mainEntityOfPage":"https://kwant.si/docs/quickstart","image":"https://kwant.si/assets/og/docs-quickstart.png?v=351be984e5","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Quickstart","item":"https://kwant.si/docs/quickstart"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/routines.html b/site/docs/routines.html
index 05357a7b..95f0f31e 100644
--- a/site/docs/routines.html
+++ b/site/docs/routines.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -178,7 +178,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/routines#article","headline":"Scheduled AI agents: routines & cron","description":"Schedule bot work with routines, cron rules and follow-ups that run on your own machine, with an Undo on every change bots make.","url":"https://kwant.si/docs/routines","mainEntityOfPage":"https://kwant.si/docs/routines","image":"https://kwant.si/assets/og/docs-routines.png?v=7be758aed4","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-04","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Routines & bot actions","item":"https://kwant.si/docs/routines"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/smart-results.html b/site/docs/smart-results.html
index 63cf845d..0505b426 100644
--- a/site/docs/smart-results.html
+++ b/site/docs/smart-results.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -145,7 +145,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/smart-results#article","headline":"Smart Results: AI agent replies as tables, charts and checklists","description":"kwant draws a bot's table or list as a sortable comparison, a chart, key numbers, findings or a checklist, copied from the reply word for word. The reply text never changes.","url":"https://kwant.si/docs/smart-results","mainEntityOfPage":"https://kwant.si/docs/smart-results","image":"https://kwant.si/assets/og/docs-smart-results.png?v=9fa23c8a28","inLanguage":"en","datePublished":"2026-11-03","dateModified":"2026-11-04","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Smart Results","item":"https://kwant.si/docs/smart-results"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/spaces.html b/site/docs/spaces.html
index 6ada31aa..15482981 100644
--- a/site/docs/spaces.html
+++ b/site/docs/spaces.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -166,7 +166,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/spaces#article","headline":"Spaces: separate AI agents for work and home","description":"Keep work, side projects and home apart. Each space has its own bots, teams, channels, routines, skills, tool servers, accounts and approval rules.","url":"https://kwant.si/docs/spaces","mainEntityOfPage":"https://kwant.si/docs/spaces","image":"https://kwant.si/assets/og/docs-spaces.png?v=619ff76f9a","inLanguage":"en","datePublished":"2026-10-22","dateModified":"2026-11-01","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Spaces","item":"https://kwant.si/docs/spaces"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/telegram.html b/site/docs/telegram.html
index 371971af..5398e1e3 100644
--- a/site/docs/telegram.html
+++ b/site/docs/telegram.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -139,7 +139,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/telegram#article","headline":"Telegram: message your kwant bots and get alerts on your phone","description":"Pair a Telegram chat with a kwant space. Write to your bots from Telegram, get their replies, questions and approvals on your phone, and allow some approvals once with a tap. It needs no public address.","url":"https://kwant.si/docs/telegram","mainEntityOfPage":"https://kwant.si/docs/telegram","image":"https://kwant.si/assets/og.png","inLanguage":"en","datePublished":"2026-11-07","dateModified":"2026-11-07","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Telegram","item":"https://kwant.si/docs/telegram"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/docs/truth-ledger.html b/site/docs/truth-ledger.html
index 3a78c151..feea244a 100644
--- a/site/docs/truth-ledger.html
+++ b/site/docs/truth-ledger.html
@@ -31,7 +31,7 @@
<link rel="apple-touch-icon" href="../apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="../assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="../assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="../assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="../assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-docs">
<a class="skip" href="#main">Skip to content</a>
@@ -138,7 +138,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="../assets/js/site.js?v=63f328cd53" defer></script>
+<script src="../assets/js/site.js?v=9846e390c8" defer></script>
<script src="../assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"TechArticle","@id":"https://kwant.si/docs/truth-ledger#article","headline":"Truth Ledger: shared facts your AI agents agree on","description":"With the Truth Ledger on, kwant bots read their notes from one list of facts. Conflicting facts are flagged until you settle them, and notes from outside text wait for you. On from 0.6.5.","url":"https://kwant.si/docs/truth-ledger","mainEntityOfPage":"https://kwant.si/docs/truth-ledger","image":"https://kwant.si/assets/og/docs-truth-ledger.png?v=c47e1653cd","inLanguage":"en","datePublished":"2026-11-01","dateModified":"2026-11-03","author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"},"about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Docs","item":"https://kwant.si/docs/quickstart"},{"@type":"ListItem","position":3,"name":"Truth Ledger","item":"https://kwant.si/docs/truth-ledger"}]},{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/features.html b/site/features.html
index bf281ccc..2a82ce7d 100644
--- a/site/features.html
+++ b/site/features.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-features">
<a class="skip" href="#main">Skip to content</a>
@@ -1044,7 +1044,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://kwant.si/features","name":"Features: self-hosted AI agent orchestration","description":"Teams and @mention handoffs, Dev mode code review, the Idea jar, Smart Results, Goals, model failover across accounts, spaces, routines, approvals, memory, skills, MCP tools and a bot browser.","url":"https://kwant.si/features","image":"https://kwant.si/assets/og/features.png?v=6c9323bb00","inLanguage":"en","dateModified":"2026-11-07","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Features","item":"https://kwant.si/features"}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/index.html b/site/index.html
index e1388146..7c2dfc1a 100644
--- a/site/index.html
+++ b/site/index.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-home">
<a class="skip" href="#main">Skip to content</a>
@@ -56,7 +56,32 @@
<a class="btn btn-soft" href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_amd64.deb" rel="noopener">Download for Linux <span class="beta">beta</span></a>
<p class="cta-alt"><a href="/docs/quickstart">A VPS or Docker? Get started <span aria-hidden="true">→</span></a></p>
</div>
- <p class="mac-dl">Free, for Apple silicon and Intel. <a href="/docs/install#mac">First open</a> needs one extra step. Linux: a <code>.deb</code> for Ubuntu and Debian on x86_64, or the <a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_x86_64.AppImage" rel="noopener">AppImage</a> (<a href="/docs/install#linux">how to install</a>).</p>
+ <details class="mac-first" id="mac-first">
+ <summary>
+ <span class="mf-ico" aria-hidden="true"><svg viewBox="0 0 20 20" fill="currentColor"><path d="M4 4h12v1H4zM3 5h1v8H3zM16 5h1v8h-1zM4 12h12v1H4zM1 14h18v2H1z"/><path d="M5 6h10v6H5z" opacity=".22"/><path d="M8 8h1v2H8zM11 8h1v2h-1z"/></svg></span>
+ <span class="mf-sum"><b>First time on a Mac?</b><span>macOS asks once, because kwant isn't notarized by Apple yet.</span></span>
+ <svg class="mf-chev" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"/></svg>
+ </summary>
+ <div class="mf-body">
+ <ol class="mf-steps">
+ <li><span>Drag kwant to Applications and open it. When macOS says it couldn't verify it, click <b>Done</b>.</span></li>
+ <li><span>Open <b>System Settings › Privacy &amp; Security</b> and scroll down to <b>Security</b>.</span></li>
+ <li><span>Click <b>Open Anyway</b> next to “kwant” was blocked, then <b>Open Anyway</b> again, and enter your Mac password or use Touch ID.</span></li>
+ </ol>
+ <figure class="mf-fig">
+ <a class="zoom" href="assets/media/open-anyway-wide.svg?v=1ba6501944" data-caption="A mock-up of macOS 15: the “kwant” Not Opened alert (click Done), System Settings › Privacy &amp; Security, and Open Anyway under Security.">
+ <picture>
+ <source media="(max-width: 640px)" srcset="assets/media/open-anyway-phone.svg?v=f4ad17b0e1">
+ <img src="assets/media/open-anyway-wide.svg?v=1ba6501944" width="560" height="360" loading="lazy" decoding="async"
+ alt="A mock-up of the three macOS steps: the “kwant” Not Opened alert with Done marked, System Settings › Privacy &amp; Security, and the Security row “kwant” was blocked to protect your Mac with Open Anyway marked.">
+ </picture>
+ </a>
+ </figure>
+ <p class="mf-after">You only do this once. On macOS 14 or earlier, right-click kwant in Applications and choose <b>Open</b> instead.</p>
+ <p class="mf-term" data-term="soon"><span class="soon">Soon</span>A one-line Terminal install that skips this step.</p>
+ </div>
+ </details>
+ <p class="mac-dl">Free, for Apple silicon and Intel. Linux: a <code>.deb</code> for Ubuntu and Debian on x86_64, or the <a href="https://github.com/alexsergivan/kwant/releases/latest/download/kwant_x86_64.AppImage" rel="noopener">AppImage</a> (<a href="/docs/install#linux">how to install</a>).</p>
<div class="install" data-tabs><div class="install-top"><span class="install-k" aria-hidden="true">Install</span><div class="tabs" role="tablist" aria-label="Install with"><button type="button" role="tab" id="hero-t-src" aria-controls="hero-p-src" aria-selected="true">macOS · Linux</button><button type="button" role="tab" id="hero-t-docker" aria-controls="hero-p-docker" aria-selected="false" tabindex="-1">Docker</button></div></div><div class="cmd" role="tabpanel" id="hero-p-src" aria-labelledby="hero-t-src"><span class="p" aria-hidden="true">$</span><code>git clone https://github.com/alexsergivan/kwant &amp;&amp; cd kwant &amp;&amp; make run</code><button type="button" class="copy-cmd" aria-label="Copy the macOS · Linux install command">copy</button></div><div class="cmd" role="tabpanel" id="hero-p-docker" aria-labelledby="hero-t-docker" hidden><span class="p" aria-hidden="true">$</span><code>git clone https://github.com/alexsergivan/kwant &amp;&amp; cd kwant &amp;&amp; docker compose up -d --build</code><button type="button" class="copy-cmd" aria-label="Copy the Docker install command">copy</button></div></div>
<p class="proof">0.7.5 released Nov 7 <span aria-hidden="true">·</span> <a href="https://github.com/alexsergivan/kwant/releases" rel="noopener">30 releases since Oct 25</a> <span aria-hidden="true">·</span> <a href="https://github.com/alexsergivan/kwant" rel="noopener">AGPL-3.0, open source</a></p>
</div>
@@ -435,7 +460,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://kwant.si/#org","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","logo":"https://kwant.si/apple-touch-icon.png","sameAs":["https://github.com/alexsergivan/kwant"]},{"@type":"WebSite","@id":"https://kwant.si/#website","name":"kwant","url":"https://kwant.si/","inLanguage":"en","publisher":{"@id":"https://kwant.si/#org"}},{"@type":"SoftwareApplication","@id":"https://kwant.si/#app","name":"kwant","alternateName":"kwnt","url":"https://kwant.si/","description":"Open-source, self-hosted AI agents that share chats, hand off work and run on a schedule. One Rust binary (kwnt) for your laptop or a VPS.","applicationCategory":"DeveloperApplication","operatingSystem":"macOS, Linux","image":"https://kwant.si/assets/og/home.png?v=77495a5e49","screenshot":"https://kwant.si/assets/media/desktop-team-discussion-1440.webp","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"},"license":["https://github.com/alexsergivan/kwant/blob/main/LICENSE"],"isAccessibleForFree":true,"downloadUrl":"https://github.com/alexsergivan/kwant","sameAs":["https://github.com/alexsergivan/kwant"],"author":{"@id":"https://kwant.si/#org"},"publisher":{"@id":"https://kwant.si/#org"}},{"@type":"SoftwareSourceCode","@id":"https://kwant.si/#code","name":"kwant","codeRepository":"https://github.com/alexsergivan/kwant","programmingLanguage":["Rust","TypeScript"],"license":["https://github.com/alexsergivan/kwant/blob/main/LICENSE"],"targetProduct":{"@id":"https://kwant.si/#app"}}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/install.sh b/site/install.sh
new file mode 100755
index 00000000..f3501325
--- /dev/null
+++ b/site/install.sh
@@ -0,0 +1,309 @@
+#!/bin/sh
+# kwant in one line, on your own server or Mac:
+#
+# curl -fsSL https://kwant.si/install.sh | sh
+#
+# Linux (x86_64 or arm64, glibc 2.35+: Ubuntu 22.04+, Debian 12+): downloads the prebuilt kwnt from the
+# latest release, checks it against its .sha256 (a mismatch installs nothing), puts it in ~/.local/bin,
+# runs it as a systemd user service when this user has one (otherwise in the background, and says how to
+# start it again), starts `kwnt setup --yes` in the background and prints a one-time sign-in link: a
+# loopback one with the SSH tunnel to reach it from a laptop, any other with its QR code. A kwnt it
+# didn't start (by hand, no pid file) keeps running; it says so instead of "updated".
+# macOS: the same checked download of the Mac app, into ~/Applications.
+# Never uses sudo. Running it again upgrades kwant in place and keeps your data (~/.kwnt).
+#
+# For tests: KWNT_INSTALL_BASE_URL is where the release files are (default: the latest GitHub release),
+# and KWNT_INSTALL_SETUP_FLAGS is added to `kwnt setup --yes` (for example --dry-run).
+#
+# Everything is inside main(), called on the last line, so a download cut off half-way runs nothing.
+
+# `a && b || fail …` is meant: fail when any step before it fails
+# shellcheck disable=SC2015
+
+set -u
+
+say() { printf '%s\n' "$*"; }
+
+fail() {
+ printf 'kwant install: %s\n' "$*" >&2
+ exit 1
+}
+
+# fetch URL FILE
+fetch() {
+ if command -v curl >/dev/null 2>&1; then
+ curl -fsSL --retry 2 -o "$2" "$1"
+ elif command -v wget >/dev/null 2>&1; then
+ wget -q -O "$2" "$1"
+ else
+ fail "This needs curl or wget to download kwant. Install one of them, then run this again."
+ fi
+}
+
+# fetch_quiet URL: the body on stdout, or nothing
+fetch_quiet() {
+ if command -v curl >/dev/null 2>&1; then
+ curl -fsS --max-time 3 "$1" 2>/dev/null
+ else
+ wget -q -T 3 -O - "$1" 2>/dev/null
+ fi
+}
+
+sha256_of() {
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "$1" | awk '{print $1}'
+ elif command -v shasum >/dev/null 2>&1; then
+ shasum -a 256 "$1" | awk '{print $1}'
+ else
+ fail "This needs sha256sum or shasum to check the download. Nothing was installed."
+ fi
+}
+
+# download_checked NAME DIR: NAME and NAME.sha256 from the release into DIR, or stop with nothing installed
+download_checked() {
+ fetch "$BASE/$1" "$2/$1" || fail "Couldn't download $BASE/$1. Nothing was installed."
+ fetch "$BASE/$1.sha256" "$2/$1.sha256" || fail "Couldn't download $BASE/$1.sha256. Nothing was installed."
+ want=$(awk '{print $1; exit}' "$2/$1.sha256")
+ case "$want" in
+ *[!0-9a-f]* | "") want=bad ;;
+ esac
+ got=$(sha256_of "$2/$1")
+ if [ "${#want}" -ne 64 ] || [ "$got" != "$want" ]; then
+ fail "The download didn't match its checksum, so nothing was installed. Try again in a minute; if it keeps happening, tell us at https://kwant.si/contact.html"
+ fi
+}
+
+install_linux() {
+ case "$(uname -m)" in
+ x86_64 | amd64) arch=x86_64 label=x86_64 ;;
+ aarch64 | arm64) arch=aarch64 label=arm64 ;;
+ *) fail "The prebuilt kwant runs on x86_64 and arm64 Linux, not $(uname -m). Download kwant for your computer at https://kwant.si" ;;
+ esac
+ bindir="$HOME/.local/bin"
+ data="$HOME/.kwnt"
+ name="kwnt-linux-$arch.tar.gz"
+
+ download_checked "$name" "$TMP"
+ mkdir "$TMP/x" && tar -xzf "$TMP/$name" -C "$TMP/x" || fail "Couldn't unpack $name. Nothing was installed."
+ [ -f "$TMP/x/kwnt" ] || fail "$name has no kwnt in it. Nothing was installed."
+ chmod 755 "$TMP/x/kwnt"
+ version=$("$TMP/x/kwnt" --version </dev/null 2>/dev/null) ||
+ fail "This kwnt doesn't run here. It needs glibc 2.35 or newer (Ubuntu 22.04+, Debian 12+). Nothing was installed."
+ version=${version#kwnt }
+
+ old=""
+ if [ -x "$bindir/kwnt" ]; then
+ old=$("$bindir/kwnt" --version </dev/null 2>/dev/null) || old=""
+ old=${old#kwnt }
+ fi
+ mkdir -p "$bindir" "$data" || fail "Couldn't create $bindir or $data."
+ # A new file renamed over the old one: a running kwnt keeps its own copy until it restarts
+ cp "$TMP/x/kwnt" "$bindir/.kwnt.new" && chmod 755 "$bindir/.kwnt.new" && mv -f "$bindir/.kwnt.new" "$bindir/kwnt" ||
+ fail "Couldn't write $bindir/kwnt."
+ run_path="$bindir:$HOME/.grok/bin:/usr/local/bin:/usr/bin:/bin"
+
+ # A kwnt this installer didn't start (no pidfile, no service) keeps running the old version
+ port=$("$bindir/kwnt" status </dev/null 2>/dev/null | awk '$1 == "port" {print $2; exit}')
+ port=${port:-8799}
+ linger_cmd=""
+ if command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
+ mode=service
+ ours=$(systemctl --user show -p MainPID --value kwnt.service 2>/dev/null)
+ else
+ mode=background
+ ours=$(cat "$data/kwnt.pid" 2>/dev/null)
+ fi
+ case "$ours" in "" | *[!0-9]*) ours=0 ;; esac
+ outside=$(outside_kwnt "$ours")
+ if [ "$mode" = service ]; then
+ start_service
+ else
+ start_background
+ fi
+
+ # A browser, and Claude Code when no AI CLI is here yet: kwnt's own setup, never sudo (it prints
+ # what needs admin rights). Laya isn't in the list because the service installs it on its first
+ # start; two installs into the same folder at once would break each other.
+ parts=browser
+ if ! PATH="$run_path:$HOME/.claude/local" command -v claude >/dev/null 2>&1 &&
+ ! PATH="$run_path" command -v codex >/dev/null 2>&1 &&
+ ! PATH="$run_path" command -v grok >/dev/null 2>&1; then
+ parts=browser,claude
+ fi
+ # shellcheck disable=SC2086 # the test flags are meant to split into words
+ PATH="$run_path" nohup "$bindir/kwnt" setup --yes --only "$parts" ${KWNT_INSTALL_SETUP_FLAGS:-} >"$data/setup.log" 2>&1 </dev/null &
+
+ tries=0
+ until fetch_quiet "http://127.0.0.1:$port/api/health" | grep -q '"app":"kwnt"'; do
+ tries=$((tries + 1))
+ if [ "$tries" -ge 60 ]; then
+ if [ "$mode" = service ]; then logs="journalctl --user -u kwnt"; else logs="tail $data/kwnt.log"; fi
+ fail "kwant was installed but didn't answer on port $port within a minute. See what it says with: $logs. When it's up, run: $bindir/kwnt signin-link"
+ fi
+ sleep 1
+ done
+
+ run="kwnt"
+ case ":$PATH:" in
+ *":$bindir:"*) ;;
+ *) run="$bindir/kwnt" ;;
+ esac
+
+ if [ -n "$outside" ]; then
+ say "✓ kwant $version for Linux $label"
+ say "kwnt is already running outside this installer. Restart it to use the new version."
+ elif [ -n "$old" ] && [ "$old" != "$version" ]; then
+ say "✓ kwant $version for Linux $label (updated from $old)"
+ else
+ say "✓ kwant $version for Linux $label"
+ fi
+ if [ "$mode" = service ] && [ -z "$linger_cmd" ]; then
+ say "✓ Runs as a service for this user (starts after a reboot)"
+ elif [ "$mode" = service ]; then
+ say "✓ Runs as a service for this user"
+ say " To start it after a reboot too, someone with admin rights runs once: $linger_cmd"
+ else
+ say "✓ Runs in the background (this system has no user services)"
+ say " After a reboot, start it again with: nohup $bindir/kwnt serve >> $data/kwnt.log 2>&1 &"
+ fi
+ say "✓ Laya and a browser for the bots are getting ready in the background"
+ say ""
+ notice=$("$bindir/kwnt" signin-link --bare </dev/null) || fail "Couldn't make a sign-in link. Run: $run signin-link"
+ link=$(printf '%s\n' "$notice" | awk '/:\/\// {print $1; exit}')
+ case "$link" in
+ http://127.0.0.1:* | http://localhost:* | "http://[::1]:"*)
+ # Only this machine can open a loopback link (and its QR code): a laptop needs a tunnel
+ say "Open $link in a browser on this machine."
+ say "On a server? On your laptop, first run:"
+ say " ssh -N -L $port:127.0.0.1:$port $(id -un)@<this-server>"
+ say "then open the same link there. For a phone (HTTPS), see https://kwant.si/docs/install"
+ say ""
+ say "The link works once, for 15 minutes."
+ ;;
+ *)
+ say "Open this on your phone or laptop to finish. It works once, for 15 minutes:"
+ say ""
+ say "$notice"
+ say ""
+ ;;
+ esac
+ say "There you choose your AI and sign in. Nothing else to type here."
+ say "Lost the link? Run: $run signin-link"
+}
+
+# outside_kwnt OURS: "yes" when this user runs a `kwnt serve` other than pid OURS, or, with no pid of
+# ours, when something already answers as kwnt on the port
+outside_kwnt() {
+ me=$(id -u)
+ for proc in /proc/[0-9]*; do
+ [ "${proc#/proc/}" = "$1" ] && continue
+ # The program and its first argument (cmdline is NUL-separated)
+ args=$(tr '\0' '\n' <"$proc/cmdline" 2>/dev/null | head -n 2 | tr '\n' ' ') || continue
+ prog=${args%% *}
+ first=${args#* }
+ first=${first%% *}
+ if [ "${prog##*/}" = kwnt ] && [ "$first" = serve ] &&
+ [ "$(awk '$1 == "Uid:" {print $2; exit}' "$proc/status" 2>/dev/null)" = "$me" ]; then
+ echo yes
+ return
+ fi
+ done
+ if [ "$1" = 0 ] && fetch_quiet "http://127.0.0.1:$port/api/health" | grep -q '"app":"kwnt"'; then
+ echo yes
+ fi
+}
+
+start_service() {
+ unit_dir="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user"
+ mkdir -p "$unit_dir" || fail "Couldn't create $unit_dir."
+ cat >"$unit_dir/kwnt.service" <<UNIT || fail "Couldn't write $unit_dir/kwnt.service."
+# Written by kwant's install.sh; running it again rewrites this file.
+[Unit]
+Description=kwant bots (kwnt serve)
+After=network-online.target
+Wants=network-online.target
+
+[Service]
+ExecStart=%h/.local/bin/kwnt serve
+Environment=PATH=$run_path
+# Your own settings, one NAME=value per line (for example KWNT_ALLOWED_ORIGINS=https://kwant.example.com)
+EnvironmentFile=-%h/.kwnt/kwnt.env
+Restart=on-failure
+RestartSec=5
+
+[Install]
+WantedBy=default.target
+UNIT
+ systemctl --user daemon-reload &&
+ systemctl --user enable kwnt.service >/dev/null 2>&1 &&
+ systemctl --user restart kwnt.service ||
+ fail "Couldn't start the kwnt service. See: systemctl --user status kwnt"
+ # Lingering keeps user services running after logout and starts them at boot
+ user=$(id -un)
+ if [ "$(loginctl show-user "$user" -p Linger 2>/dev/null)" != "Linger=yes" ] &&
+ ! loginctl enable-linger --no-ask-password "$user" >/dev/null 2>&1; then
+ linger_cmd="sudo loginctl enable-linger $user"
+ fi
+}
+
+start_background() {
+ pidfile="$data/kwnt.pid"
+ if [ -f "$pidfile" ]; then
+ pid=$(cat "$pidfile")
+ case "$pid" in
+ "" | *[!0-9]*) ;;
+ *)
+ if kill -0 "$pid" 2>/dev/null && grep -q kwnt "/proc/$pid/cmdline" 2>/dev/null; then
+ kill "$pid" 2>/dev/null
+ n=0
+ while kill -0 "$pid" 2>/dev/null && [ "$n" -lt 10 ]; do
+ sleep 1
+ n=$((n + 1))
+ done
+ fi
+ ;;
+ esac
+ fi
+ PATH="$run_path" nohup "$bindir/kwnt" serve >>"$data/kwnt.log" 2>&1 </dev/null &
+ echo $! >"$pidfile"
+}
+
+install_mac() {
+ name="kwant_universal.app.tar.gz"
+ download_checked "$name" "$TMP"
+ mkdir "$TMP/x" && tar -xzf "$TMP/$name" -C "$TMP/x" || fail "Couldn't unpack $name. Nothing was installed."
+ [ -d "$TMP/x/kwant.app" ] || fail "$name has no kwant.app in it. Nothing was installed."
+ apps="$HOME/Applications"
+ mkdir -p "$apps" || fail "Couldn't create $apps."
+ rm -rf "$apps/.kwant.app.old"
+ if [ -d "$apps/kwant.app" ]; then
+ mv "$apps/kwant.app" "$apps/.kwant.app.old" || fail "Couldn't move the old kwant.app aside."
+ fi
+ if ! mv "$TMP/x/kwant.app" "$apps/kwant.app"; then
+ [ -d "$apps/.kwant.app.old" ] && mv "$apps/.kwant.app.old" "$apps/kwant.app"
+ fail "Couldn't put kwant.app in $apps."
+ fi
+ rm -rf "$apps/.kwant.app.old"
+ say "✓ kwant for Mac in $apps/kwant.app"
+ if [ -d /Applications/kwant.app ]; then
+ say " You also have kwant in /Applications. Keep one of them so you always open the new one."
+ fi
+ say ""
+ say "Open kwant from $apps (or run: open \"$apps/kwant.app\"). If it's open now, quit it and open it again."
+}
+
+main() {
+ BASE="${KWNT_INSTALL_BASE_URL:-https://github.com/alexsergivan/kwant/releases/latest/download}"
+ BASE="${BASE%/}"
+ [ -n "${HOME:-}" ] && [ -d "$HOME" ] || fail "HOME isn't set to a folder."
+ TMP=$(mktemp -d 2>/dev/null || mktemp -d -t kwnt) || fail "Couldn't make a temporary folder."
+ trap 'rm -rf "$TMP"' EXIT
+ trap 'exit 1' INT TERM
+ case "$(uname -s)" in
+ Linux) install_linux ;;
+ Darwin) install_mac ;;
+ *) fail "This one-line install works on Linux and macOS, not on $(uname -s). Download kwant for your computer at https://kwant.si" ;;
+ esac
+}
+
+main "$@"
diff --git a/site/privacy.html b/site/privacy.html
index 685a79ae..8526250b 100644
--- a/site/privacy.html
+++ b/site/privacy.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-legal">
<a class="skip" href="#main">Skip to content</a>
@@ -136,7 +136,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://kwant.si/privacy","name":"Privacy policy","description":"What kwant.si and the self-hosted kwant software send where. The website sets no cookies and counts page views with cookie-free Cloudflare Web Analytics; the software has no telemetry.","url":"https://kwant.si/privacy","image":"https://kwant.si/assets/og/privacy.png?v=f3dfda6219","inLanguage":"en","dateModified":"2026-11-01","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Privacy policy","item":"https://kwant.si/privacy"}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/self-hosted-ai-agents.html b/site/self-hosted-ai-agents.html
index 1f2434e3..76041c08 100644
--- a/site/self-hosted-ai-agents.html
+++ b/site/self-hosted-ai-agents.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-guide">
<a class="skip" href="#main">Skip to content</a>
@@ -193,7 +193,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://kwant.si/self-hosted-ai-agents","name":"Self-Hosted AI Agent Team: Run One Yourself","description":"What a self-hosted AI agent team is, what it takes to run one, and what stays on your machine. How kwant does it: one binary, your own logins.","url":"https://kwant.si/self-hosted-ai-agents","image":"https://kwant.si/assets/og/self-hosted-ai-agents.png?v=1cfc6f7ff2","inLanguage":"en","dateModified":"2026-10-29","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Self-Hosted AI Agent Team","item":"https://kwant.si/self-hosted-ai-agents"}]},{"@type":"FAQPage","@id":"https://kwant.si/self-hosted-ai-agents#faq","url":"https://kwant.si/self-hosted-ai-agents","mainEntity":[{"@type":"Question","name":"What is a self-hosted AI agent team?","acceptedAnswer":{"@type":"Answer","text":"It is a group of AI bots that you run on your own laptop, home server or VPS rather than in a vendor's cloud. The bots share chats, hand work to each other and can run on a schedule. kwant is an open-source (AGPL-3.0) example: one binary, kwnt, with the web app and database built in."}},{"@type":"Question","name":"Does self-hosting mean my data never leaves my machine?","acceptedAnswer":{"@type":"Answer","text":"No. kwant keeps its chats, settings and data in a folder on your machine and sends no telemetry to its developers. But a bot on a Claude, Codex or Grok login or an API key still sends its prompts to that provider. To keep a model on your own hardware, use local Ollama or your own OpenAI-compatible server."}},{"@type":"Question","name":"What do I need to run kwant?","acceptedAnswer":{"@type":"Answer","text":"A computer or VPS that stays on, Rust and Node.js to build it, and at least one AI login, API key or a local Ollama model. Once built, the kwnt binary needs no Node.js. Docker is only needed for VM mode and the bots' shared browser. kwant also sets up a small Python service called Laya to pick which bot answers."}},{"@type":"Question","name":"Can the bots run while I am away?","acceptedAnswer":{"@type":"Answer","text":"Yes. Routines run a prompt on a schedule, such as daily, weekly or a cron rule, and post the answer in a chat. They run on your own machine, so they run while that machine is on. A small VPS keeps them going around the clock."}},{"@type":"Question","name":"How do I stop a bot doing something I did not want?","acceptedAnswer":{"@type":"Answer","text":"kwant shows an approval card with the exact command or arguments before risky steps. You can allow once, always allow or deny. Payments always ask. The default \"ask only when risky\" mode guards against accidents but is not a sandbox, so use the stricter ask mode for bots or folders you do not trust."}},{"@type":"Question","name":"Is kwant free?","acceptedAnswer":{"@type":"Answer","text":"The software is free under the AGPL-3.0, and commercial licenses are available. You pay for whatever model accounts or API keys you connect. A local Ollama model needs no account or key."}}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/site/terms.html b/site/terms.html
index 09dfa264..bd1e95e4 100644
--- a/site/terms.html
+++ b/site/terms.html
@@ -29,7 +29,7 @@
<link rel="apple-touch-icon" href="apple-touch-icon.png?v=1bc2442f39">
<link rel="preload" href="assets/fonts/pixelify-sans.woff2?v=66e897e155" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="assets/fonts/inter-var.woff2?v=3100e775e8" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="assets/css/site.css?v=99f2fc30c3">
+<link rel="stylesheet" href="assets/css/site.css?v=94d7040e8f">
</head>
<body class="page-legal">
<a class="skip" href="#main">Skip to content</a>
@@ -128,7 +128,7 @@
<p class="foot-made">Made in Germany with <span aria-hidden="true">❤️</span><span class="sr-only">love</span></p>
</div>
</footer>
-<script src="assets/js/site.js?v=63f328cd53" defer></script>
+<script src="assets/js/site.js?v=9846e390c8" defer></script>
<script src="assets/js/pixel.js?v=ce88473d7b" defer></script>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","@id":"https://kwant.si/terms","name":"Terms of use","description":"kwant is free software under the GNU AGPL-3.0, provided as is. You run it yourself and are responsible for your accounts, your bots and their costs.","url":"https://kwant.si/terms","image":"https://kwant.si/assets/og/terms.png?v=1aca9ee37d","inLanguage":"en","dateModified":"2026-10-25","about":{"@id":"https://kwant.si/#app"},"isPartOf":{"@id":"https://kwant.si/#website"}},{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"kwant","item":"https://kwant.si/"},{"@type":"ListItem","position":2,"name":"Terms of use","item":"https://kwant.si/terms"}]}]}</script>
<!-- Cloudflare Web Analytics --><script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "7f6ed395033a43eea3885ad0943890c2"}'></script><!-- End Cloudflare Web Analytics -->
diff --git a/src/db/mod.rs b/src/db/mod.rs
index 9727f95a..c5bcf46c 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -1195,26 +1195,37 @@ async fn insert_message_core(
Ok(msg)
}
-/// Renames chat `chat`, now called `chat_name` (`team-<name>`), to `archived-team-<name>`, or
-/// `archived-team-<name>-2`, `-3`… when that is taken (ignoring case). No team answers to an
-/// `archived-` name, so it becomes an ordinary channel; its messages, lead and members stay.
-/// Returns the new name.
+/// Renames chat `chat`, now called `chat_name` (`team-<name>`), to [`archived_chat_name`].
+/// No team answers to an `archived-` name, so it becomes an ordinary channel; its messages, lead
+/// and members stay. Returns the new name.
async fn archive_team_chat(
tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>,
space: &SpaceId,
chat: &str,
chat_name: &str,
+) -> Result<String, DbError> {
+ let name = archived_chat_name(tx, space.as_str(), chat_name).await?;
+ sqlx::query("UPDATE channels SET name = ? WHERE id = ?").bind(&name).bind(chat).execute(&mut **tx).await?;
+ Ok(name)
+}
+
+/// The name [`archive_team_chat`] gives chat `chat_name` in `space` right now:
+/// `archived-<chat_name>`, or `archived-<chat_name>-2`, `-3`… when that is taken (ignoring case).
+/// Read-only, so the Undo preview can show the same name the Undo will use.
+pub(crate) async fn archived_chat_name(
+ conn: &mut sqlx::SqliteConnection,
+ space: &str,
+ chat_name: &str,
) -> Result<String, DbError> {
let base = format!("archived-{chat_name}");
for n in 1..1000 {
let candidate = if n == 1 { base.clone() } else { format!("{base}-{n}") };
let (taken,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM channels WHERE space_id = ? AND name = ? COLLATE NOCASE")
- .bind(space.as_str())
+ .bind(space)
.bind(&candidate)
- .fetch_one(&mut **tx)
+ .fetch_one(&mut *conn)
.await?;
if taken == 0 {
- sqlx::query("UPDATE channels SET name = ? WHERE id = ?").bind(&candidate).bind(chat).execute(&mut **tx).await?;
return Ok(candidate);
}
}
diff --git a/src/db/team_templates.rs b/src/db/team_templates.rs
index 81a998fb..5d645ab4 100644
--- a/src/db/team_templates.rs
+++ b/src/db/team_templates.rs
@@ -245,6 +245,10 @@ pub struct TemplateInfo {
pub blocked: Vec<Blocked>,
pub removes: Removes,
pub chat_messages: i64,
+ /// What Undo will rename the team chat to (`archived-team-<handle>`, with `-2`, `-3`… when
+ /// that is taken), when it keeps the chat because it has messages. `None` when Undo deletes
+ /// the chat or leaves it alone.
+ pub archived_chat: Option<String>,
pub also_in: Vec<AlsoIn>,
pub edited_skills: Vec<String>,
/// Needs (T5) the server can see are done. A `composer_prompt` need, such as Sales'
@@ -471,6 +475,17 @@ impl Database {
}
_ => 0,
};
+ // The same choice `undo_in` makes: a new team's chat with messages, still `team-…`.
+ let archived_chat = match (&c.created.channel_id, chat_messages > 0) {
+ (Some(ch), true) => {
+ let name: Option<(String,)> = sqlx::query_as("SELECT name FROM channels WHERE id = ?").bind(ch).fetch_optional(&mut *conn).await?;
+ match name {
+ Some((name,)) if name.starts_with("team-") => Some(super::archived_chat_name(&mut conn, &c.space_id, &name).await?),
+ _ => None,
+ }
+ }
+ _ => None,
+ };
let person_posted = match &c.created.channel_id {
Some(ch) => {
sqlx::query_as::<_, (i64,)>("SELECT COUNT(*) FROM messages WHERE channel_id = ? AND sender_role = 'user'")
@@ -507,6 +522,7 @@ impl Database {
blocked,
removes: Removes { bots, skills, routines, handle: handle.map(|(h,)| h) },
chat_messages,
+ archived_chat,
also_in,
edited_skills,
needs_done,
diff --git a/src/drivers/events.rs b/src/drivers/events.rs
index 7cf00658..af386c5c 100644
--- a/src/drivers/events.rs
+++ b/src/drivers/events.rs
@@ -352,6 +352,10 @@ pub enum RuntimeEvent {
space_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
space_name: Option<String>,
+ /// `spend_stopped` only: what the stop held was the person's own message, not a routine,
+ /// a mission or a Jira task, so Telegram may tell them to send it again.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ held_message: bool,
},
}
diff --git a/src/main.rs b/src/main.rs
index 5ebead64..828e53e6 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -89,6 +89,9 @@ pub enum Commands {
/// Leave out the QR code
#[arg(long)]
no_qr: bool,
+ /// Only the link and its QR code, indented (install.sh prints its own sentences around them)
+ #[arg(long, hide = true)]
+ bare: bool,
},
/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)
@@ -213,7 +216,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
} else {
config.data_dir.join("api-token").display().to_string()
};
- if let Err(e) = kwnt::server::signin::cli_link(&config, None, true).await {
+ if let Err(e) = kwnt::server::signin::cli_link(&config, None, true, false).await {
eprintln!("kwnt token: {e}");
eprintln!("The API token still works on the sign-in screen: it's {where_token} (`kwnt token --raw` prints it).");
std::process::exit(1);
@@ -221,8 +224,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!(" Prefer typing the token? It's {where_token} (`kwnt token --raw` prints it).");
}
}
- Some(Commands::SigninLink { url, no_qr }) => {
- if let Err(e) = kwnt::server::signin::cli_link(&config, url.as_deref(), !no_qr).await {
+ Some(Commands::SigninLink { url, no_qr, bare }) => {
+ if let Err(e) = kwnt::server::signin::cli_link(&config, url.as_deref(), !no_qr, bare).await {
eprintln!("kwnt signin-link: {e}");
std::process::exit(1);
}
diff --git a/src/profiles/login.rs b/src/profiles/login.rs
index af0b6d27..f61ebd9c 100644
--- a/src/profiles/login.rs
+++ b/src/profiles/login.rs
@@ -14,9 +14,16 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::process::ChildStdin;
use tokio::sync::Notify;
-/// A login nobody finishes is killed after this long.
+/// A login nobody finishes is killed after this long, unless the CLI says how long its code
+/// works (see [`cli_lifetime`]).
pub const LOGIN_TIMEOUT: Duration = Duration::from_secs(600);
+/// The longest code lifetime kwnt takes from a CLI's output.
+const MAX_CLI_LIFETIME: Duration = Duration::from_secs(30 * 60);
+
+/// How long past the code's own expiry kwnt waits for the CLI to give up by itself.
+const EXPIRY_GRACE: Duration = Duration::from_secs(10);
+
/// Hosts a sign-in link may point at. Anything else ends the login: kwnt never shows the user
/// a link a compromised or unexpected binary printed.
pub const LOGIN_HOSTS: &[&str] = &[
@@ -65,9 +72,20 @@ pub struct LoginView {
pub expires_at: chrono::DateTime<chrono::Utc>,
}
+impl LoginView {
+ /// Everything the user needs is known: the link, and the device code unless they paste one.
+ pub fn shows_everything(&self) -> bool {
+ self.url.is_some() && (self.needs_code || self.user_code.is_some())
+ }
+}
+
struct Flow {
view: Mutex<LoginView>,
home: PathBuf,
+ /// When the login started, for a lifetime the CLI prints ("expires in 15 minutes").
+ started: (tokio::time::Instant, chrono::DateTime<chrono::Utc>),
+ /// The CLI said the code expired, so its failing exit is an expiry.
+ said_expired: std::sync::atomic::AtomicBool,
stdin: tokio::sync::Mutex<Option<ChildStdin>>,
cancel: Notify,
}
@@ -176,6 +194,7 @@ impl LoginManager {
})?;
let timeout = self.timeout;
let flow_id = format!("login_{}", uuid::Uuid::new_v4().simple());
+ let started = (tokio::time::Instant::now(), chrono::Utc::now());
let flow = Arc::new(Flow {
view: Mutex::new(LoginView {
flow_id: flow_id.clone(),
@@ -186,9 +205,11 @@ impl LoginManager {
needs_code: engine == Engine::Claude,
code_sent: false,
error: None,
- expires_at: chrono::Utc::now() + chrono::Duration::from_std(timeout).unwrap(),
+ expires_at: started.1 + chrono::Duration::from_std(timeout).unwrap(),
}),
home: home.to_path_buf(),
+ started,
+ said_expired: Default::default(),
stdin: tokio::sync::Mutex::new(child.stdin.take()),
cancel: Notify::new(),
});
@@ -211,11 +232,13 @@ impl LoginManager {
let end = loop {
tokio::select! {
line = line_rx.recv(), if lines_open => match line {
- Some(line) => {
- if let Err(e) = flow.take_line(&line) {
- break (LoginStatus::Failed, Some(e));
- }
- }
+ Some(line) => match flow.take_line(&line) {
+ Err(e) => break (LoginStatus::Failed, Some(e)),
+ // The code's own lifetime: kwnt waits that long, plus a moment for
+ // the CLI to say it expired itself
+ Ok(Some(lifetime)) => deadline.as_mut().reset(flow.started.0 + lifetime + EXPIRY_GRACE),
+ Ok(None) => {}
+ },
None => lines_open = false,
},
status = child.wait() => {
@@ -225,6 +248,7 @@ impl LoginManager {
}
break match status {
Ok(s) if s.success() => (LoginStatus::Succeeded, None),
+ Ok(_) if flow.code_expired() => (LoginStatus::Expired, Some("sign-in timed out".into())),
Ok(s) => (LoginStatus::Failed, Some(format!("sign-in did not finish (exit {})", s.code().unwrap_or(-1)))),
Err(_) => (LoginStatus::Failed, Some("sign-in process failed".into())),
};
@@ -245,10 +269,11 @@ impl LoginManager {
on_success(finished);
}
});
- // Give the CLI a moment to print its link so the first response usually has it
+ // Give the CLI a moment to print its link (and device code) so the first response
+ // usually has them
for _ in 0..30 {
match self.get(&flow_id) {
- Some(view) if view.url.is_none() && view.status.is_active() => {}
+ Some(view) if !view.shows_everything() && view.status.is_active() => {}
Some(view) => return Ok(view),
None => break,
}
@@ -341,9 +366,14 @@ async fn read_lines<R: tokio::io::AsyncRead + Unpin>(
}
impl Flow {
- /// Picks the sign-in link and device code out of a line of CLI output.
- fn take_line(&self, raw: &str) -> Result<(), String> {
+ /// Picks the sign-in link, device code and the code's lifetime out of a line of CLI output.
+ /// `Ok(Some(lifetime))` when the line says how long the code works.
+ fn take_line(&self, raw: &str) -> Result<Option<Duration>, String> {
let line = strip_ansi(raw);
+ let lower = line.to_ascii_lowercase();
+ if lower.contains("expired") {
+ self.said_expired.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
let mut view = self.view.lock().unwrap();
if view.url.is_none() {
if let Some(url) = first_https_url(&line) {
@@ -353,14 +383,40 @@ impl Flow {
}
view.url = Some(url);
view.status = LoginStatus::Waiting;
- return Ok(());
+ return Ok(None);
}
}
+ let lifetime = cli_lifetime(&lower);
+ if let Some(d) = lifetime {
+ view.expires_at = self.started.1 + chrono::Duration::from_std(d).unwrap();
+ }
if view.user_code.is_none() && view.url.is_some() {
view.user_code = device_code(&line);
}
- Ok(())
+ Ok(lifetime)
}
+
+ /// The CLI said the code expired, or it is past the code's lifetime.
+ fn code_expired(&self) -> bool {
+ self.said_expired.load(std::sync::atomic::Ordering::Relaxed)
+ || self.view.lock().unwrap().expires_at <= chrono::Utc::now()
+ }
+}
+
+/// "expires in 15 minutes" (Codex) in a lowercased line: the code's lifetime, at most
+/// [`MAX_CLI_LIFETIME`].
+fn cli_lifetime(lower: &str) -> Option<Duration> {
+ let rest = &lower[lower.find("expires in ")? + "expires in ".len()..];
+ let mut words = rest.split_whitespace();
+ let n: u64 = words.next()?.parse().ok()?;
+ let unit = words.next()?.trim_end_matches(|c: char| !c.is_ascii_alphabetic());
+ let secs = match unit {
+ "second" | "seconds" => n,
+ "minute" | "minutes" | "min" | "mins" => n.checked_mul(60)?,
+ "hour" | "hours" => n.checked_mul(3600)?,
+ _ => return None,
+ };
+ (secs > 0).then(|| Duration::from_secs(secs).min(MAX_CLI_LIFETIME))
}
/// Removes terminal escape sequences (colors, cursor moves, OSC hyperlinks).
@@ -461,6 +517,18 @@ fn is_device_code(w: &str) -> bool {
mod tests {
use super::*;
+ #[test]
+ fn cli_lifetime_reads_the_codes_own_expiry() {
+ let line = strip_ansi("2. Enter this one-time code \u{1b}[90m(expires in 15 minutes)\u{1b}[0m").to_lowercase();
+ assert_eq!(cli_lifetime(&line), Some(Duration::from_secs(900)));
+ assert_eq!(cli_lifetime("the code expires in 90 seconds."), Some(Duration::from_secs(90)));
+ assert_eq!(cli_lifetime("expires in 1 hour"), Some(Duration::from_secs(3600).min(MAX_CLI_LIFETIME)));
+ assert_eq!(cli_lifetime("expires in 99999999 hours"), Some(MAX_CLI_LIFETIME));
+ for none in ["expires in 0 minutes", "expires in soon", "expires in 5 days", "waiting for authorization...", "expired"] {
+ assert_eq!(cli_lifetime(none), None, "{none}");
+ }
+ }
+
#[test]
fn login_url_allowlist() {
assert!(
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 66f9c3ac..209d8923 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -2,7 +2,7 @@ use futures::{SinkExt, StreamExt};
use super::credentials::CredentialStore;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
-use std::sync::atomic::{AtomicU64, Ordering};
+use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
@@ -353,6 +353,10 @@ pub enum BrowserError {
Timeout,
#[error("Browser is controlled by a person. Retry after control is returned.")]
HumanControl,
+ /// Take over from a live view while another of the person's live views has control (not a
+ /// bot finishing a step): retrying can't win until that view hands back.
+ #[error("You're controlling this browser in another window. Press Hand back there to take over here.")]
+ HeldByPerson,
/// The person's live view sent input without taking control, and nobody else has it.
#[error("Take control of the browser first.")]
NotInControl,
@@ -370,6 +374,25 @@ pub enum BrowserError {
SiteRule(super::site_guard::Refusal),
}
+/// A live view's control of the browser ([`BrowserController::take_control`]): the write lock,
+/// counted as a view's while it lives. The count goes down before the lock is let go.
+pub struct PersonLease {
+ views: Arc<AtomicUsize>,
+ _guard: OwnedRwLockWriteGuard<()>,
+}
+
+impl Drop for PersonLease {
+ fn drop(&mut self) {
+ self.views.fetch_sub(1, Ordering::SeqCst);
+ }
+}
+
+impl std::fmt::Debug for PersonLease {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("PersonLease")
+ }
+}
+
/// What a click aims at: a label to match, or a numbered ref from the last control list.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ClickTarget {
@@ -1014,6 +1037,9 @@ pub struct BrowserController {
/// Held while a human step (sign in, CAPTCHA) waits on the person: bot actions get
/// `HumanControl` and the person's live-view input goes through without taking control.
held_for_person: Arc<std::sync::Mutex<Option<OwnedRwLockWriteGuard<()>>>>,
+ /// How many [`PersonLease`]s live views hold (0 or 1): tells a takeover refused because the
+ /// person has the browser in another window from one refused because a bot is mid-step.
+ view_leases: Arc<AtomicUsize>,
/// Which mouse buttons live-view input holds down, and where, if any.
pointer_held: Arc<std::sync::Mutex<Option<HeldPointer>>>,
/// The page sizes open live views asked for. Async: a resize holds it while it applies, so
@@ -1087,6 +1113,7 @@ impl BrowserController {
browser_level: false,
control: Arc::new(RwLock::new(())),
held_for_person: Arc::default(),
+ view_leases: Arc::default(),
pointer_held: Arc::default(),
view_claims: Arc::default(),
cookie_jar: Arc::default(),
@@ -1122,8 +1149,17 @@ impl BrowserController {
ctrl
}
- pub async fn take_control(&self) -> Result<OwnedRwLockWriteGuard<()>, BrowserError> {
- self.control.clone().try_write_owned().map_err(|_| BrowserError::HumanControl)
+ /// The person's control for one live view. Refused with [`BrowserError::HeldByPerson`] while
+ /// another live view has it, and with [`BrowserError::HumanControl`] while a bot is mid-step.
+ pub async fn take_control(&self) -> Result<PersonLease, BrowserError> {
+ match self.control.clone().try_write_owned() {
+ Ok(guard) => {
+ self.view_leases.fetch_add(1, Ordering::SeqCst);
+ Ok(PersonLease { views: self.view_leases.clone(), _guard: guard })
+ }
+ Err(_) if self.view_leases.load(Ordering::SeqCst) > 0 => Err(BrowserError::HeldByPerson),
+ Err(_) => Err(BrowserError::HumanControl),
+ }
}
/// Locks the browser to the person until [`Self::release_person_hold`]. Waits briefly for a
diff --git a/src/sandbox/chrome_download.rs b/src/sandbox/chrome_download.rs
new file mode 100644
index 00000000..dcc3936f
--- /dev/null
+++ b/src/sandbox/chrome_download.rs
@@ -0,0 +1,501 @@
+//! The bots' private browser without Node (0.7.6, O5): when a bot first needs the local browser
+//! and this computer has no Chrome or Chromium, kwnt downloads Google's Chrome for Testing build
+//! into its own cache folder (`~/Library/Caches/kwant/chrome` on a Mac, `~/.cache/kwant/chrome`
+//! on Linux) and uses that. No admin rights, no Homebrew, no Node.
+//!
+//! It is silent unless it fails. Then [`FAILED_LINE`] is what the person sees, with "Try again"
+//! ([`ChromeSetup::retry`]).
+//!
+//! Chrome for Testing publishes no checksums or signatures, so the download is taken only over
+//! HTTPS from Google's own storage (`storage.googleapis.com/chrome-for-testing-public/`, as listed
+//! in Google's JSON), checked for a complete body and the expected browser inside, and has to
+//! start (`--version`) before it is used.
+//!
+//! There's no build for Linux on ARM, and a Linux that blocks the sandbox of a browser in the
+//! home folder (Ubuntu 23.10+) couldn't start one, so neither downloads: they keep the existing
+//! "install Chromium" advice.
+use std::path::{Path, PathBuf};
+use std::process::Stdio;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use serde::Serialize;
+
+/// Google's list of the current Chrome for Testing builds and their downloads.
+pub const CFT_JSON: &str =
+ "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json";
+/// Where Google serves the builds; a download anywhere else is refused.
+pub const CFT_STORAGE: &str = "https://storage.googleapis.com/chrome-for-testing-public/";
+/// What the person sees when the browser couldn't be set up (design.md §8).
+pub const FAILED_LINE: &str = "The bots' browser couldn't be set up. Bots can still answer; web pages won't open.";
+/// After a failure, the next bot that needs the browser tries again only after this long (or at
+/// once on "Try again"), so a broken network doesn't restart a large download on every call.
+pub const RETRY_AFTER: Duration = Duration::from_secs(10 * 60);
+/// A build is about 150–200 MB; anything past this is not a browser.
+pub const MAX_BYTES: u64 = 1 << 30;
+
+/// The Chrome for Testing platform for this OS and CPU, or `None` where Google has no build
+/// (Linux on ARM) or kwnt doesn't download one (Windows).
+pub fn cft_platform(os: &str, arch: &str) -> Option<&'static str> {
+ match (os, arch) {
+ ("macos", "aarch64") => Some("mac-arm64"),
+ ("macos", "x86_64") => Some("mac-x64"),
+ ("linux", "x86_64") => Some("linux64"),
+ _ => None,
+ }
+}
+
+/// The browser inside a build's zip (and inside its install folder).
+pub fn binary_in(platform: &str) -> PathBuf {
+ let app = "Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing";
+ match platform {
+ "mac-arm64" | "mac-x64" => PathBuf::from(format!("chrome-{platform}")).join(app),
+ _ => PathBuf::from(format!("chrome-{platform}")).join("chrome"),
+ }
+}
+
+/// kwnt's own browser cache under `home`: `Library/Caches/kwant/chrome` on a Mac,
+/// `.cache/kwant/chrome` elsewhere.
+pub fn cache_root(os: &str, home: &Path) -> PathBuf {
+ if os == "macos" {
+ home.join("Library/Caches/kwant/chrome")
+ } else {
+ home.join(".cache/kwant/chrome")
+ }
+}
+
+/// The newest browser kwnt downloaded under `home`, if any. Builds sit in
+/// `<cache_root>/<version>-<platform>/`.
+pub fn downloaded_chrome(os: &str, home: &Path) -> Option<PathBuf> {
+ newest_in(&cache_root(os, home))
+}
+
+fn newest_in(root: &Path) -> Option<PathBuf> {
+ let mut builds: Vec<(Vec<u32>, PathBuf)> = std::fs::read_dir(root)
+ .ok()?
+ .flatten()
+ .filter_map(|e| {
+ let name = e.file_name().to_string_lossy().to_string();
+ let (version, platform) = name.split_once('-')?;
+ let key: Vec<u32> = version.split('.').map(|n| n.parse().ok()).collect::<Option<_>>()?;
+ let bin = e.path().join(binary_in(platform));
+ bin.is_file().then_some((key, bin))
+ })
+ .collect();
+ builds.sort_by(|a, b| b.0.cmp(&a.0));
+ builds.into_iter().next().map(|(_, bin)| bin)
+}
+
+/// Where the setup stands, for the UI. The line shows only for `failed`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum SetupState {
+ /// Nothing has needed it yet (or Chrome is installed).
+ Idle,
+ /// Downloading or checking a build.
+ Downloading,
+ /// A build kwnt downloaded is in place.
+ Ready,
+ /// The last attempt failed: show [`FAILED_LINE`] and "Try again".
+ Failed,
+ /// No build for this computer (Linux on ARM, Windows) or its sandbox is blocked: the
+ /// existing "install Chrome" advice applies.
+ Unavailable,
+}
+
+/// [`ChromeSetup::view`]: what `GET /api/settings/computer` shows as `browser_setup`.
+#[derive(Debug, Clone, Serialize)]
+pub struct SetupView {
+ pub state: SetupState,
+ /// [`FAILED_LINE`] when `failed`.
+ pub error: Option<String>,
+ /// Why it failed, in a few words (no paths or tokens), for a details line or logs.
+ pub detail: Option<String>,
+ /// The Chrome for Testing version in use or being fetched.
+ pub version: Option<String>,
+}
+
+struct Status {
+ state: SetupState,
+ detail: Option<String>,
+ version: Option<String>,
+ failed_at: Option<Instant>,
+}
+
+/// The private browser download for one cache folder. One download runs at a time; every bot
+/// that needs the browser meanwhile waits for it.
+pub struct ChromeSetup {
+ /// Google's JSON (or a test server's).
+ json_url: String,
+ /// Downloads must start with this.
+ storage: String,
+ root: PathBuf,
+ platform: Option<&'static str>,
+ status: Mutex<Status>,
+ run: tokio::sync::Mutex<()>,
+ max_bytes: u64,
+}
+
+impl ChromeSetup {
+ pub fn new(root: PathBuf, platform: Option<&'static str>) -> Self {
+ Self {
+ json_url: CFT_JSON.into(),
+ storage: CFT_STORAGE.into(),
+ root,
+ platform,
+ status: Mutex::new(Status { state: SetupState::Idle, detail: None, version: None, failed_at: None }),
+ run: tokio::sync::Mutex::new(()),
+ max_bytes: MAX_BYTES,
+ }
+ }
+
+ /// For this computer: `$HOME`'s cache folder and this OS and CPU. Linux whose sandbox is
+ /// blocked, and Docker, get no download.
+ pub fn system() -> Self {
+ let home = std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default();
+ let os = std::env::consts::OS;
+ let platform = cft_platform(os, std::env::consts::ARCH).filter(|_| {
+ !super::computer::chrome_sandbox_blocked()
+ && crate::doctor::Platform::detect() != crate::doctor::Platform::Docker
+ && !home.as_os_str().is_empty()
+ });
+ let setup = Self::new(cache_root(os, &home), platform);
+ #[cfg(feature = "test-seams")]
+ if let Ok(url) = std::env::var("KWNT_CHROME_FOR_TESTING_URL") {
+ // A fake list (live QA): its downloads must sit in the list's own folder
+ let storage = url.rfind('/').map(|i| url[..=i].to_string()).unwrap_or_else(|| url.clone());
+ return setup.source(&url, &storage);
+ }
+ setup
+ }
+
+ /// Takes the build list from `json_url` and accepts downloads under `storage` (tests).
+ pub fn source(mut self, json_url: &str, storage: &str) -> Self {
+ self.json_url = json_url.into();
+ self.storage = storage.into();
+ self
+ }
+
+ pub fn max_bytes(mut self, max: u64) -> Self {
+ self.max_bytes = max;
+ self
+ }
+
+ /// Whether this computer can get a browser this way.
+ pub fn available(&self) -> bool {
+ self.platform.is_some()
+ }
+
+ /// The browser downloaded earlier, if it's in place.
+ pub fn installed(&self) -> Option<PathBuf> {
+ self.platform?;
+ newest_in(&self.root)
+ }
+
+ pub fn view(&self) -> SetupView {
+ let s = self.status.lock().unwrap();
+ let state = match (&s.state, self.platform) {
+ (_, None) => SetupState::Unavailable,
+ (SetupState::Idle, _) if self.installed().is_some() => SetupState::Ready,
+ (state, _) => state.clone(),
+ };
+ SetupView {
+ error: (state == SetupState::Failed).then(|| FAILED_LINE.to_string()),
+ detail: if state == SetupState::Failed { s.detail.clone() } else { None },
+ version: s.version.clone(),
+ state,
+ }
+ }
+
+ fn set(&self, state: SetupState, detail: Option<String>) {
+ let mut s = self.status.lock().unwrap();
+ s.failed_at = (state == SetupState::Failed).then(Instant::now);
+ s.state = state;
+ s.detail = detail;
+ }
+
+ /// The private browser, downloading it first if it isn't there. Several callers share one
+ /// download. After a failure, callers get the failure at once until "Try again" or
+ /// [`RETRY_AFTER`].
+ pub async fn ensure(&self) -> Result<PathBuf, String> {
+ let Some(platform) = self.platform else {
+ return Err("There's no private browser download for this computer.".into());
+ };
+ if let Some(bin) = self.installed() {
+ return Ok(bin);
+ }
+ let _one = self.run.lock().await;
+ if let Some(bin) = self.installed() {
+ self.set(SetupState::Ready, None);
+ return Ok(bin);
+ }
+ {
+ let s = self.status.lock().unwrap();
+ if s.state == SetupState::Failed && s.failed_at.is_some_and(|t| t.elapsed() < RETRY_AFTER) {
+ return Err(failed_message(s.detail.as_deref()));
+ }
+ }
+ self.set(SetupState::Downloading, None);
+ match self.download(platform).await {
+ Ok(bin) => {
+ self.set(SetupState::Ready, None);
+ Ok(bin)
+ }
+ Err(why) => {
+ tracing::warn!(reason = %why, "the bots' private browser couldn't be set up");
+ self.set(SetupState::Failed, Some(why.clone()));
+ Err(failed_message(Some(&why)))
+ }
+ }
+ }
+
+ /// "Try again": forgets the last failure and starts the download in the background.
+ pub fn retry(self: &std::sync::Arc<Self>) {
+ {
+ let mut s = self.status.lock().unwrap();
+ if s.state == SetupState::Failed {
+ s.failed_at = None;
+ }
+ }
+ if self.platform.is_none() || self.installed().is_some() {
+ return;
+ }
+ let me = self.clone();
+ tokio::spawn(async move {
+ let _ = me.ensure().await;
+ });
+ }
+
+ async fn download(&self, platform: &'static str) -> Result<PathBuf, String> {
+ use futures::StreamExt;
+ use tokio::io::AsyncWriteExt;
+
+ // A download that starts on Google's storage may only be redirected within it: the prefix
+ // check below would mean nothing if a hop could take the zip from anywhere. A refused hop
+ // comes back as the 3xx itself and fails the download. The list keeps ordinary redirects.
+ let storage = self.storage.clone();
+ let redirects = reqwest::redirect::Policy::custom(move |hop| {
+ let from_storage = hop.previous().first().is_some_and(|u| u.as_str().starts_with(&storage));
+ if from_storage && !hop.url().as_str().starts_with(&storage) {
+ hop.stop()
+ } else if hop.previous().len() > 10 {
+ hop.error("too many redirects")
+ } else {
+ hop.follow()
+ }
+ });
+ let client = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(30))
+ .redirect(redirects)
+ .user_agent(concat!("kwnt/", env!("CARGO_PKG_VERSION")))
+ .build()
+ .map_err(|e| e.to_string())?;
+
+ // Which build: the Stable channel's download for this platform
+ let list: serde_json::Value = async {
+ let r = client
+ .get(&self.json_url)
+ .timeout(Duration::from_secs(60))
+ .send()
+ .await
+ .map_err(|_| "couldn't reach Google's Chrome for Testing list (offline?)".to_string())?;
+ if !r.status().is_success() {
+ return Err(format!("Google's Chrome for Testing list answered {}", r.status()));
+ }
+ r.json().await.map_err(|_| "Google's Chrome for Testing list couldn't be read".to_string())
+ }
+ .await?;
+ let stable = &list["channels"]["Stable"];
+ let version = stable["version"]
+ .as_str()
+ .filter(|v| !v.is_empty() && v.len() < 32 && v.split('.').all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())))
+ .ok_or("Google's Chrome for Testing list has no Stable version")?
+ .to_string();
+ let url = stable["downloads"]["chrome"]
+ .as_array()
+ .and_then(|all| all.iter().find(|d| d["platform"] == platform))
+ .and_then(|d| d["url"].as_str())
+ .ok_or_else(|| format!("Chrome for Testing {version} has no build for {platform}"))?
+ .to_string();
+ if !url.starts_with(&self.storage) || url.contains("..") {
+ return Err(format!("Chrome for Testing {version} points somewhere other than Google's storage, so it wasn't downloaded"));
+ }
+ self.status.lock().unwrap().version = Some(version.clone());
+ tracing::info!(version = %version, platform, "downloading the bots' private browser (Chrome for Testing)");
+
+ std::fs::create_dir_all(&self.root).map_err(|_| "couldn't make kwant's browser cache folder".to_string())?;
+ let zip = self.root.join(format!(".download.{}.zip", std::process::id()));
+ let staging = self.root.join(format!(".staging.{version}-{platform}.{}", std::process::id()));
+ struct Cleanup(PathBuf, PathBuf);
+ impl Drop for Cleanup {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ let _ = std::fs::remove_dir_all(&self.1);
+ }
+ }
+ let _cleanup = Cleanup(zip.clone(), staging.clone());
+
+ let resp = client
+ .get(&url)
+ .send()
+ .await
+ .map_err(|_| "couldn't reach Google's storage to download Chrome for Testing (offline?)".to_string())?;
+ if resp.status().is_redirection() {
+ return Err("the Chrome for Testing download was redirected away from Google's storage, so it wasn't downloaded".into());
+ }
+ if !resp.status().is_success() {
+ return Err(format!("the Chrome for Testing download answered {}", resp.status()));
+ }
+ let total = resp.content_length().filter(|n| *n > 0);
+ if total.is_some_and(|n| n > self.max_bytes) {
+ return Err(format!("the Chrome for Testing download is larger than {} MB", self.max_bytes >> 20));
+ }
+ let mut file = tokio::fs::File::create(&zip).await.map_err(|_| "couldn't write to kwant's browser cache folder".to_string())?;
+ let (mut got, mut next_note) = (0u64, 0u64);
+ let mut body = resp.bytes_stream();
+ loop {
+ let chunk = match tokio::time::timeout(Duration::from_secs(120), body.next()).await {
+ Err(_) => return Err("the Chrome for Testing download stalled".into()),
+ Ok(None) => break,
+ Ok(Some(c)) => c.map_err(|_| "the Chrome for Testing download broke off".to_string())?,
+ };
+ got += chunk.len() as u64;
+ if got > self.max_bytes {
+ return Err(format!("the Chrome for Testing download is larger than {} MB", self.max_bytes >> 20));
+ }
+ file.write_all(&chunk).await.map_err(|_| "couldn't write to kwant's browser cache folder (disk full?)".to_string())?;
+ if got >= next_note {
+ tracing::info!(mb = got >> 20, of_mb = total.map(|t| t >> 20), "downloading the bots' private browser");
+ next_note = got + (25 << 20);
+ }
+ }
+ file.flush().await.map_err(|e| e.to_string())?;
+ drop(file);
+ if total.is_some_and(|t| t != got) {
+ return Err("the Chrome for Testing download ended early".into());
+ }
+
+ // Unpack beside earlier builds; only a complete, starting build is moved into place
+ let inner = binary_in(platform);
+ let (zip_path, staging_dir, want) = (zip.clone(), staging.clone(), inner.clone());
+ tokio::task::spawn_blocking(move || -> Result<(), String> {
+ let file = std::fs::File::open(&zip_path).map_err(|_| "couldn't read the download".to_string())?;
+ let mut archive = zip::ZipArchive::new(file).map_err(|_| "the Chrome for Testing download isn't a readable zip".to_string())?;
+ let wanted = want.to_string_lossy().replace('\\', "/");
+ if archive.index_for_name(&wanted).is_none() {
+ return Err("the Chrome for Testing download has no browser inside".into());
+ }
+ let _ = std::fs::remove_dir_all(&staging_dir);
+ std::fs::create_dir_all(&staging_dir).map_err(|_| "couldn't make kwant's browser cache folder".to_string())?;
+ archive.extract(&staging_dir).map_err(|_| "the Chrome for Testing download couldn't be unpacked".to_string())
+ })
+ .await
+ .map_err(|_| "unpacking the browser stopped".to_string())??;
+ let bin = staging.join(&inner);
+ if !bin.is_file() {
+ return Err("the Chrome for Testing download has no browser inside".into());
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755));
+ }
+ let said = starts(&bin).await?;
+ tracing::info!(version = %said, "the bots' private browser starts");
+
+ let dest = self.root.join(format!("{version}-{platform}"));
+ if dest.exists() {
+ std::fs::remove_dir_all(&dest).map_err(|_| "couldn't replace an older private browser".to_string())?;
+ }
+ std::fs::rename(&staging, &dest).map_err(|_| "couldn't move the browser into place".to_string())?;
+ Ok(dest.join(inner))
+ }
+}
+
+fn failed_message(detail: Option<&str>) -> String {
+ match detail {
+ Some(d) => format!("{FAILED_LINE} ({d})"),
+ None => FAILED_LINE.into(),
+ }
+}
+
+/// Runs `bin --version` (retrying a moment while another process still holds the new file open),
+/// and gives its first line. A build that can't start (missing system libraries) fails here.
+async fn starts(bin: &Path) -> Result<String, String> {
+ let mut tries = 0;
+ let out = loop {
+ let run = tokio::process::Command::new(bin)
+ .arg("--version")
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true)
+ .output();
+ match tokio::time::timeout(Duration::from_secs(60), run).await {
+ Err(_) => return Err("the downloaded browser didn't answer --version".into()),
+ // ETXTBSY: a process forked elsewhere still has the just-written file open
+ Ok(Err(e)) if e.raw_os_error() == Some(26) && tries < 20 => {
+ tries += 1;
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ Ok(Err(_)) => return Err("the downloaded browser couldn't be started".into()),
+ Ok(Ok(out)) => break out,
+ }
+ };
+ let said = String::from_utf8_lossy(&out.stdout).lines().next().unwrap_or_default().trim().to_string();
+ if !out.status.success() || !said.contains("Chrom") {
+ return Err("the downloaded browser doesn't start here (missing system libraries?)".into());
+ }
+ Ok(said)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn platforms_with_a_build() {
+ assert_eq!(cft_platform("macos", "aarch64"), Some("mac-arm64"));
+ assert_eq!(cft_platform("macos", "x86_64"), Some("mac-x64"));
+ assert_eq!(cft_platform("linux", "x86_64"), Some("linux64"));
+ // Google has no Linux ARM build; Windows isn't downloaded
+ assert_eq!(cft_platform("linux", "aarch64"), None);
+ assert_eq!(cft_platform("windows", "x86_64"), None);
+ }
+
+ #[test]
+ fn where_builds_go_and_which_one_is_used() {
+ let tmp = tempfile::tempdir().unwrap();
+ let home = tmp.path();
+ assert_eq!(cache_root("macos", home), home.join("Library/Caches/kwant/chrome"));
+ assert_eq!(cache_root("linux", home), home.join(".cache/kwant/chrome"));
+ assert_eq!(
+ binary_in("mac-arm64"),
+ PathBuf::from("chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing")
+ );
+ assert_eq!(downloaded_chrome("linux", home), None);
+ let root = cache_root("linux", home);
+ for v in ["9.0.1.2", "131.0.6778.85", "131.0.6778.9"] {
+ let bin = root.join(format!("{v}-linux64")).join(binary_in("linux64"));
+ std::fs::create_dir_all(bin.parent().unwrap()).unwrap();
+ std::fs::write(&bin, "").unwrap();
+ }
+ // a half-unpacked or foreign folder is ignored
+ std::fs::create_dir_all(root.join(".staging.999.0.0.0-linux64.1/chrome-linux64")).unwrap();
+ std::fs::create_dir_all(root.join("999.0.0.0-linux64")).unwrap();
+ assert_eq!(
+ downloaded_chrome("linux", home),
+ Some(root.join("131.0.6778.85-linux64").join(binary_in("linux64")))
+ );
+ }
+
+ #[test]
+ fn no_build_means_unavailable_and_no_line() {
+ let tmp = tempfile::tempdir().unwrap();
+ let setup = ChromeSetup::new(tmp.path().to_path_buf(), None);
+ let v = setup.view();
+ assert_eq!(v.state, SetupState::Unavailable);
+ assert!(v.error.is_none());
+ assert!(!setup.available());
+ }
+}
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index cdbd78c1..6ab32446 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -93,7 +93,8 @@ const CHROME_COMMANDS: [&str; 5] = [
];
/// Finds the browser local mode launches: the override if it names a file, else the macOS app
-/// bundles (in `/Applications` and `~/Applications`), else a Chrome/Chromium command on `path`.
+/// bundles (in `/Applications` and `~/Applications`), else a Chrome/Chromium command on `path`,
+/// else a Playwright Chromium, else the Chrome for Testing kwnt downloaded itself (O5).
pub fn find_chrome(
override_path: Option<&str>,
os: &str,
@@ -125,7 +126,9 @@ pub fn find_chrome(
.find(|candidate| candidate.is_file())
})
});
- on_path.or_else(|| playwright_chromium(os, home?))
+ on_path
+ .or_else(|| playwright_chromium(os, home?))
+ .or_else(|| super::chrome_download::downloaded_chrome(os, home?))
}
/// The newest Chromium Playwright downloaded into the person's cache (`kwnt setup` puts one there
@@ -194,8 +197,8 @@ pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool, platfor
})
}
-/// The local Chrome this process would launch, from the real environment. A Playwright Chromium
-/// counts only where its sandbox can start (see [`chrome_sandbox_blocked`]).
+/// The local Chrome this process would launch, from the real environment. A Playwright Chromium,
+/// or one kwnt downloaded, counts only where its sandbox can start (see [`chrome_sandbox_blocked`]).
pub fn local_chrome_path() -> Option<PathBuf> {
let home = std::env::var_os("HOME").map(PathBuf::from);
let found = find_chrome(
@@ -204,8 +207,11 @@ pub fn local_chrome_path() -> Option<PathBuf> {
home.as_deref(),
std::env::var("PATH").ok().as_deref(),
)?;
- let playwright = home.is_some_and(|h| found.starts_with(h.join(".cache").join("ms-playwright")));
- (!(playwright && chrome_sandbox_blocked())).then_some(found)
+ let in_home_cache = home.is_some_and(|h| {
+ found.starts_with(h.join(".cache").join("ms-playwright"))
+ || found.starts_with(super::chrome_download::cache_root(std::env::consts::OS, &h))
+ });
+ (!(in_home_cache && chrome_sandbox_blocked())).then_some(found)
}
/// Linux blocks the unprivileged user namespaces Chrome's sandbox needs (Ubuntu 23.10+ AppArmor,
@@ -218,9 +224,14 @@ pub fn chrome_sandbox_blocked() -> bool {
|| read("/proc/sys/kernel/unprivileged_userns_clone").as_deref() == Some("0"))
}
-/// [`local_unavailable_reason`] for this process's environment.
+/// [`local_unavailable_reason`] for this process's environment. Where kwnt can download its own
+/// browser (O5), a missing Chrome is no reason: the first bot that needs one gets it.
pub fn local_reason() -> Option<String> {
- local_unavailable_reason(local_chrome_path().as_deref(), Platform::detect())
+ let chrome = local_chrome_path();
+ if chrome.is_none() && super::chrome_download::ChromeSetup::system().available() {
+ return None;
+ }
+ local_unavailable_reason(chrome.as_deref(), Platform::detect())
}
/// [`window_unavailable_reason`] for this process's environment.
@@ -628,7 +639,8 @@ where
/// Starts the kwant Chrome on `profile`, detached, so it outlives a switch or a kwant restart.
/// Only [`ensure_local_chrome`] calls this, once no Chrome holds the profile.
fn launch_local_chrome(profile: &Path, headless: bool) -> Result<(), String> {
- let chrome = local_chrome_path().ok_or_else(|| local_reason().unwrap_or_default())?;
+ let chrome = local_chrome_path()
+ .ok_or_else(|| local_reason().unwrap_or_else(|| "No Chrome or Chromium was found.".into()))?;
if !headless {
if let Some(reason) = window_reason() {
return Err(reason);
diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs
index 41564035..28679c0f 100644
--- a/src/sandbox/mod.rs
+++ b/src/sandbox/mod.rs
@@ -2,6 +2,7 @@ pub mod app_links;
pub mod bitwarden;
pub mod browser;
pub mod browser_history;
+pub mod chrome_download;
pub mod computer;
pub mod credentials;
pub mod manager;
diff --git a/src/sandbox/service.rs b/src/sandbox/service.rs
index cbde4093..0fbbfa7b 100644
--- a/src/sandbox/service.rs
+++ b/src/sandbox/service.rs
@@ -1,6 +1,7 @@
//! One browser service per installation; isolated CDP contexts per bot/team.
//! The private CDP endpoint is used only by the server, never by the web client.
use super::browser::{BrowserController, BrowserError};
+use super::chrome_download::{self, ChromeSetup};
use super::computer::{self, ComputerMode};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -35,6 +36,8 @@ pub struct BrowserService {
last_error: std::sync::Mutex<Option<String>>,
/// When a bot last used the browser (see [`Self::note_use`]).
last_use: std::sync::Mutex<Option<std::time::SystemTime>>,
+ /// Local mode without Chrome: the private browser kwnt downloads on first use (O5).
+ chrome_setup: std::sync::Arc<ChromeSetup>,
}
struct ServiceState {
@@ -50,9 +53,32 @@ impl BrowserService {
root, endpoint, mode: std::sync::RwLock::new(mode),
local_window: std::sync::atomic::AtomicBool::new(false), state: Mutex::new(None),
last_error: std::sync::Mutex::new(None), last_use: std::sync::Mutex::new(None),
+ chrome_setup: std::sync::Arc::new(ChromeSetup::system()),
}
}
+ /// The same service with its private browser downloaded through `setup` (tests).
+ pub fn with_chrome_setup(mut self, setup: ChromeSetup) -> Self {
+ self.chrome_setup = std::sync::Arc::new(setup);
+ self
+ }
+
+ /// The private browser download (O5): its state for the UI, and "Try again".
+ pub fn chrome_setup(&self) -> &std::sync::Arc<ChromeSetup> { &self.chrome_setup }
+
+ /// Local mode with no Chrome on this computer: downloads the private browser first, outside
+ /// the connection lock so status and frames don't wait for a download.
+ async fn ensure_private_browser(&self) -> Result<(), BrowserError> {
+ if self.mode() != ComputerMode::Local || !self.chrome_setup.available() {
+ return Ok(());
+ }
+ let found = tokio::task::spawn_blocking(computer::local_chrome_path).await.ok().flatten();
+ if found.is_none() {
+ self.chrome_setup.ensure().await.map_err(BrowserError::Http)?;
+ }
+ Ok(())
+ }
+
pub fn mode(&self) -> ComputerMode {
*self.mode.read().unwrap_or_else(|e| e.into_inner())
}
@@ -344,13 +370,17 @@ impl BrowserService {
}
let last = self.last_error.lock().unwrap_or_else(|e| e.into_inner()).clone();
match last {
+ Some(reason) if reason.starts_with(chrome_download::FAILED_LINE) => reason,
Some(reason) => format!("The bot browser could not start kwant's Chrome on this computer: {reason}"),
None => "The bot browser could not start kwant's Chrome on this computer. Restart the browser and try again.".into(),
}
}
pub async fn session(&self, id: &str, workspace: &Path) -> Result<BrowserController, BrowserError> {
- let result = self.open_session(id, workspace).await;
+ let result = match self.ensure_private_browser().await {
+ Ok(()) => self.open_session(id, workspace).await,
+ Err(e) => Err(e),
+ };
*self.last_error.lock().unwrap_or_else(|e| e.into_inner()) = result.as_ref().err().map(|e| match e {
// the local start's own words, without the CDP prefix
BrowserError::Http(reason) => reason.clone(),
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 797ece5c..28fa6a07 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -243,6 +243,22 @@ pub fn one_time_notice(link: &str, qr: bool) -> Vec<String> {
lines
}
+/// The link and its QR code alone, indented, for install.sh (`kwnt signin-link --bare`), which says
+/// the rest in its own words (Mira's S1 lines): no "works once" or "Used or expired?" line here.
+pub fn bare_notice(link: &str, qr: bool) -> Vec<String> {
+ let mut lines = vec![format!(" {link}")];
+ if link.contains(THIS_HOST) {
+ lines.push(format!(" Replace {THIS_HOST} with this server's address. Set KWNT_ALLOWED_ORIGINS to your HTTPS address for a ready link and a QR code."));
+ } else if qr {
+ let code = signin::qr_lines(link);
+ if !code.is_empty() {
+ lines.push(String::new());
+ lines.extend(code.into_iter().map(|l| format!(" {l}")));
+ }
+ }
+ lines
+}
+
/// Stands in for the server's address when kwnt listens on every address.
pub const THIS_HOST: &str = "<this-host>";
@@ -333,6 +349,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "documents", ..] => true,
// Setup installs software on this machine and shows what is signed in
["", "api", "setup", ..] => true,
+ // Signing the machine's own AI accounts in or out (0.7.6: Claude, ChatGPT, Grok)
+ ["", "api", "engines", _, "login", ..] | ["", "api", "engines", _, "logout"] => true,
// Sign-in links, device approvals and sessions: who else may sign in as the person
["", "api", "signin", ..] => true,
// Web Push: where the person's notifications go
@@ -895,6 +913,12 @@ mod tests {
fn person_only_routes() {
let (get, post, put, del) = (Method::GET, Method::POST, Method::PUT, Method::DELETE);
assert!(person_only(&get, "/api/sandbox/t1/passwords"));
+ assert!(person_only(&post, "/api/engines/codex/login"));
+ assert!(person_only(&get, "/api/engines/grok/login/login_1"));
+ assert!(person_only(&post, "/api/engines/claude/login/login_1/code"));
+ assert!(person_only(&post, "/api/engines/claude/logout"));
+ assert!(!person_only(&get, "/api/engines"));
+ assert!(!person_only(&post, "/api/engines/recheck"));
assert!(person_only(&post, "/api/sandbox/t1/passwords/c1/reveal"));
assert!(person_only(&del, "/api/sandbox/t1/passwords/c1"));
assert!(person_only(&post, "/api/sandbox/t1/interact"));
@@ -1101,6 +1125,16 @@ mod tests {
assert!(real.iter().any(|l| l.contains('█')), "QR code");
assert!(real.last().unwrap().contains("kwnt signin-link"));
assert!(!one_time_notice("https://kwant.example.com/#kwnt_token=kl1.abc", false).iter().any(|l| l.contains('█')));
+ // install.sh's bare form: the link (indented), then the QR code, and none of the notice's sentences
+ let bare = bare_notice("https://kwant.example.com/#kwnt_token=kl1.abc", true);
+ assert_eq!(bare[0], " https://kwant.example.com/#kwnt_token=kl1.abc");
+ assert!(bare.iter().any(|l| l.contains('█')), "QR code");
+ assert!(bare.iter().skip(1).all(|l| l.is_empty() || l.starts_with(" ")), "{bare:?}");
+ assert!(!bare.iter().any(|l| l.contains("works once") || l.contains("signin-link")), "{bare:?}");
+ let bare_placeholder = bare_notice(&one_time_link("0.0.0.0", 8799, None, code), true);
+ assert!(bare_placeholder.iter().any(|l| l.contains("KWNT_ALLOWED_ORIGINS")));
+ assert!(!bare_placeholder.iter().any(|l| l.contains('█')));
+ assert_eq!(bare_notice("https://kwant.example.com/#kwnt_token=kl1.abc", false).len(), 1);
// The API token itself is never printed at startup any more
assert!(!real.iter().chain(&placeholder).any(|l| l.contains("kwnt token")));
assert_eq!(token_command_link("0.0.0.0", 8799, "tok"), "http://<this-host>:8799/#kwnt_token=tok");
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index 4e34ec3f..19db015b 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -9,14 +9,14 @@ use super::browser_input::{self as bi, KeyEvent, KeyKind, MouseButton, RateLimit
use super::{routes::get_or_create_browser_controller, AppState};
use super::show_once::{capture as recorder, stage::{Act, StageRecorder}};
use crate::sandbox::app_links::{self, AppLinkWatch, Verdict};
-use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
+use crate::sandbox::browser::{web_address, BrowserController, BrowserError, HeldPointer, PersonLease, ViewClaim, ViewRelease, FOCUSED_EDITABLE_JS, MOUSE_BUTTON_BITS};
use crate::sandbox::browser_history::HistoryDirection;
use axum::{extract::{Path, State, WebSocketUpgrade, ws::{Message, WebSocket}}, http::{HeaderMap, StatusCode}, response::Response};
use futures::{SinkExt, StreamExt};
use serde::Deserialize;
use serde_json::{json, Value};
use std::{collections::HashMap, sync::{Arc, atomic::{AtomicBool, AtomicU64, Ordering}}, time::Duration};
-use tokio::{sync::{mpsc, oneshot, OwnedRwLockWriteGuard}, task::JoinHandle, time::{timeout, Instant}};
+use tokio::{sync::{mpsc, oneshot}, task::JoinHandle, time::{timeout, Instant}};
use tokio_tungstenite::tungstenite::Message as CdpMessage;
/// The viewport the screencast starts at when the controller has none saved.
@@ -439,6 +439,18 @@ fn navigated_to(method: &str, params: &Value) -> Option<String> {
Some(format!("{url}{}", params["frame"]["urlFragment"].as_str().unwrap_or_default()))
}
+/// What a live view hears when Take over is refused: `code` is `held_by_person` while another of
+/// the person's views has control (retrying can't win until it hands back) and `bot_busy` while
+/// a bot is mid-step (a retry soon can). `error` is the text, as before.
+fn takeover_refused(error: &BrowserError) -> Value {
+ let code = match error {
+ BrowserError::HeldByPerson => "held_by_person",
+ BrowserError::HumanControl => "bot_busy",
+ _ => "failed",
+ };
+ json!({"type":"error","error":error.to_string(),"code":code})
+}
+
/// The error for input from a live view that has not taken control.
fn not_in_control(someone_has_control: bool) -> BrowserError {
if someone_has_control { BrowserError::HumanControl } else { BrowserError::NotInControl }
@@ -615,12 +627,14 @@ impl Worker {
let address = web_address(&url)?;
let parsed = reqwest::Url::parse(&address).map_err(|e| BrowserError::Protocol(e.to_string()))?;
if !matches!(parsed.scheme(), "http"|"https") { return Err(protocol("Use an HTTP or HTTPS URL")); }
+ self.commit_recorder().await;
self.ctrl.navigate_unlocked(&address).await?;
refresh_location(&self.cdp, &self.ctrl, &self.shared, &self.client);
let _ = self.client.send(ack(id, json!({})));
}
BrowserInput::History { direction } => {
self.close_select();
+ self.commit_recorder().await;
self.ctrl.navigate_history(direction).await?;
refresh_location(&self.cdp, &self.ctrl, &self.shared, &self.client);
let _ = self.client.send(ack(id, json!({})));
@@ -782,6 +796,18 @@ impl Worker {
true
}
+ /// Show it once (S-F5): the person is leaving through kwnt's address bar or back/forward,
+ /// which moves no focus in the page, so the recorder posts its pending field edits as steps
+ /// first (masked as always). Nothing happens while no recording is on.
+ async fn commit_recorder(&self) {
+ if !self.shared.recording.load(Ordering::SeqCst) { return; }
+ let cdp = &self.cdp;
+ let call = |method: &'static str, params: Value| async move { cdp.call(method, params, PROBE_WAIT).await.ok() };
+ if !recorder::commit_pending(call).await {
+ tracing::debug!("show it once: pending edits weren't committed before the person's navigation");
+ }
+ }
+
fn close_select(&mut self) {
if self.open_select.take().is_some() {
self.cdp.fire("Runtime.releaseObjectGroup", json!({"objectGroup": SELECT_GROUP}));
@@ -940,8 +966,8 @@ async fn stream(
client_rx: &mut mpsc::UnboundedReceiver<Value>,
jobs: &mpsc::UnboundedSender<Job>,
rec: &mut StageRecorder,
-) -> (Result<(), BrowserError>, Option<OwnedRwLockWriteGuard<()>>) {
- let mut lease: Option<OwnedRwLockWriteGuard<()>> = None;
+) -> (Result<(), BrowserError>, Option<PersonLease>) {
+ let mut lease: Option<PersonLease> = None;
// the Show it once recorder's script on new documents, while a recording is live
let mut recorder_script: Option<String> = None;
let result = async {
@@ -1088,7 +1114,7 @@ async fn stream(
let held = ctrl.pointer_held_slot().lock().unwrap_or_else(|e| e.into_inner()).take();
release_on(cdp, held).await;
}
- Err(error) => { send(socket, json!({"type":"error","error":error.to_string()})).await?; continue; }
+ Err(error) => { send(socket, takeover_refused(&error)).await?; continue; }
}
}
let (vw, vh) = shared.view();
@@ -1468,6 +1494,34 @@ mod tests {
assert_eq!(navigated_to("Page.domContentEventFired", &json!({"timestamp":1.0})), None);
}
+ /// Take over from a second window while the first has control is `held_by_person`, never
+ /// the busy bot's error; a bot mid-step is `bot_busy`; once the first window hands back (its
+ /// lease dropped) the second can take over.
+ #[tokio::test]
+ async fn takeover_refused_says_whether_the_person_or_a_bot_has_the_browser() {
+ let ctrl = BrowserController::new(0);
+ let first = ctrl.take_control().await.expect("a free browser");
+ let refused = ctrl.take_control().await.expect_err("one window at a time");
+ assert!(matches!(refused, BrowserError::HeldByPerson));
+ let wire = takeover_refused(&refused);
+ assert_eq!(wire["type"], "error");
+ assert_eq!(wire["code"], "held_by_person");
+ assert_eq!(wire["error"], "You're controlling this browser in another window. Press Hand back there to take over here.");
+ drop(first);
+
+ // A bot action in flight holds the read side
+ let bot = ctrl.control.clone().try_read_owned().unwrap();
+ let refused = ctrl.take_control().await.expect_err("the bot is mid-step");
+ assert!(matches!(refused, BrowserError::HumanControl));
+ assert_eq!(takeover_refused(&refused)["code"], "bot_busy");
+ drop(bot);
+
+ let second = ctrl.take_control().await.expect("free again");
+ assert!(matches!(ctrl.take_control().await, Err(BrowserError::HeldByPerson)));
+ drop(second);
+ assert!(ctrl.take_control().await.is_ok(), "the count went down with the lease");
+ }
+
#[test]
fn input_without_control_says_to_take_control_unless_someone_has_it() {
assert_eq!(not_in_control(false).to_string(), "Take control of the browser first.");
diff --git a/src/server/computer.rs b/src/server/computer.rs
index bb6904a7..4802bc81 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -60,9 +60,28 @@ async fn view(state: &AppState) -> Value {
"available": window.is_none(),
"reason": window,
},
+ // The private browser kwnt downloads when there's no Chrome (O5). The UI shows its
+ // `error` line, with "Try again", only while `state` is "failed".
+ "browser_setup": state.browser_service.chrome_setup().view(),
})
}
+/// `POST /api/settings/computer/browser`: "Try again" for the bots' private browser. Starts the
+/// download again in the background and answers at once with the view (`browser_setup.state` is
+/// then `downloading`, or `ready` if a browser is already there).
+pub async fn retry_browser(State(state): State<AppState>) -> Json<Value> {
+ state.browser_service.chrome_setup().retry();
+ // let the background start mark itself downloading before answering
+ for _ in 0..20 {
+ let s = state.browser_service.chrome_setup().view().state;
+ if s != crate::sandbox::chrome_download::SetupState::Failed {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(25)).await;
+ }
+ Json(view(&state).await)
+}
+
/// `GET /api/settings/computer`
pub async fn get_computer(State(state): State<AppState>) -> Json<Value> {
Json(view(&state).await)
diff --git a/src/server/continuity.rs b/src/server/continuity.rs
index dfdcfb73..6df20e87 100644
--- a/src/server/continuity.rs
+++ b/src/server/continuity.rs
@@ -1729,6 +1729,12 @@ pub async fn notify(state: &AppState, n: Notification) {
/// the space of the turn it held), so the space's Telegram chat and push still get it. With
/// `None`, the space is the bot's.
pub async fn notify_in(state: &AppState, n: Notification, space: Option<&crate::db::spaces::SpaceId>) {
+ notify_held(state, n, space, false).await
+}
+
+/// [`notify_in`], marking a `spend_stopped` notification whose held turn was the person's own
+/// message (see [`super::spend_stop`]).
+pub async fn notify_held(state: &AppState, n: Notification, space: Option<&crate::db::spaces::SpaceId>, held_message: bool) {
if !notify_on(state).await.iter().any(|k| k == n.kind) {
return;
}
@@ -1760,6 +1766,7 @@ pub async fn notify_in(state: &AppState, n: Notification, space: Option<&crate::
body: body.clone(),
space_id,
space_name,
+ held_message,
});
let Some(url) = state
.db
diff --git a/src/server/dev/git.rs b/src/server/dev/git.rs
index c30199c8..6b7599cd 100644
--- a/src/server/dev/git.rs
+++ b/src/server/dev/git.rs
@@ -237,7 +237,68 @@ async fn run(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>) -> R
/// [`run`]; with `head`, stdout past `o.max_out` isn't an error: reading stops there (git then
/// stops at a closed pipe) and the first `o.max_out` bytes come back with `true`.
+///
+/// A remote that answers with a redirect is asked once more at the same address with `.git`
+/// when it had none (N-4: GitLab sends `/group/repo` to `/group/repo.git`, and git is never let
+/// follow a redirect itself). Any other redirect is [`GitError::Failed`], as before.
async fn run_with(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>, head: bool) -> Result<(Vec<u8>, bool), GitError> {
+ match run_once(bin, git_dir, args, o, head).await {
+ Err(Ran::Moved) => {
+ let Some((i, url)) = args.iter().position(|a| *a == "--").and_then(|i| Some((i + 1, with_dot_git(args.get(i + 1)?)?))) else {
+ return Err(GitError::Failed);
+ };
+ let mut again = args.to_vec();
+ again[i] = &url;
+ run_once(bin, git_dir, &again, o, head).await.map_err(Ran::error)
+ }
+ r => r.map_err(Ran::error),
+ }
+}
+
+/// How one run of git failed: a [`GitError`], or a redirect from the remote.
+enum Ran {
+ Git(GitError),
+ Moved,
+}
+
+impl Ran {
+ fn error(self) -> GitError {
+ match self {
+ Ran::Git(e) => e,
+ Ran::Moved => GitError::Failed,
+ }
+ }
+}
+
+impl From<GitError> for Ran {
+ fn from(e: GitError) -> Self {
+ Ran::Git(e)
+ }
+}
+
+/// Whether git stopped at an HTTP redirect it wasn't allowed to follow.
+fn redirected(stderr: &[u8]) -> bool {
+ let e = String::from_utf8_lossy(stderr).to_lowercase();
+ ["301", "302", "303", "307", "308"].iter().any(|c| e.contains(&format!("the requested url returned error: {c}")))
+}
+
+/// `url` with `.git` added, for an http(s) [`fetch_url`] whose path doesn't end in it: the same
+/// scheme, host and port, so the address check, its pin and a token's origin all still hold.
+/// `None` for anything else (ssh, scp-like, a path that already ends in `.git`, no path).
+fn with_dot_git(url: &str) -> Option<String> {
+ let lower = url.to_ascii_lowercase();
+ if !(lower.starts_with("https://") || lower.starts_with("http://")) || fetch_url(url).as_deref() != Some(url) {
+ return None;
+ }
+ let base = url.trim_end_matches('/');
+ if base.to_ascii_lowercase().ends_with(".git") {
+ return None;
+ }
+ let next = format!("{base}.git");
+ (fetch_url(&next).as_deref() == Some(next.as_str()) && remote_host(&next) == remote_host(url)).then_some(next)
+}
+
+async fn run_once(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>, head: bool) -> Result<(Vec<u8>, bool), Ran> {
let mut cmd = tokio::process::Command::new(bin);
if let Some(d) = git_dir {
cmd.arg("--git-dir").arg(d);
@@ -330,9 +391,11 @@ async fn run_with(bin: &str, git_dir: Option<&Path>, args: &[&str], o: Opts<'_>,
} else if status.success() {
Ok((out, false))
} else if o.fsize.is_some() && hit_size_limit(&status, &err) {
- Err(GitError::RepoTooBig)
+ Err(GitError::RepoTooBig.into())
+ } else if redirected(&err) {
+ Err(Ran::Moved)
} else {
- Err(classify(&err))
+ Err(classify(&err).into())
}
}
@@ -1433,6 +1496,25 @@ mod tests {
use super::*;
use std::process::Command;
+ /// Writes an executable script at `path` that is safe to run while other tests start
+ /// processes (D-2). Writing it here would hold a write fd on it in this process, and a
+ /// thread that forks at that moment hands the fd to its child until that child execs; running
+ /// the script then fails with "text file busy" (ETXTBSY), which `run` reports as `Failed`.
+ /// So the bytes go to a draft, and a separate `cp` makes the real file: the only fd ever open
+ /// for writing on it lives and dies in that `cp`, which has exited before anything runs it.
+ fn exe(path: &Path, text: &str) {
+ let draft = path.with_extension("draft");
+ std::fs::write(&draft, text).unwrap();
+ let copied = Command::new("cp").arg(&draft).arg(path).status().unwrap();
+ assert!(copied.success(), "cp {copied}");
+ std::fs::remove_file(&draft).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ }
+
/// Plain git for setting a throwaway repo up (never the code under test).
fn sh(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
@@ -1700,12 +1782,7 @@ mod tests {
let tmp = tempfile::tempdir().unwrap();
let fake = tmp.path().join("git");
let pid_file = tmp.path().join("child.pid");
- std::fs::write(&fake, format!("#!/bin/sh\nsleep 30 &\necho $! > {}\nwait\n", pid_file.display())).unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
+ exe(&fake, &format!("#!/bin/sh\nsleep 30 &\necho $! > {}\nwait\n", pid_file.display()));
let t = Instant::now();
let r = run(fake.to_str().unwrap(), None, &["x"], Opts { timeout: Duration::from_millis(500), ..Opts::read() }).await;
assert_eq!(r, Err(GitError::Timeout));
@@ -1723,19 +1800,13 @@ mod tests {
let fake = tmp.path().join("git");
let seen = tmp.path().join("seen");
// Records its argv and the config git would read from the environment
- std::fs::write(
+ exe(
&fake,
- format!(
+ &format!(
"#!/bin/sh\nprintf '%s\\n' \"$@\" > {0}.argv\nenv | grep -E '^(GIT_|SSH_ASKPASS|GCM_)' | sort > {0}.env\n",
seen.display()
),
- )
- .unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
+ );
let token = format!("{}{}", ["gh", "s_"].concat(), "c4n4ry".repeat(6));
let header = Zeroizing::new(format!("Basic {token}"));
let auth = Auth::header("https://github.com/o/n.git", header).unwrap();
@@ -1877,6 +1948,92 @@ mod tests {
assert!(request.to_ascii_lowercase().contains(&format!("host: pinned.invalid:{port}")), "{request}");
}
+ #[test]
+ fn only_an_http_address_without_dot_git_gets_one() {
+ let g = |u: &str| with_dot_git(u);
+ assert_eq!(g("https://gitlab.com/gitlab-org/gitter/webapp").as_deref(), Some("https://gitlab.com/gitlab-org/gitter/webapp.git"));
+ assert_eq!(g("https://gitlab.com/group/sub/app/").as_deref(), Some("https://gitlab.com/group/sub/app.git"));
+ assert_eq!(g("https://git.example.org:8443/g/r").as_deref(), Some("https://git.example.org:8443/g/r.git"));
+ assert_eq!(g("http://gitea.lan/o/n").as_deref(), Some("http://gitea.lan/o/n.git"));
+ for u in ["https://gitlab.com/g/r.git", "https://gitlab.com/g/r.GIT", "https://gitlab.com", "https://gitlab.com/", "ssh://[email protected]/g/r", "[email protected]:g/r", "git://gitlab.com/g/r", "https://u:[email protected]/g/r", "https://gitlab.com/g/r?x=1"] {
+ assert_eq!(g(u), None, "{u}");
+ }
+ assert!(redirected(b"fatal: unable to access 'https://gitlab.com/g/r/': The requested URL returned error: 301\n"));
+ assert!(!redirected(b"fatal: unable to access 'https://gitlab.com/g/r/': The requested URL returned error: 404\n"));
+ }
+
+ /// A listener on this machine that answers each request by its path (`answer` gets the
+ /// request line) and keeps the request lines it saw, for `n` requests.
+ fn http_host(n: usize, answer: fn(&str) -> String) -> (u16, std::thread::JoinHandle<Vec<String>>) {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ listener.set_nonblocking(false).unwrap();
+ let seen = std::thread::spawn(move || {
+ use std::io::{Read, Write};
+ let mut lines = Vec::new();
+ for _ in 0..n {
+ let Ok((mut c, _)) = listener.accept() else { break };
+ c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let mut buf = [0u8; 8192];
+ let k = c.read(&mut buf).unwrap_or(0);
+ let req = String::from_utf8_lossy(&buf[..k]).to_string();
+ let line = req.lines().next().unwrap_or_default().to_string();
+ let _ = c.write_all(answer(&line).as_bytes());
+ lines.push(line);
+ }
+ lines
+ });
+ (port, seen)
+ }
+
+ /// N-4: GitLab answers `/group/repo` with a redirect to `/group/repo.git`. git isn't let follow
+ /// it; kwant asks the same host once more with `.git`, and a private repo there is `Auth`
+ /// (so Suggest offers "Connect GitLab"), not a generic failure.
+ #[tokio::test]
+ async fn an_address_without_dot_git_is_asked_again_with_it() {
+ const SHA: &str = "0123456789abcdef0123456789abcdef01234567";
+ fn gitlab(line: &str) -> String {
+ let path = line.split(' ').nth(1).unwrap_or_default();
+ if let Some(rest) = path.strip_prefix("/group/app/") {
+ format!("HTTP/1.0 301 Moved Permanently\r\nLocation: /group/app.git/{rest}\r\nContent-Length: 0\r\n\r\n")
+ } else if path.starts_with("/group/app.git/info/refs") {
+ let body = format!("{SHA}\trefs/heads/main\n");
+ format!("HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", body.len())
+ } else if let Some(rest) = path.strip_prefix("/private/app/") {
+ format!("HTTP/1.0 301 Moved Permanently\r\nLocation: /private/app.git/{rest}\r\nContent-Length: 0\r\n\r\n")
+ } else if path.starts_with("/private/app.git/") {
+ "HTTP/1.0 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"x\"\r\nContent-Length: 0\r\n\r\n".into()
+ } else {
+ // Moves every time: kwant asks twice at most and never follows it
+ "HTTP/1.0 302 Found\r\nLocation: http://elsewhere.invalid/\r\nContent-Length: 0\r\n\r\n".into()
+ }
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let o = Opts { timeout: REMOTE_TIMEOUT, ..Opts::read() };
+
+ let (port, seen) = http_host(2, gitlab);
+ let url = format!("http://127.0.0.1:{port}/group/app");
+ let out = run("git", Some(tmp.path()), &["ls-remote", "--heads", "--", &url], o).await.unwrap();
+ assert_eq!(String::from_utf8_lossy(&out), format!("{SHA}\trefs/heads/main\n"));
+ let seen = seen.join().unwrap();
+ assert!(seen[0].starts_with("GET /group/app/info/refs"), "{seen:?}");
+ assert!(seen[1].starts_with("GET /group/app.git/info/refs"), "{seen:?}");
+
+ let (port, seen) = http_host(2, gitlab);
+ let url = format!("http://127.0.0.1:{port}/private/app");
+ assert_eq!(run("git", Some(tmp.path()), &["ls-remote", "--", &url], o).await, Err(GitError::Auth));
+ assert!(seen.join().unwrap()[1].starts_with("GET /private/app.git/info/refs"));
+
+ let (port, seen) = http_host(3, gitlab);
+ let url = format!("http://127.0.0.1:{port}/moved/app");
+ assert_eq!(run("git", Some(tmp.path()), &["ls-remote", "--", &url], o).await, Err(GitError::Failed));
+ // Close the listener's third wait: there must be no third request
+ let _ = std::net::TcpStream::connect(("127.0.0.1", port));
+ let seen = seen.join().unwrap();
+ assert!(seen[0].starts_with("GET /moved/app/info/refs") && seen[1].starts_with("GET /moved/app.git/info/refs"), "{seen:?}");
+ assert_eq!(seen[2], "", "asked twice, never followed: {seen:?}");
+ }
+
#[tokio::test]
async fn a_fetch_checks_its_remote_first() {
let tmp = tempfile::tempdir().unwrap();
@@ -1963,14 +2120,6 @@ mod tests {
// -----------------------------------------------------------------------------------------
// G2 review (Lin, at 6dd0243): one test per probe.
- fn exe(path: &Path, text: &str) {
- std::fs::write(path, text).unwrap();
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
- }
- }
/// F1 (probe P1): an ssh remote runs `ssh`, never an empty command, whatever the repo's own
/// config says. A fake `ssh` first on PATH logs what git asked it for.
diff --git a/src/server/dev/tickets/hooks.rs b/src/server/dev/tickets/hooks.rs
index cbe4615b..39d2ee9d 100644
--- a/src/server/dev/tickets/hooks.rs
+++ b/src/server/dev/tickets/hooks.rs
@@ -99,8 +99,12 @@ async fn save(state: &AppState, space_id: &str, key: &str, b: &Brief) -> Brief {
}
async fn fail(state: &AppState, space_id: &str, key: &str, note: &str) {
+ fail_with(state, space_id, key, note, super::store::FailCode::BriefFailed).await;
+}
+
+async fn fail_with(state: &AppState, space_id: &str, key: &str, note: &str, code: super::store::FailCode) {
let _ = state.db.set_ticket_brief_field(space_id, key, "note", Some(note)).await;
- seam::fail(state, space_id, key, super::store::FailCode::BriefFailed).await;
+ seam::fail(state, space_id, key, code).await;
}
async fn open_questions(state: &AppState, space_id: &str, key: &str) -> Vec<TicketQuestion> {
@@ -368,7 +372,11 @@ pub async fn after_turn(state: &AppState, space_id: &str, key: &str, thread_id:
Some(id) => state.db.get_task(id).await.ok().flatten().is_some_and(|t| !matches!(t.state.as_str(), "working" | "needs_you")),
None => false,
};
- let note = if over {
+ // D6: a refused engine is its own reason on the card, in kwant's words, not a failure
+ let refused = error.as_deref().is_some_and(super::is_engine_refusal);
+ let note = if refused {
+ super::store::FailCode::EngineRefused.message()
+ } else if over {
"The brief went over its token budget; press Start to try again.".to_string()
} else {
match error {
@@ -377,7 +385,8 @@ pub async fn after_turn(state: &AppState, space_id: &str, key: &str, thread_id:
}
};
close_task(state, r.task_id.as_deref(), false, &note).await;
- fail(state, space_id, key, &note).await;
+ let code = if refused { super::store::FailCode::EngineRefused } else { super::store::FailCode::BriefFailed };
+ fail_with(state, space_id, key, &note, code).await;
return;
};
let texts = session.map(|s| s.texts).unwrap_or_default();
diff --git a/src/server/dev/tickets/mod.rs b/src/server/dev/tickets/mod.rs
index 401f69c1..df15c06e 100644
--- a/src/server/dev/tickets/mod.rs
+++ b/src/server/dev/tickets/mod.rs
@@ -36,6 +36,21 @@ pub fn brief_engine(engine: crate::profiles::Engine) -> bool {
matches!(engine, crate::profiles::Engine::Claude | crate::profiles::Engine::Codex)
}
+/// Why a brief turn was refused before it ran (J7, D6): the lead's engine isn't one
+/// [`brief_engine`] allows, or the lead's turn has no tools to check. kwant's own words, shown in the brief's
+/// chat and, through `engine_refused`, on the ticket card.
+pub const ENGINE_REFUSED: &str = "A Jira brief is prepared only on Claude or Codex, with tool checks on.";
+
+/// The brief's chat line for a refused brief turn, naming the lead.
+pub fn engine_refused_line(lead: &str) -> String {
+ format!("⚠️ [{lead}] {ENGINE_REFUSED}")
+}
+
+/// Whether a brief turn's error is kwant's refusal ([`engine_refused_line`]), not a failure.
+pub fn is_engine_refusal(error: &str) -> bool {
+ error.starts_with("⚠️ [") && error.ends_with(&format!("] {ENGINE_REFUSED}"))
+}
+
/// A Jira key as kwant accepts it: `PROJECT-123`, upper-case, at most 40 characters.
pub fn valid_key(key: &str) -> bool {
let Some((project, n)) = key.split_once('-') else { return false };
diff --git a/src/server/dev/tickets/store.rs b/src/server/dev/tickets/store.rs
index d9dfde97..b366262d 100644
--- a/src/server/dev/tickets/store.rs
+++ b/src/server/dev/tickets/store.rs
@@ -84,6 +84,9 @@ pub enum FailCode {
JiraUnreachable,
/// Reading the ticket into a brief failed (Vega's brief turn).
BriefFailed,
+ /// The brief turn was refused before it ran: the lead isn't on Claude or Codex, or its turn has
+ /// no tools to check (J7, D6). Nothing of the ticket was read.
+ EngineRefused,
/// The team's work stopped with an error.
WorkFailed,
/// A writer that didn't say why (`dev_jira::FAIL_DEFAULT_CODE`).
@@ -91,12 +94,13 @@ pub enum FailCode {
}
impl FailCode {
- pub const ALL: &'static [FailCode] = &[FailCode::JiraUnreachable, FailCode::BriefFailed, FailCode::WorkFailed, FailCode::Failed];
+ pub const ALL: &'static [FailCode] = &[FailCode::JiraUnreachable, FailCode::BriefFailed, FailCode::EngineRefused, FailCode::WorkFailed, FailCode::Failed];
pub fn code(self) -> &'static str {
match self {
FailCode::JiraUnreachable => "jira_unreachable",
FailCode::BriefFailed => "brief_failed",
+ FailCode::EngineRefused => "engine_refused",
FailCode::WorkFailed => "work_failed",
FailCode::Failed => dev_jira::FAIL_DEFAULT_CODE,
}
@@ -106,6 +110,7 @@ impl FailCode {
match self {
FailCode::JiraUnreachable => format!("Couldn't reach Jira for {} hours, so work on this ticket stopped.", super::pickup::UNREACHABLE_FAIL_HOURS),
FailCode::BriefFailed => "Couldn't turn this ticket into a brief.".into(),
+ FailCode::EngineRefused => format!("{} Put the team's lead on one of them, then press Start.", super::ENGINE_REFUSED),
FailCode::WorkFailed => "The work on this ticket stopped with an error.".into(),
FailCode::Failed => "Work on this ticket stopped.".into(),
}
@@ -259,6 +264,42 @@ mod tests {
assert_eq!(v["data"], serde_json::json!({"space_id": "s", "key": "K-1", "step": "links", "state": "skipped", "detail": "none"}));
}
+ #[test]
+ fn every_fail_code_reads_back_and_a_refused_engine_says_why() {
+ for c in FailCode::ALL {
+ assert_eq!(FailCode::of(c.code()), *c, "{c:?}");
+ }
+ assert_eq!(FailCode::of("nonsense"), FailCode::Failed);
+ assert_eq!(FailCode::EngineRefused.code(), "engine_refused");
+ let m = FailCode::EngineRefused.message();
+ assert_eq!(m, "A Jira brief is prepared only on Claude or Codex, with tool checks on. Put the team's lead on one of them, then press Start.");
+ assert_ne!(m, FailCode::Failed.message());
+ assert!(m.chars().count() <= 300, "the card keeps 300 characters");
+ }
+
+ #[test]
+ fn no_card_sentence_says_a_bare_kwant() {
+ // the frontend's wording rule (frontend/tests/wording.test.mjs): never a bare "kwant", "kwnt" or "agent"
+ let bad = |w: &str| matches!(w.to_lowercase().as_str(), "kwant" | "kwants" | "kwant's" | "kwnt" | "agent" | "agents");
+ for c in FailCode::ALL {
+ let m = c.message();
+ let words = m.split(|ch: char| !(ch.is_alphanumeric() || ch == '\''));
+ assert!(!words.into_iter().any(bad), "{c:?}: {m}");
+ }
+ }
+
+ #[test]
+ fn only_kwants_own_refusal_line_counts_as_a_refused_engine() {
+ use super::super::{engine_refused_line, is_engine_refusal};
+ assert!(is_engine_refusal(&engine_refused_line("Lead")));
+ assert!(is_engine_refusal(&engine_refused_line("A [b] c")));
+ assert!(!is_engine_refusal("The brief took longer than 15 minutes"));
+ assert!(!is_engine_refusal(super::super::ENGINE_REFUSED), "without the chat's lead prefix");
+ assert!(!is_engine_refusal(&format!("{} and more", engine_refused_line("Lead"))));
+ let old = "⚠️ [Lead] A Jira brief is prepared only on Claude or Codex, with kwant's tool checks on.";
+ assert!(!is_engine_refusal(old), "only the current sentence counts");
+ }
+
#[test]
fn keys_come_from_the_branch_then_the_title() {
assert_eq!(key_in(Some("TRAIL-101-receipt-link"), "x"), Some("TRAIL-101".into()));
diff --git a/src/server/engine_login.rs b/src/server/engine_login.rs
index 536e4093..3eb102cd 100644
--- a/src/server/engine_login.rs
+++ b/src/server/engine_login.rs
@@ -1,10 +1,12 @@
-//! "Sign in with Claude" for the Claude engine: `POST /api/engines/claude/login` runs Claude
-//! Code's own `auth login --claudeai` on the config dir the engine itself uses. The CLI prints a
-//! claude.ai link; claude.ai then shows a code the user pastes back, and the CLI keeps the login.
-//! kwnt never reads, stores or logs the token, the code or the link's state.
+//! In-app sign-in for the CLI engines: `POST /api/engines/:engine/login` runs the engine CLI's
+//! own login on the config dir the engine itself uses.
+//! - Claude: `auth login --claudeai` prints a claude.ai link; claude.ai shows a code the user
+//! pastes back (`POST .../:sid/code`).
+//! - Codex (ChatGPT) and Grok: `login --device-auth` prints a link and a device code; the user
+//! enters the code on the site and the CLI finishes by itself, so kwnt notices on its own.
//!
-//! Also `GET`/`DELETE /api/engines/claude/login/:sid`, `POST .../:sid/code` and
-//! `POST /api/engines/claude/logout`.
+//! The CLI keeps the login. kwnt never reads, stores or logs the token, the code or the link.
+//! Also `GET`/`DELETE /api/engines/:engine/login/:sid` and `POST /api/engines/:engine/logout`.
use super::engine_routes::EnginesResponse;
use super::AppState;
@@ -19,105 +21,223 @@ use axum::{
};
use serde::{Deserialize, Serialize};
use serde_json::json;
-use std::collections::HashSet;
+use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
-/// Owner recorded on engine sign-ins, so profile routes never see them (profile ids are `prf_…`).
+/// Owner recorded on Claude's engine sign-ins, so profile routes never see them (profile ids
+/// are `prf_…`). Codex and Grok use `engine:codex` and `engine:grok`.
pub const OWNER: &str = "engine:claude";
+/// The engines kwnt can sign in to from the app.
+pub const ENGINES: [Engine; 3] = [Engine::Claude, Engine::Codex, Engine::Grok];
+
+/// The engine named in the path, if it has an in-app sign-in.
+pub fn engine_named(name: &str) -> Option<Engine> {
+ ENGINES.into_iter().find(|e| e.as_str() == name)
+}
+
+fn engine_id(engine: Engine) -> EngineId {
+ match engine {
+ Engine::Codex => EngineId::Codex,
+ Engine::Grok => EngineId::Grok,
+ _ => EngineId::Claude,
+ }
+}
+
+/// The product name people know the engine by.
+fn display(engine: Engine) -> &'static str {
+ match engine {
+ Engine::Codex => "ChatGPT",
+ Engine::Grok => "Grok",
+ _ => "Claude",
+ }
+}
+
+/// The CLI's name in "isn't installed".
+fn cli_name(engine: Engine) -> &'static str {
+ match engine {
+ Engine::Codex => "Codex",
+ Engine::Grok => "Grok CLI",
+ _ => "Claude Code",
+ }
+}
+
/// How long `auth logout` may take.
const LOGOUT_TIMEOUT: Duration = Duration::from_secs(30);
-pub struct ClaudeLogin {
+pub struct EngineLogin {
+ engine: Engine,
+ owner: String,
pub logins: LoginManager,
- /// `None`: `claude` on PATH.
+ /// `None`: the engine's CLI on PATH (or where kwnt installs it).
bin: Option<String>,
- /// `None` (always, outside tests): the CLI's env as turns see it, so `CLAUDE_CONFIG_DIR` on
- /// kwnt's process, else `~/.claude`. Set, sign-in, sign-out and the Claude check use this dir.
+ /// `None` (always, outside tests): the CLI's env as turns see it, so `CLAUDE_CONFIG_DIR`,
+ /// `CODEX_HOME` or `GROK_HOME` on kwnt's process, else `~/.claude`, `~/.codex` or `~/.grok`.
+ /// Set, sign-in and sign-out use this dir.
config_dir: Option<PathBuf>,
- /// Successful sign-ins the engine registry has re-checked Claude for.
- rechecked: Mutex<HashSet<String>>,
+ /// Successful sign-ins the engine registry has re-checked the engine for: `None` when the
+ /// engine is now ready, else what the check said (device sign-ins only).
+ rechecked: Mutex<HashMap<String, Option<String>>>,
}
-impl Default for ClaudeLogin {
+/// The Claude engine's sign-in, as before 0.7.6.
+pub type ClaudeLogin = EngineLogin;
+
+impl Default for EngineLogin {
fn default() -> Self {
- Self::new(None, None, LoginManager::default())
+ Self::system(Engine::Claude)
}
}
-impl ClaudeLogin {
+impl EngineLogin {
+ /// Claude's sign-in with this CLI and config dir (tests); see [`Self::for_engine`].
pub fn new(bin: Option<String>, config_dir: Option<PathBuf>, logins: LoginManager) -> Self {
- Self { logins, bin, config_dir, rechecked: Default::default() }
+ Self::for_engine(Engine::Claude, bin, config_dir, logins)
+ }
+
+ pub fn for_engine(engine: Engine, bin: Option<String>, config_dir: Option<PathBuf>, logins: LoginManager) -> Self {
+ Self {
+ engine,
+ owner: format!("engine:{}", engine.as_str()),
+ logins,
+ bin,
+ config_dir,
+ rechecked: Default::default(),
+ }
+ }
+
+ /// The engine's own CLI and config dir, as turns use them.
+ pub fn system(engine: Engine) -> Self {
+ Self::for_engine(engine, None, None, LoginManager::default())
+ }
+
+ pub fn engine(&self) -> Engine {
+ self.engine
}
fn bin(&self) -> Option<String> {
- self.bin.clone().or_else(|| crate::drivers::find_cli_binary("claude"))
+ self.bin.clone().or_else(|| crate::drivers::find_cli_binary(self.engine.as_str()))
}
/// The config dir the CLI will write the login to.
fn home(&self) -> Option<PathBuf> {
- self.config_dir.clone().or_else(|| Engine::Claude.system_home())
+ self.config_dir.clone().or_else(|| self.engine.system_home())
}
fn cli_env(&self) -> CliEnv {
match &self.config_dir {
- Some(dir) => CliEnv::for_home(Engine::Claude, dir),
+ Some(dir) => CliEnv::for_home(self.engine, dir),
None => CliEnv::default(),
}
}
- /// The engine checks, pointed at the same CLI and config dir as sign-in.
+ fn device(&self) -> bool {
+ self.engine != Engine::Claude
+ }
+
+ /// The engine checks, pointed at the same CLI (and, for Claude, config dir) as sign-in.
pub fn probe_env(&self, mut env: ProbeEnv) -> ProbeEnv {
- if let Some(bin) = &self.bin {
- env.claude_bin = Some(bin.clone());
+ match self.engine {
+ Engine::Codex => {
+ if let Some(bin) = &self.bin {
+ env.codex_bin = Some(bin.clone());
+ }
+ }
+ Engine::Grok => {
+ if let Some(bin) = &self.bin {
+ env.grok_bin = Some(bin.clone());
+ }
+ }
+ _ => {
+ if let Some(bin) = &self.bin {
+ env.claude_bin = Some(bin.clone());
+ }
+ env.claude_config_dir = self.config_dir.clone();
+ }
}
- env.claude_config_dir = self.config_dir.clone();
env
}
fn view(&self, v: &LoginView) -> SessionView {
- let rechecked = self.rechecked.lock().unwrap().contains(&v.flow_id);
+ let rechecked = self.rechecked.lock().unwrap().get(&v.flow_id).cloned();
+ let name = display(self.engine);
let (state, detail) = match v.status {
LoginStatus::Starting => ("starting", None),
+ // A device sign-in shows nothing until it has both the link and the code
+ LoginStatus::Waiting if self.device() && !v.shows_everything() => ("starting", None),
+ LoginStatus::Waiting if self.device() => ("waiting_for_approval", None),
LoginStatus::Waiting if v.code_sent => ("verifying", None),
LoginStatus::Waiting => ("waiting_for_code", None),
// Done only once GET /api/engines shows the new status
- LoginStatus::Succeeded if !rechecked => ("verifying", None),
- LoginStatus::Succeeded => ("done", None),
+ LoginStatus::Succeeded => match rechecked {
+ None => ("verifying", None),
+ Some(None) => ("done", None),
+ Some(Some(why)) if self.device() => (
+ "failed",
+ Some(format!("Signed in, but {} can't use this account: {why}", cli_name(self.engine))),
+ ),
+ Some(Some(_)) => ("done", None),
+ },
// The CLI's own output is never shown: it can carry the code
LoginStatus::Failed if v.code_sent => {
("failed", Some("Claude didn't accept that code. Start sign-in again.".to_string()))
}
LoginStatus::Failed => ("failed", v.error.clone()),
+ LoginStatus::Expired if self.device() => {
+ ("expired", Some(format!("That {name} code expired. Get a new code to try again.")))
+ }
LoginStatus::Expired => ("expired", Some("Sign-in timed out. Start it again.".to_string())),
LoginStatus::Cancelled => ("cancelled", None),
};
- // A finished sign-in's link is dead: don't offer it
- let url = matches!(state, "starting" | "waiting_for_code" | "verifying").then(|| v.url.clone()).flatten();
+ // A finished sign-in's link and code are dead: don't offer them
+ let live = matches!(state, "starting" | "waiting_for_code" | "waiting_for_approval" | "verifying");
SessionView {
session_id: v.flow_id.clone(),
+ engine: self.engine.as_str(),
+ kind: if self.device() { "device_code" } else { "paste_code" },
state,
detail,
- url,
+ url: live.then(|| v.url.clone()).flatten(),
+ user_code: (live && self.device()).then(|| v.user_code.clone()).flatten(),
expires_at: v.expires_at,
}
}
fn find(&self, sid: &str) -> Option<LoginView> {
- self.logins.get(sid).filter(|v| v.profile_id == OWNER)
+ self.logins.get(sid).filter(|v| v.profile_id == self.owner)
+ }
+}
+
+/// The sign-in of the engine named in the path, or a 404.
+#[allow(clippy::result_large_err)]
+fn login_for<'a>(state: &'a AppState, name: &str) -> Result<&'a Arc<EngineLogin>, Response> {
+ match engine_named(name) {
+ Some(Engine::Claude) => Ok(&state.claude_login),
+ Some(Engine::Codex) => Ok(&state.codex_login),
+ Some(Engine::Grok) => Ok(&state.grok_login),
+ _ => Err(err(StatusCode::NOT_FOUND, "no in-app sign-in for this engine")),
}
}
-/// What the UI gets for a sign-in. `url` is the claude.ai link meant for the user.
+/// What the UI gets for a sign-in. `url` and `user_code` are meant for the user.
#[derive(Debug, Serialize)]
pub struct SessionView {
pub session_id: String,
- /// `starting`, `waiting_for_code`, `verifying`, `done`, `failed`, `expired` or `cancelled`.
+ /// `claude`, `codex` or `grok`.
+ pub engine: &'static str,
+ /// `paste_code` (Claude: open the link, paste the code back) or `device_code` (Codex, Grok:
+ /// open the link, enter `user_code` there; kwnt notices by itself).
+ pub kind: &'static str,
+ /// `starting`, `waiting_for_code` (paste), `waiting_for_approval` (device), `verifying`,
+ /// `done`, `failed`, `expired` or `cancelled`.
pub state: &'static str,
pub detail: Option<String>,
pub url: Option<String>,
+ /// The device code to enter on `url` (device sign-ins, while live).
+ pub user_code: Option<String>,
+ /// When the sign-in (and a device code) stops working.
pub expires_at: chrono::DateTime<chrono::Utc>,
}
@@ -131,57 +251,85 @@ fn err(status: StatusCode, msg: impl Into<String>) -> Response {
(status, Json(json!({ "error": msg.into() }))).into_response()
}
-async fn recheck_claude(state: &AppState) {
+async fn recheck(state: &AppState, engine: Engine) {
let env = super::engine_routes::probe_env(state).await;
- state.engines.recheck_one(EngineId::Claude, &env).await;
+ state.engines.recheck_one(engine_id(engine), &env).await;
}
-/// `POST /api/engines/claude/login`: starts Claude Code's sign-in. 409 while one is running.
-pub async fn start(State(state): State<AppState>) -> Response {
- let login = &state.claude_login;
+/// Why the engine can't take turns after a sign-in, or `None` when it is ready.
+fn not_ready_reason(state: &AppState, engine: Engine) -> Option<String> {
+ let id = engine_id(engine);
+ let report = state.engines.snapshot().into_iter().find(|r| r.id == id)?;
+ use crate::drivers::engines::EngineStatus;
+ // Turned off in Settings is not about the account: the sign-in itself is done
+ match report.status {
+ EngineStatus::SignedOut => Some("it still shows as signed out".into()),
+ EngineStatus::Error => Some(report.detail.unwrap_or_else(|| "it isn't ready".into())),
+ _ => None,
+ }
+}
+
+/// `POST /api/engines/:engine/login`: starts the engine CLI's sign-in. 409 while one is running.
+pub async fn start(State(state): State<AppState>, Path(engine): Path<String>) -> Response {
+ let login = match login_for(&state, &engine) {
+ Ok(l) => l.clone(),
+ Err(r) => return r,
+ };
+ let engine = login.engine;
let Some(bin) = login.bin() else {
- return err(StatusCode::BAD_REQUEST, "Claude Code isn't installed");
+ return err(StatusCode::BAD_REQUEST, format!("{} isn't installed", cli_name(engine)));
};
let Some(home) = login.home() else {
- return err(StatusCode::INTERNAL_SERVER_ERROR, "couldn't find Claude Code's config dir");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't find {}'s config dir", cli_name(engine)));
};
- if login.config_dir.is_some() {
+ // Codex refuses a CODEX_HOME that doesn't exist yet
+ if login.config_dir.is_some() || !home.exists() {
if let Err(e) = create_private_dir(&home) {
- tracing::warn!(error = %e, "could not create the Claude config dir");
- return err(StatusCode::INTERNAL_SERVER_ERROR, "couldn't create Claude Code's config dir");
+ tracing::warn!(engine = engine.as_str(), error = %e, "could not create the engine's config dir");
+ return err(StatusCode::INTERNAL_SERVER_ERROR, format!("couldn't create {}'s config dir", cli_name(engine)));
}
}
let done_state = state.clone();
let on_success: OnSuccess = Arc::new(move |view: LoginView| {
let state = done_state.clone();
tokio::spawn(async move {
- recheck_claude(&state).await;
- state.claude_login.rechecked.lock().unwrap().insert(view.flow_id);
- tracing::info!("claude engine sign-in finished");
+ recheck(&state, engine).await;
+ let login = login_for(&state, engine.as_str()).expect("engine has a sign-in");
+ let why = if login.device() { not_ready_reason(&state, engine) } else { None };
+ let ready = why.is_none();
+ login.rechecked.lock().unwrap().insert(view.flow_id, why);
+ tracing::info!(engine = engine.as_str(), ready, "{} engine sign-in finished", engine.as_str());
});
});
match login
.logins
- .start_exclusive(Engine::Claude, &bin, OWNER, &home, &login.cli_env(), on_success)
+ .start_exclusive(engine, &bin, &login.owner, &home, &login.cli_env(), on_success)
.await
{
Ok(v) => {
- tracing::info!("claude engine sign-in started");
+ tracing::info!(engine = engine.as_str(), "{} engine sign-in started", engine.as_str());
Json(login.view(&v)).into_response()
}
Err(StartError::Busy(v)) => (
StatusCode::CONFLICT,
- Json(json!({ "error": "a Claude sign-in is already running", "session_id": v.flow_id })),
+ Json(json!({
+ "error": format!("a {} sign-in is already running", display(engine)),
+ "session_id": v.flow_id,
+ })),
)
.into_response(),
Err(StartError::Failed(e)) => err(StatusCode::BAD_GATEWAY, e),
}
}
-/// `GET /api/engines/claude/login/:sid`
-pub async fn get(State(state): State<AppState>, Path(sid): Path<String>) -> Response {
- match state.claude_login.find(&sid) {
- Some(v) => Json(state.claude_login.view(&v)).into_response(),
+/// `GET /api/engines/:engine/login/:sid`
+pub async fn get(State(state): State<AppState>, Path((engine, sid)): Path<(String, String)>) -> Response {
+ let login = match login_for(&state, &engine) {
+ Ok(l) => l,
+ Err(r) => return r,
+ };
+ match login.find(&sid) {
+ Some(v) => Json(login.view(&v)).into_response(),
None => err(StatusCode::NOT_FOUND, "no such sign-in"),
}
}
@@ -192,14 +340,17 @@ pub struct CodeBody {
code: String,
}
-/// `POST /api/engines/claude/login/:sid/code`: the code claude.ai showed. Answers once Claude Code
-/// has accepted or refused it (or after 20s, still `verifying`).
+/// `POST /api/engines/:engine/login/:sid/code`: the code claude.ai showed (Claude only). Answers
+/// once Claude Code has accepted or refused it (or after 20s, still `verifying`).
pub async fn submit_code(
State(state): State<AppState>,
- Path(sid): Path<String>,
+ Path((engine, sid)): Path<(String, String)>,
Json(body): Json<CodeBody>,
) -> Response {
- let login = &state.claude_login;
+ let login = match login_for(&state, &engine) {
+ Ok(l) => l,
+ Err(r) => return r,
+ };
if login.find(&sid).is_none() {
return err(StatusCode::NOT_FOUND, "no such sign-in");
}
@@ -217,9 +368,12 @@ pub async fn submit_code(
Json(view).into_response()
}
-/// `DELETE /api/engines/claude/login/:sid`: stops the sign-in and kills the CLI.
-pub async fn cancel(State(state): State<AppState>, Path(sid): Path<String>) -> Response {
- let login = &state.claude_login;
+/// `DELETE /api/engines/:engine/login/:sid`: stops the sign-in and kills the CLI.
+pub async fn cancel(State(state): State<AppState>, Path((engine, sid)): Path<(String, String)>) -> Response {
+ let login = match login_for(&state, &engine) {
+ Ok(l) => l,
+ Err(r) => return r,
+ };
if login.find(&sid).is_none() {
return err(StatusCode::NOT_FOUND, "no such sign-in");
}
@@ -235,16 +389,24 @@ pub async fn cancel(State(state): State<AppState>, Path(sid): Path<String>) -> R
StatusCode::NO_CONTENT.into_response()
}
-/// `POST /api/engines/claude/logout`: Claude Code's own `auth logout` on the engine's config dir.
-/// Answers with every engine, as `GET /api/engines` does.
-pub async fn logout(State(state): State<AppState>) -> Response {
- let login = &state.claude_login;
+/// `POST /api/engines/:engine/logout`: the CLI's own sign-out (`claude auth logout`,
+/// `codex logout`, `grok logout`) on the engine's config dir. Answers with every engine, as
+/// `GET /api/engines` does.
+pub async fn logout(State(state): State<AppState>, Path(engine): Path<String>) -> Response {
+ let login = match login_for(&state, &engine) {
+ Ok(l) => l.clone(),
+ Err(r) => return r,
+ };
+ let engine = login.engine;
let Some(bin) = login.bin() else {
- return err(StatusCode::BAD_REQUEST, "Claude Code isn't installed");
+ return err(StatusCode::BAD_REQUEST, format!("{} isn't installed", cli_name(engine)));
};
- login.logins.cancel_profile(OWNER);
+ login.logins.cancel_profile(&login.owner);
let mut cmd = tokio::process::Command::new(&bin);
- cmd.args(["auth", "logout"]);
+ match engine {
+ Engine::Claude => cmd.args(["auth", "logout"]),
+ _ => cmd.arg("logout"),
+ };
login.cli_env().apply(&mut cmd);
cmd.env("NO_COLOR", "1")
.stdin(std::process::Stdio::null())
@@ -255,10 +417,10 @@ pub async fn logout(State(state): State<AppState>) -> Response {
tokio::time::timeout(LOGOUT_TIMEOUT, cmd.status()).await,
Ok(Ok(s)) if s.success()
);
- recheck_claude(&state).await;
+ recheck(&state, engine).await;
if !ok {
- return err(StatusCode::BAD_GATEWAY, "Claude Code couldn't sign out");
+ return err(StatusCode::BAD_GATEWAY, format!("{} couldn't sign out", cli_name(engine)));
}
- tracing::info!("claude engine signed out");
+ tracing::info!(engine = engine.as_str(), "{} engine signed out", engine.as_str());
Json(EnginesResponse { engines: state.engines.snapshot() }).into_response()
}
diff --git a/src/server/engine_routes.rs b/src/server/engine_routes.rs
index f71b6140..25b72308 100644
--- a/src/server/engine_routes.rs
+++ b/src/server/engine_routes.rs
@@ -42,7 +42,8 @@ pub async fn recheck_all(state: &AppState, space: &SpaceId) -> Vec<EngineReport>
/// What the checks run with: Settings and the env, and Claude's sign-in config dir.
pub async fn probe_env(state: &AppState) -> ProbeEnv {
- state.claude_login.probe_env(ProbeEnv::from_settings(&state.db).await)
+ let env = state.claude_login.probe_env(ProbeEnv::from_settings(&state.db).await);
+ state.grok_login.probe_env(state.codex_login.probe_env(env))
}
/// Reads which engines are off from Settings into the registry.
diff --git a/src/server/mod.rs b/src/server/mod.rs
index b185a9dc..9a83eab5 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -112,6 +112,10 @@ pub struct AppState {
pub human_steps: Arc<human_steps::HumanStepHub>,
/// "Sign in with Claude" for the Claude engine.
pub claude_login: Arc<engine_login::ClaudeLogin>,
+ /// "Sign in with ChatGPT" (Codex device code) for the Codex engine.
+ pub codex_login: Arc<engine_login::EngineLogin>,
+ /// "Sign in with Grok" (device code) for the Grok engine.
+ pub grok_login: Arc<engine_login::EngineLogin>,
/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).
pub mcp_registry: Arc<crate::mcp::registry::McpRegistry>,
/// Composio's app catalogue (`KWNT_COMPOSIO_API_URL`), called only once Composio is added.
@@ -173,6 +177,8 @@ impl AppState {
questions: Default::default(),
human_steps: Default::default(),
claude_login: Default::default(),
+ codex_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Codex)),
+ grok_login: Arc::new(engine_login::EngineLogin::system(crate::profiles::Engine::Grok)),
mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),
composio_api: Arc::new(crate::mcp::composio::ComposioApi::from_env()),
credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),
@@ -228,13 +234,14 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/profiles/:id/logout", post(profile_routes::logout))
.route("/api/engines", get(engine_routes::list))
.route("/api/engines/recheck", post(engine_routes::recheck))
- .route("/api/engines/claude/login", post(engine_login::start))
+ // :engine is claude, codex or grok (anything else is a 404)
+ .route("/api/engines/:engine/login", post(engine_login::start))
.route(
- "/api/engines/claude/login/:sid",
+ "/api/engines/:engine/login/:sid",
get(engine_login::get).delete(engine_login::cancel),
)
- .route("/api/engines/claude/login/:sid/code", post(engine_login::submit_code))
- .route("/api/engines/claude/logout", post(engine_login::logout))
+ .route("/api/engines/:engine/login/:sid/code", post(engine_login::submit_code))
+ .route("/api/engines/:engine/logout", post(engine_login::logout))
.route("/api/engines/:id", post(engine_routes::set_enabled).put(engine_routes::set_enabled))
.route("/api/laya/status", get(routes::laya_status))
.route("/api/kwants", get(routes::list_kwants).post(routes::create_kwant))
@@ -282,6 +289,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/settings", get(routes::get_settings).post(routes::save_settings))
.route("/api/settings/computer", get(computer::get_computer).put(computer::put_computer))
.route("/api/settings/computer/window", put(computer::put_window))
+ .route("/api/settings/computer/browser", post(computer::retry_browser))
.route("/api/system/directories", get(routes::list_system_directories))
.route("/api/system/select-folder", post(routes::select_folder))
.route("/api/sandbox/:team_id/status", get(routes::get_sandbox_status))
diff --git a/src/server/routes.rs b/src/server/routes.rs
index eada3a36..c64790df 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -1950,7 +1950,10 @@ pub(super) async fn turn_once(
// The daily spending stop: the one check every turn passes, whatever started it (see
// [`super::spend_stop`]). Checked again once the slot is taken, for turns that queued.
let quiet_stop = opts.quiet_failure || opts.unsaved;
- super::spend_stop::gate(scope, target_kwant, quiet_stop).await?;
+ // Only the person's own message carries a nav prompt (hand-offs, routines, missions and Jira
+ // tasks never do), so this is how the stop knows it held the person's message
+ let person_turn = opts.nav_prompt.is_some();
+ super::spend_stop::gate(scope, target_kwant, quiet_stop, person_turn).await?;
let turns = &scope.state.turns;
turns.add_keys(&scope.job_id, std::slice::from_ref(&tag.turn_id));
// Sends turn_ended even if this future is dropped, queued or mid-turn
@@ -1966,7 +1969,7 @@ pub(super) async fn turn_once(
let Some(_slot) = turns.acquire(&tag, &scope.cancel_token, &scope.state.event_sender).await else {
return Err("stopped by the user".into());
};
- super::spend_stop::gate(scope, target_kwant, quiet_stop).await?;
+ super::spend_stop::gate(scope, target_kwant, quiet_stop, person_turn).await?;
turns.set_turn(super::turns::ActiveTurn {
turn_id: tag.turn_id.clone(),
kwant_id: tag.kwant_id.clone(),
@@ -2608,7 +2611,7 @@ async fn run_kwant_turn_inner(
gave_up = Some(text);
} else if attempts.is_empty() {
let text = if brief_turn && (rehearse_blocked || had_attempts) {
- format!("⚠️ [{}] A Jira brief is prepared only on Claude or Codex, with kwant's tool checks on.", target_kwant.name)
+ super::dev::tickets::engine_refused_line(&target_kwant.name)
} else if rehearse_blocked {
format!("⚠️ [{}] A skill replay runs only on Claude, with kwant's tool checks on.", target_kwant.name)
} else {
diff --git a/src/server/show_once/capture.rs b/src/server/show_once/capture.rs
index 986d3365..43bccded 100644
--- a/src/server/show_once/capture.rs
+++ b/src/server/show_once/capture.rs
@@ -50,6 +50,31 @@ where
took
}
+/// Run in the recorder's world before the person's own navigation: the pending edits are posted
+/// through the binding as steps. `false` where the recorder isn't installed.
+pub const COMMIT: &str =
+ "typeof globalThis.__kwntRecorderCommit === 'function' ? (globalThis.__kwntRecorderCommit(), true) : false";
+
+/// The person is leaving the page through kwnt's address bar or back/forward (S-F5). Neither
+/// moves focus in the page, so a field typed into and never left would otherwise leave no step.
+/// The recorder posts those edits through its binding first, as `type` steps with the field's
+/// mask, so a password or code is recorded masked and its value never leaves the page. `call`
+/// sends one CDP command. True when the recorder took the commit.
+pub async fn commit_pending<F, Fut>(call: F) -> bool
+where
+ F: Fn(&'static str, serde_json::Value) -> Fut,
+ Fut: std::future::Future<Output = Option<serde_json::Value>>,
+{
+ use serde_json::json;
+ let Some(tree) = call("Page.getFrameTree", json!({})).await else { return false };
+ let Some(frame) = tree["frameTree"]["frame"]["id"].as_str() else { return false };
+ let world = json!({"frameId": frame, "worldName": WORLD});
+ let Some(world) = call("Page.createIsolatedWorld", world).await else { return false };
+ let Some(context) = world["executionContextId"].as_i64() else { return false };
+ let eval = json!({"expression": COMMIT, "contextId": context, "returnByValue": true});
+ call("Runtime.evaluate", eval).await.is_some_and(|r| r["result"]["value"] == true)
+}
+
/// Largest payload read; anything bigger is dropped.
pub const MAX_PAYLOAD: usize = 16 * 1024;
pub const MAX_NAME: usize = 120;
@@ -313,6 +338,48 @@ mod tests {
assert!(PICKED_FN.contains("typeof f === 'function'"));
}
+ /// `commit_pending` against a fake CDP: what it returned and every call it made.
+ fn commit_with(replies: Replies) -> (bool, Vec<(String, serde_json::Value)>) {
+ let map: std::collections::HashMap<_, _> = replies.into_iter().collect();
+ let log = std::sync::Mutex::new(Vec::new());
+ let call = |m: &'static str, p: serde_json::Value| {
+ log.lock().unwrap().push((m.to_string(), p));
+ let r = map.get(m).cloned().flatten();
+ async move { r }
+ };
+ let took = tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(commit_pending(call));
+ (took, log.into_inner().unwrap())
+ }
+
+ fn commit_ok(took: bool) -> Replies {
+ vec![
+ ("Page.getFrameTree", Some(json!({"frameTree": {"frame": {"id": "F1"}}}))),
+ ("Page.createIsolatedWorld", Some(json!({"executionContextId": 7}))),
+ ("Runtime.evaluate", Some(json!({"result": {"value": took}}))),
+ ]
+ }
+
+ #[test]
+ fn leaving_by_the_address_bar_commits_in_the_recorders_world_only() {
+ let (took, log) = commit_with(commit_ok(true));
+ assert!(took);
+ let methods: Vec<&str> = log.iter().map(|(m, _)| m.as_str()).collect();
+ assert_eq!(methods, ["Page.getFrameTree", "Page.createIsolatedWorld", "Runtime.evaluate"]);
+ assert_eq!(log[1].1, json!({"frameId": "F1", "worldName": WORLD}), "the recorder's own world");
+ assert_eq!(log[2].1, json!({"expression": COMMIT, "contextId": 7, "returnByValue": true}));
+ // no recorder there, or any step failing: nothing taken, and nothing past the failure
+ assert!(!commit_with(commit_ok(false)).0);
+ for failing in ["Page.getFrameTree", "Page.createIsolatedWorld", "Runtime.evaluate"] {
+ let replies = commit_ok(true).into_iter().map(|(m, r)| (m, if m == failing { None } else { r })).collect();
+ let (took, log) = commit_with(replies);
+ assert!(!took, "{failing}");
+ assert_eq!(log.last().unwrap().0, failing);
+ }
+ assert!(COMMIT.contains("typeof globalThis.__kwntRecorderCommit === 'function'"));
+ let js = recorder_js();
+ assert!(js.contains("Object.defineProperty(globalThis, '__kwntRecorderCommit'"), "not enumerable, not writable");
+ }
+
#[test]
fn the_recorder_names_a_wrapped_field_by_the_labels_own_words() {
let js = recorder_js();
diff --git a/src/server/show_once/draft.rs b/src/server/show_once/draft.rs
index 9e4ba28c..894a7ae5 100644
--- a/src/server/show_once/draft.rs
+++ b/src/server/show_once/draft.rs
@@ -167,8 +167,27 @@ fn input_name(raw: &str) -> Option<String> {
ok.then_some(n)
}
+/// What the Write failed banner says when the draft's input took its example from a step where
+/// nothing was typed (a page step, a click, a note): Mira's copy, next-076/copy.md §S-F3.
+pub const SHOWN_NOTHING_TYPED: &str = "Its draft took a value from a step where nothing was typed.";
+/// What it says for any other draft check that failed (the same slot).
+pub const SHOWN_DRAFT_MISMATCH: &str = "Its draft didn't match your recorded steps.";
+/// The end of the check that an input's `from_step` has no typed value.
+const NO_VALUE: &str = "has no value";
+const IS_A_NOTE: &str = "is a note; a note can't be an input";
+
+/// The person's sentence for a draft that failed a check (S-F3). The check's own words
+/// (`input 1's from_step 1 has no value`) go to the engine on the retry only, never to the banner.
+pub fn shown_reason(why: &str) -> &'static str {
+ if why.starts_with("input ") && (why.ends_with(NO_VALUE) || why.ends_with(IS_A_NOTE)) {
+ SHOWN_NOTHING_TYPED
+ } else {
+ SHOWN_DRAFT_MISMATCH
+ }
+}
+
/// Reads the turn's reply against the recording's steps. `Err` is the reason, said to the bot on
-/// the retry and to the person as `write_error`.
+/// the retry; the person sees [`shown_reason`] of it as `write_error`.
pub fn parse(reply: &str, steps: &[StepRow]) -> Result<Draft, String> {
let m = json_object(reply)?;
// Everything the engine wrote is masked like any other text kwant keeps (S-F4): a key it
@@ -210,10 +229,10 @@ pub fn parse(reply: &str, steps: &[StepRow]) -> Result<Draft, String> {
return Err(format!("input {at}'s from_step {from} is masked; a masked step can't be an input"));
}
if step.kind == "note" {
- return Err(format!("input {at}'s from_step {from} is a note; a note can't be an input"));
+ return Err(format!("input {at}'s from_step {from} {IS_A_NOTE}"));
}
let Some(example) = step.value.clone().filter(|v| !v.trim().is_empty()) else {
- return Err(format!("input {at}'s from_step {from} has no value"));
+ return Err(format!("input {at}'s from_step {from} {NO_VALUE}"));
};
// Duplicate names get _2, _3...
let mut unique = name.clone();
@@ -328,13 +347,56 @@ pub async fn write(state: AppState, id: String) {
match scope_for(st, b, None, None, job, 0).await {
Ok(scope) => tokio::time::timeout(TURN_TIMEOUT, turn_once(&scope, b, p, draft_opts()))
.await
- .unwrap_or_else(|_| Err("the draft took longer than 10 minutes".into())),
+ .unwrap_or_else(|_| Err(TIMED_OUT.into())),
Err(e) => Err(e),
}
};
write_with(&state, rec, &bot.name, ask).await;
}
+/// What [`write`]'s turn returns when it ran out of time.
+pub const TIMED_OUT: &str = "the draft took longer than 10 minutes";
+/// What a turn returns when the person pressed Stop on the bot (`turn_once`'s cancel token).
+const STOPPED_BY_USER: &str = "stopped by the user";
+
+/// S-F9 (Mira, copy.md): `write_error` when the drafting turn failed. The banner already leads with
+/// "**{bot} couldn't write the skill.**" and ends with "Your steps are kept until {day}, so try
+/// again.", so this never repeats the lead and never carries the engine's own words.
+pub const WRITE_TIMED_OUT: &str = "Writing took longer than 10 minutes, so kwant bots stopped it.";
+pub const WRITE_STOPPED: &str = "You stopped it before the draft was done.";
+pub const WRITE_SPEND_STOP: &str = "Today's spending stop was on, so it didn't start. Press Continue today in Needs you first.";
+const CHECK_SIGN_IN: &str = "Check that it's signed in under Settings › This space › Accounts.";
+
+/// The engine as the review's lock note names it, when Write goes to exactly one engine
+/// ([`super::engine_for`] gives one id, or several joined by " or ").
+fn one_engine_name(engine: Option<&str>) -> Option<&'static str> {
+ match engine? {
+ "claude" => Some("Claude"),
+ "codex" => Some("Codex"),
+ "grok" => Some("Grok"),
+ "custom" => Some("Custom API"),
+ _ => None,
+ }
+}
+
+/// The banner's sentence for a drafting turn that failed with `err` (S-F9's four cases, and the
+/// "run with no tools" note). `engine` is what [`super::engine_for`] says for the bot.
+pub fn failed_turn_reason(err: &str, bot_name: &str, engine: Option<&str>) -> String {
+ let err = err.trim();
+ let engine = one_engine_name(engine).unwrap_or("Its engine");
+ if err == TIMED_OUT {
+ WRITE_TIMED_OUT.into()
+ } else if err == STOPPED_BY_USER {
+ WRITE_STOPPED.into()
+ } else if crate::server::spend_stop::is_stop_error(err) {
+ WRITE_SPEND_STOP.into()
+ } else if err.contains("run with no tools") {
+ format!("{engine} can't write with every tool switched off. Turn on one tool for {bot_name}, or give {bot_name} another engine.")
+ } else {
+ format!("{engine} stopped with an error before the draft was done. {CHECK_SIGN_IN}")
+ }
+}
+
/// [`write`] with `ask` in place of the turn (tests give a canned reply).
pub async fn write_with<F, Fut>(state: &AppState, rec: Recording, bot_name: &str, mut ask: F)
where
@@ -360,17 +422,17 @@ where
break;
}
Err(why) => {
- last = Some(why.clone());
- result = Err(why);
+ // the check's own words go back to the engine; the person gets a sentence
+ result = Err(shown_reason(&why).to_string());
+ last = Some(why);
}
},
Err(e) => {
+ // The engine's own words stay in the log, as before; the banner gets a sentence (S-F9)
let first: String = e.lines().next().unwrap_or(&e).chars().take(300).collect();
- result = Err(if e.contains("run with no tools") {
- format!("{bot_name}'s engine can't run a turn with every tool switched off, so the skill wasn't written.")
- } else {
- format!("{bot_name} couldn't write the skill: {first}")
- });
+ tracing::info!(recording = %id, "show it once: the drafting turn failed: {first}");
+ let engine = super::engine_for(state, &rec.kwant_id).await;
+ result = Err(failed_turn_reason(&e, bot_name, engine.as_deref()));
// A failed turn isn't a bad reply: no retry
break;
}
@@ -534,6 +596,77 @@ mod tests {
}
}
+ /// S-F9: one sentence per way the drafting turn can fail; none repeats the banner's lead or
+ /// carries the engine's text.
+ #[test]
+ fn a_failed_turn_gets_one_of_miras_sentences_never_the_engines_words() {
+ let no_lead = |s: &str| {
+ assert!(!s.contains("couldn't write the skill"), "repeats the lead: {s}");
+ assert!(!s.contains(':'), "no engine text after a colon: {s}");
+ // the app names itself "kwant bots" wherever the person reads it, never a bare "kwant"
+ assert!(!s.replace("kwant bots", "").contains("kwant"), "a bare kwant: {s}");
+ };
+ // 1 · the 10-minute timeout
+ let s = failed_turn_reason(TIMED_OUT, "Rook", Some("claude"));
+ assert_eq!(s, "Writing took longer than 10 minutes, so kwant bots stopped it.");
+ no_lead(&s);
+ // 2 · the person pressed Stop
+ let s = failed_turn_reason("stopped by the user", "Rook", Some("claude"));
+ assert_eq!(s, "You stopped it before the draft was done.");
+ no_lead(&s);
+ // 3 · the spend stop, whatever its details say
+ let s = failed_turn_reason("spend_stopped: 120k of 100k tokens today, until 00:00 CET", "Rook", Some("codex"));
+ assert_eq!(s, "Today's spending stop was on, so it didn't start. Press Continue today in Needs you first.");
+ assert!(!s.contains("120k"), "no amounts: {s}");
+ no_lead(&s);
+ // 4 · anything else: the engine's name, never its words
+ let raw = "Error: 401 Unauthorized: OAuth token has expired at /home/someone/.claude";
+ let s = failed_turn_reason(raw, "Rook", Some("claude"));
+ assert_eq!(s, "Claude stopped with an error before the draft was done. Check that it's signed in under Settings › This space › Accounts.");
+ assert!(!s.contains("401") && !s.contains("OAuth") && !s.contains("/home"), "{s}");
+ no_lead(&s);
+ assert!(failed_turn_reason(raw, "Rook", Some("grok")).starts_with("Grok stopped with an error"));
+ assert!(failed_turn_reason(raw, "Rook", Some("codex")).starts_with("Codex stopped with an error"));
+ }
+
+ /// S-F9 case 4's fallback: no single engine (several, none, or an unknown id) says "Its engine".
+ #[test]
+ fn a_failed_turn_without_one_engine_says_its_engine() {
+ let want = "Its engine stopped with an error before the draft was done. Check that it's signed in under Settings › This space › Accounts.";
+ for engine in [None, Some("claude or codex"), Some("something-new")] {
+ assert_eq!(failed_turn_reason("boom", "Rook", engine), want, "{engine:?}");
+ }
+ }
+
+ /// Mira's note: the "run with no tools" failure names the engine and the fix, not the lead.
+ #[test]
+ fn a_turn_with_every_tool_off_names_the_fix() {
+ let e = "the engine can't run with no tools here";
+ assert_eq!(
+ failed_turn_reason(e, "Rook", Some("grok")),
+ "Grok can't write with every tool switched off. Turn on one tool for Rook, or give Rook another engine."
+ );
+ assert!(failed_turn_reason(e, "Rook", None).starts_with("Its engine can't write with every tool switched off."));
+ }
+
+ #[test]
+ fn the_person_sees_a_sentence_for_a_failed_check_never_the_check() {
+ // a page step, a click and a note have nothing typed: Mira's sentence (S-F3)
+ for n in [1, 4, 5] {
+ let e = parse(&reply(json!([{"name": "x", "description": "d", "from_step": n}])), &steps()).unwrap_err();
+ assert_eq!(shown_reason(&e), SHOWN_NOTHING_TYPED, "{n}: {e}");
+ }
+ // a masked step, a step that isn't there, and every other check: the fallback
+ for n in [2, 9] {
+ let e = parse(&reply(json!([{"name": "x", "description": "d", "from_step": n}])), &steps()).unwrap_err();
+ assert_eq!(shown_reason(&e), SHOWN_DRAFT_MISMATCH, "{n}: {e}");
+ }
+ assert_eq!(shown_reason(&parse("Sure! Here is your skill.", &steps()).unwrap_err()), SHOWN_DRAFT_MISMATCH);
+ assert_eq!(shown_reason("input 1's name must be 1 to 40 lowercase letters"), SHOWN_DRAFT_MISMATCH);
+ assert_eq!(SHOWN_NOTHING_TYPED, "Its draft took a value from a step where nothing was typed.");
+ assert_eq!(SHOWN_DRAFT_MISMATCH, "Its draft didn't match your recorded steps.");
+ }
+
#[test]
fn duplicate_input_names_get_numbered() {
let i = json!([
diff --git a/src/server/show_once/recorder.js b/src/server/show_once/recorder.js
index b6441ebd..ce075474 100644
--- a/src/server/show_once/recorder.js
+++ b/src/server/show_once/recorder.js
@@ -106,6 +106,15 @@
return out;
} });
+ // The person is leaving by kwnt's own address bar or back/forward (S-F5): no blur reaches the
+ // page then, so kwnt's server calls this first, in this world only. Each pending edit is posted
+ // through the binding as a `type` step like a blur would (same facts, same mask); the count.
+ Object.defineProperty(globalThis, '__kwntRecorderCommit', { value: function () {
+ var n = dirty.size;
+ commitAll();
+ return n;
+ } });
+
// a show-password toggle keeps the field masked for good
new MutationObserver(function (list) {
list.forEach(function (r) { if (String(r.oldValue).toLowerCase() === 'password') everPassword.add(r.target); });
diff --git a/src/server/show_once/scrub.rs b/src/server/show_once/scrub.rs
index 2fa043e0..2fce574a 100644
--- a/src/server/show_once/scrub.rs
+++ b/src/server/show_once/scrub.rs
@@ -1,7 +1,8 @@
//! What a recorded step keeps of a page address (decisions.md Q-S1): the origin and the path,
//! without the query, the fragment or any user:password, and with every path segment that looks
//! like an id or a token (a run of 20 or more base64url characters, which covers hex) replaced
-//! by "…".
+//! by "…". A long run that is a readable slug, lowercase words joined by hyphens such as
+//! `how-to-export-your-orders`, is kept (S-F6): see [`is_slug`].
/// Where a step happened.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -29,20 +30,65 @@ pub fn scrub(raw: &str) -> Option<PageAt> {
Some(PageAt { origin, path: cut(&path, MAX_PATH_CHARS) })
}
-/// A segment, or "…" when it has a token-like run.
+/// A segment, or "…" when it has a token-like run: a run of [`TOKEN_RUN`] or more
+/// `[A-Za-z0-9_-]` characters that isn't a readable slug ([`is_slug`]).
pub fn scrub_segment(seg: &str) -> String {
- let mut run = 0usize;
- for c in seg.chars() {
- if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
- run += 1;
- if run >= TOKEN_RUN {
- return "…".into();
+ let token = seg
+ .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
+ .any(|run| run.len() >= TOKEN_RUN && !is_slug(run));
+ if token {
+ "…".into()
+ } else {
+ seg.to_string()
+ }
+}
+
+/// Longest word in a readable slug.
+pub const SLUG_WORD: usize = 16;
+/// Most consonants in a row in a slug's word (`strengths` has five and isn't kept: safe).
+pub const SLUG_CONSONANTS: usize = 4;
+/// Longest number in a readable slug (a year, an issue number).
+pub const SLUG_NUMBER: usize = 4;
+
+/// Whether a run reads as words joined by hyphens (`quarterly-report-for-2025`) rather than an
+/// id or a token: two or more parts split by single hyphens, each either lowercase letters (at
+/// most [`SLUG_WORD`], and once longer than three with a vowel and no more than
+/// [`SLUG_CONSONANTS`] consonants in a row) or digits (at most
+/// [`SLUG_NUMBER`]), and not only numbers. Anything with an uppercase letter, an underscore,
+/// letters and digits in one part, a long number or a long consonant run is not: that covers
+/// base64url, hex, uuids and most random ids. A token made of real words (`correct-horse-…`)
+/// reads as a slug and is kept; it's indistinguishable from one by its look.
+pub fn is_slug(run: &str) -> bool {
+ let parts: Vec<&str> = run.split('-').collect();
+ if parts.len() < 2 {
+ return false;
+ }
+ let mut words = 0;
+ for part in &parts {
+ let letters = !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase());
+ let digits = !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
+ if letters {
+ if part.len() > SLUG_WORD || (part.len() > 3 && !reads_as_a_word(part)) {
+ return false;
}
- } else {
- run = 0;
+ words += 1;
+ } else if !(digits && part.len() <= SLUG_NUMBER) {
+ return false;
}
}
- seg.to_string()
+ words > 0
+}
+
+fn reads_as_a_word(word: &str) -> bool {
+ let vowel = |b: u8| b"aeiouy".contains(&b);
+ let mut run = 0;
+ for b in word.bytes() {
+ run = if vowel(b) { 0 } else { run + 1 };
+ if run > SLUG_CONSONANTS {
+ return false;
+ }
+ }
+ word.bytes().any(vowel)
}
fn cut(s: &str, max: usize) -> String {
@@ -104,6 +150,55 @@ mod tests {
assert_eq!(at("https://a.example/reset.AbCdEfGhIjKlMnOpQrStUv.html"), pair("https://a.example", "/…"));
}
+ #[test]
+ fn readable_slugs_are_kept_but_tokens_are_not() {
+ // S-F6: words joined by hyphens stay readable, however long
+ for slug in [
+ "how-to-export-your-orders",
+ "quarterly-report-for-2025",
+ "annual-sales-summary",
+ "help/articles/reset-your-two-factor-settings",
+ ] {
+ assert_eq!(at(&format!("https://a.example/{slug}")), pair("https://a.example", &format!("/{slug}")), "{slug}");
+ }
+ // with a readable slug next to a token in the same address, only the token goes
+ assert_eq!(
+ at("https://a.example/blog/how-to-export-your-orders/AbCdEfGhIjKlMnOpQrSt"),
+ pair("https://a.example", "/blog/how-to-export-your-orders/…")
+ );
+ // Rigel's reset link (Q-S1(f)): the token is still scrubbed
+ for token in [
+ "Zx9fK2LmQp4RtV8wYb3NcD7e",
+ "0f3a9c27e1b84d6f9a2c5e7b",
+ "9c1f6e2a-4b7d-4e3a-8f5c-0d2b6a9e1c74",
+ "k3j4h5g6-f7d8s9a0-q1w2e3r4",
+ "abcdefgh-ijklmnop-qrstuvwx",
+ "xkcd-qwrtzp-plmnbv-zxcvbn",
+ "reset-token-0f3a9c27e1b84d6f9a2c",
+ "Reset-Your-Password-Today",
+ "reset_your_password_today",
+ "abc--defghijklmnopqrstu",
+ "2024-11-07-1234-5678",
+ ] {
+ assert_eq!(at(&format!("https://a.example/account/reset/{token}")), pair("https://a.example", "/account/reset/…"), "{token}");
+ }
+ }
+
+ #[test]
+ fn what_counts_as_a_slug() {
+ assert!(is_slug("how-to-export-your-orders"));
+ assert!(is_slug("report-2025"));
+ assert!(is_slug("q-and-a"));
+ assert!(!is_slug("orders"), "one word has no hyphen");
+ assert!(!is_slug("2024-11-07"), "only numbers");
+ assert!(!is_slug("report-20251107"), "a long number");
+ assert!(!is_slug("report-v2"), "letters and digits in one part");
+ assert!(!is_slug("verylongwordthatkeepsgoing-on"), "a word over 16 letters");
+ assert!(!is_slug("bcdf-report"), "no vowel");
+ assert!(!is_slug("ijklmnop-report"), "five consonants in a row");
+ assert!(!is_slug("-report-x"), "an empty part");
+ }
+
#[test]
fn dotted_segments_are_kept_while_each_part_is_short() {
assert_eq!(at("https://a.example/files/report.csv"), pair("https://a.example", "/files/report.csv"));
diff --git a/src/server/show_once/stage.rs b/src/server/show_once/stage.rs
index 4160377d..1f789570 100644
--- a/src/server/show_once/stage.rs
+++ b/src/server/show_once/stage.rs
@@ -150,11 +150,14 @@ pub struct StageRecorder {
/// Start opened a `start_url` that hasn't loaded yet: the page the browser was on before
/// isn't a step, the start page is the first one.
start_pending: bool,
+ /// The page the browser was on when Start opened a `start_url`: the first page step after
+ /// all if the start page can't be opened (S-F1).
+ before_start: Option<String>,
}
impl StageRecorder {
pub fn new(state: AppState, stage: String, socket: u64) -> Self {
- StageRecorder { state, stage, socket, rx: None, live: None, last_page: None, start_pending: false }
+ StageRecorder { state, stage, socket, rx: None, live: None, last_page: None, start_pending: false, before_start: None }
}
/// Whether a recording is live on this socket.
@@ -224,6 +227,7 @@ impl StageRecorder {
// page adds no second page step (a page changed while it was stopped still does)
self.last_page = self.last_page_step(&rec.id).await;
self.start_pending = start_url.is_some();
+ self.before_start = None;
let mut acts = vec![Act::Install, Act::Send(state_frame(&rec))];
if let Some(url) = start_url {
acts.push(Act::Navigate(url));
@@ -252,16 +256,21 @@ impl StageRecorder {
/// Start opens a `start_url` next (B1), whose own load is the first page step.
pub async fn on_installed(&mut self, url: &str) -> Vec<Act> {
if self.start_pending {
+ self.before_start = Some(url.to_string());
return vec![];
}
self.on_navigated(url).await
}
- /// The `start_url` couldn't be opened: the page the browser is on is the first step after all.
+ /// The `start_url` couldn't be opened: the page the browser stays on is the first step after
+ /// all. Chromium usually shows its own error page there (`chrome-error://…`, never recorded),
+ /// so that's the page the browser was on when Start was pressed (S-F1).
pub async fn on_start_failed(&mut self, url: Option<&str>) -> Vec<Act> {
self.start_pending = false;
- match url {
- Some(url) => self.on_navigated(url).await,
+ let before = self.before_start.take();
+ let stays_on = url.filter(|u| scrub::scrub(u).is_some()).map(str::to_string).or(before);
+ match stays_on {
+ Some(url) => self.on_navigated(&url).await,
None => vec![],
}
}
@@ -279,8 +288,18 @@ impl StageRecorder {
/// A top-level page loaded: a `page` step, unless it's the page already recorded.
pub async fn on_navigated(&mut self, url: &str) -> Vec<Act> {
let Some(id) = self.live.clone() else { return vec![] };
- let Some(page) = scrub::scrub(url) else { return vec![] };
+ // the start page landed on Chromium's error page without Page.navigate saying so: the
+ // page before Start is the first step, as in on_start_failed
+ let url = match self.before_start.take() {
+ Some(before) if self.start_pending && url.starts_with("chrome-error:") => before,
+ before => {
+ self.before_start = before;
+ url.to_string()
+ }
+ };
+ let Some(page) = scrub::scrub(&url) else { return vec![] };
self.start_pending = false;
+ self.before_start = None;
let key = (page.origin.clone(), page.path.clone());
if self.last_page.as_ref() == Some(&key) {
return vec![];
diff --git a/src/server/signin.rs b/src/server/signin.rs
index 1680c9f7..3d7ff66a 100644
--- a/src/server/signin.rs
+++ b/src/server/signin.rs
@@ -596,7 +596,7 @@ pub fn qr_lines(text: &str) -> Vec<String> {
/// `kwnt signin-link`: asks the running server (with the API token, from this machine) for a new
/// one-time link and prints it with a QR code.
-pub async fn cli_link(config: &crate::config::Config, url: Option<&str>, qr: bool) -> Result<(), String> {
+pub async fn cli_link(config: &crate::config::Config, url: Option<&str>, qr: bool, bare: bool) -> Result<(), String> {
use super::auth;
let token = auth::env_token()
.map(Ok)
@@ -632,7 +632,8 @@ pub async fn cli_link(config: &crate::config::Config, url: Option<&str>, qr: boo
.and_then(|u| u.split_once("/#").map(|(b, _)| b.to_string()))
});
let link = auth::one_time_link(&config.host, config.port, base.as_deref(), code);
- for line in auth::one_time_notice(&link, qr) {
+ let lines = if bare { auth::bare_notice(&link, qr) } else { auth::one_time_notice(&link, qr) };
+ for line in lines {
println!("{line}");
}
Ok(())
diff --git a/src/server/smart_results/mod.rs b/src/server/smart_results/mod.rs
index 8110d96c..988c9e80 100644
--- a/src/server/smart_results/mod.rs
+++ b/src/server/smart_results/mod.rs
@@ -1,6 +1,6 @@
//! Smart Results (0.6.5): a table or a list in a bot's final reply, kept as one typed block the
//! chat can draw as a chart, a comparison, metric tiles, findings, cards, a checklist, a timeline,
-//! steps or facts. Contract: docs/smart-results.md.
+//! steps, facts or a recipe. Contract: docs/smart-results.md.
//!
//! - The reply's text is never changed. The block set lives beside it in `message_results`,
//! written when the reply is saved ([`crate::db::Database::insert_message_with`]), and every
@@ -18,6 +18,7 @@ mod items;
mod compose;
mod files;
mod present_result;
+mod recipe;
mod selector;
mod validate;
mod verification;
@@ -32,7 +33,7 @@ use serde::{Deserialize, Serialize};
/// The block types this build stores and serves. Taking a type out (a one-line release fallback)
/// stops new blocks of it and hides stored ones (`results: null`); the chat then shows the
/// reply's markdown.
-pub const ENABLED_TYPES: &[&str] = &["chart", "comparison", "metrics", "findings", "cards", "steps", "facts", "verification", "files"];
+pub const ENABLED_TYPES: &[&str] = &["chart", "comparison", "metrics", "findings", "cards", "steps", "facts", "verification", "files", "recipe"];
/// The payload version this build writes and reads.
pub const VERSION: u32 = 1;
/// Largest stored payload, in bytes of JSON.
@@ -48,8 +49,8 @@ pub const PICK_REASON: &str = "named as the pick in this reply";
/// the transposed shape (options as columns, a row per point) is what [`selector`] reads as a
/// comparison. Every header cell must be filled, or the table stays text.
pub const PROMPT_LINE: &str = "When you compare options use a table with every header cell filled (one row per option; for \
- just two, a column each and a row per point), for steps use a numbered list, and for key numbers use '**Label:** value' \
- lines; kwant shows them as cards and charts.";
+ just two, a column each and a row per point), for steps use a numbered list, for a recipe an 'Ingredients' list then \
+ numbered steps, and for key numbers use '**Label:** value' lines; kwant shows them as cards and charts.";
/// The checked block set for a reply: the first candidate, in priority order ([`rank`]), whose
/// type is enabled and that passes [`validate`]; `None` when there isn't one. A selector bug must never
@@ -94,6 +95,7 @@ pub enum Block {
Facts(Facts),
Verification(Verification),
Files(Files),
+ Recipe(Recipe),
}
impl Block {
@@ -109,6 +111,7 @@ impl Block {
Block::Facts(_) => "facts",
Block::Verification(_) => "verification",
Block::Files(_) => "files",
+ Block::Recipe(_) => "recipe",
}
}
@@ -142,6 +145,7 @@ macro_rules! common {
Block::Facts($b) => $e,
Block::Verification($b) => $e,
Block::Files($b) => $e,
+ Block::Recipe($b) => $e,
}
};
}
@@ -151,26 +155,49 @@ use common;
/// chat draws it after the reply; `verification`, `files` and a `present_result` call use it and
/// leave `index` out). `index` counts in the order the chat renders them, from 0: tables in one
/// count, numbered lists in another, bullet lists (`ordered: false`) in a third.
-#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+///
+/// `markdown_section` (`recipe` only) is a run of the reply's top-level blocks: from `lead` blocks
+/// before the list `index`/`ordered` to the list `last_index`/`last_ordered`, both ends included.
+/// The chat draws the block where the run starts and none of the run's own markdown.
+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Source {
- /// `markdown_table`, `markdown_list` or `slot`.
+ /// `markdown_table`, `markdown_list`, `markdown_section` or `slot`.
pub kind: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub index: Option<usize>,
/// Lists only; absent means `true` (v1).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ordered: Option<bool>,
+ /// `markdown_section` only: its last list.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_index: Option<usize>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub last_ordered: Option<bool>,
+ /// `markdown_section` only: top-level blocks just before its first list that belong to it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub lead: Option<usize>,
}
impl Source {
pub fn table(index: usize) -> Self {
- Source { kind: "markdown_table".into(), index: Some(index), ordered: None }
+ Source { kind: "markdown_table".into(), index: Some(index), ..Source::default() }
}
pub fn list(index: usize, ordered: bool) -> Self {
- Source { kind: "markdown_list".into(), index: Some(index), ordered: Some(ordered) }
+ Source { kind: "markdown_list".into(), index: Some(index), ordered: Some(ordered), ..Source::default() }
+ }
+ /// The run from `lead` blocks before list `first` to list `last` (index, ordered).
+ pub fn section(first: (usize, bool), last: (usize, bool), lead: usize) -> Self {
+ Source {
+ kind: "markdown_section".into(),
+ index: Some(first.0),
+ ordered: Some(first.1),
+ last_index: Some(last.0),
+ last_ordered: Some(last.1),
+ lead: Some(lead),
+ }
}
pub fn slot() -> Self {
- Source { kind: "slot".into(), index: None, ordered: None }
+ Source { kind: "slot".into(), ..Source::default() }
}
}
@@ -518,3 +545,60 @@ pub struct Files {
pub provenance: Provenance,
pub items: Vec<FileItem>,
}
+
+/// A time of a recipe in the reply's own words: "Prep" and "15 min".
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct RecipeTime {
+ pub label: String,
+ pub text: String,
+}
+
+/// One ingredient line. `qty` is its leading amount exactly as written ("2 cups", "½", "1–2") and
+/// `text` the rest, so the line is `text` alone without a `qty`, `qty + text` when `text` starts
+/// with ",", and `qty + " " + text` otherwise. `group` is the sub-heading above it ("For the sauce").
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Ingredient {
+ pub id: String,
+ pub text: String,
+ #[serde(default)]
+ pub qty: Option<String>,
+ #[serde(default)]
+ pub group: Option<String>,
+}
+
+impl Ingredient {
+ /// The line as the reply wrote it.
+ pub fn line(&self) -> String {
+ match &self.qty {
+ None => self.text.clone(),
+ Some(q) if self.text.starts_with(',') => format!("{q}{}", self.text),
+ Some(q) => format!("{q} {}", self.text),
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct RecipeStep {
+ pub id: String,
+ pub text: String,
+}
+
+/// One recipe: 2–40 ingredients and 2–30 steps, with servings, up to 3 times and up to 6 notes
+/// when the reply gives them. `title` is the dish name. Its source is the `markdown_section` the
+/// recipe fills, from the dish heading to its last list.
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct Recipe {
+ pub id: String,
+ #[serde(default)]
+ pub title: Option<String>,
+ pub source: Source,
+ #[serde(default)]
+ pub serves: Option<u32>,
+ #[serde(default)]
+ pub times: Vec<RecipeTime>,
+ pub ingredients: Vec<Ingredient>,
+ pub steps: Vec<RecipeStep>,
+ #[serde(default)]
+ pub notes: Vec<String>,
+ pub provenance: Provenance,
+}
diff --git a/src/server/smart_results/present_result.rs b/src/server/smart_results/present_result.rs
index ab5fc8af..2831fdc7 100644
--- a/src/server/smart_results/present_result.rs
+++ b/src/server/smart_results/present_result.rs
@@ -8,6 +8,9 @@
//! `source` is refused);
//! - `steps` must name the numbered list of the reply they stand for (`source`) and be all of it:
//! the same items in the same order (a task list is never declared as steps);
+//! - a `recipe` needs no `source`: the reply must hold the one recipe the recipe selector reads,
+//! with the same ingredient lines and steps in the same order, and the block stored is the one
+//! read from the reply (so its amounts, groups, servings and times are the reply's own);
//! - every URL is a link in the reply (never plain text, never with a login in it), and nothing is
//! HTML.
//!
@@ -26,8 +29,9 @@ use crate::mcp::SELF_SERVER_NAME;
use crate::server::continuity::SelfScope;
use crate::server::AppState;
+use super::recipe::recipe_of;
use super::selector::{is_task, lists_of, plain, tables_of};
-use super::{Block, Column, Comparison, Provenance, ResultSet, Row, Source, Step, Steps, VERSION};
+use super::{Block, Column, Comparison, Ingredient, Provenance, Recipe, RecipeStep, ResultSet, Row, Source, Step, Steps, VERSION};
const NAME: &str = "present_result";
/// Largest call, in bytes of JSON; a bigger one is refused at the call.
@@ -40,21 +44,21 @@ pub fn handles(name: &str) -> bool {
pub fn tools() -> Vec<Value> {
vec![json!({
"name": NAME,
- "description": "Optional. Declare the one block kwant should draw for your final reply (a comparison table, a numbered-steps list), only when the answer's data reads better that way than as plain text; never for a simple answer, and never instead of writing the reply. The data must match your reply text exactly: every label, cell, item and link is checked against it, and a call that doesn't match is dropped and the plain reply is shown. For a comparison, `source` is required: the index (from 0) of the table in your reply that it describes. Call it once, just before your final reply. Types today: comparison and steps; kwant draws charts, metrics, facts, cards and findings from your reply's own structure (use '**Label:** value' lines for key numbers).",
+ "description": "Optional. Declare the one block kwant should draw for your final reply (a comparison table, a numbered-steps list), only when the answer's data reads better that way than as plain text; never for a simple answer, and never instead of writing the reply. The data must match your reply text exactly: every label, cell, item and link is checked against it, and a call that doesn't match is dropped and the plain reply is shown. For a comparison, `source` is required: the index (from 0) of the table in your reply that it describes. For a recipe, no `source`: your reply must hold the recipe as an 'Ingredients' list then numbered steps. Call it once, just before your final reply. Types today: comparison, steps and recipe; kwant draws charts, metrics, facts, cards and findings from your reply's own structure (use '**Label:** value' lines for key numbers).",
"inputSchema": {
"type": "object",
"properties": {
- "type": {"type": "string", "enum": ["comparison", "steps"]},
+ "type": {"type": "string", "enum": ["comparison", "steps", "recipe"]},
"title": {"type": "string", "description": "Optional short title."},
"source": {
"type": "object",
- "description": "Which table or numbered list of your reply the block replaces: {kind: 'markdown_table' | 'markdown_list', index: number counted from 0 in the order they appear}. Required for both types.",
+ "description": "Which table or numbered list of your reply the block replaces: {kind: 'markdown_table' | 'markdown_list', index: number counted from 0 in the order they appear}. Required for comparison and steps; leave it out for a recipe.",
"properties": {"kind": {"type": "string", "enum": ["markdown_table", "markdown_list"]}, "index": {"type": "integer", "minimum": 0}},
"required": ["kind", "index"],
},
"data": {
"type": "object",
- "description": "comparison: {columns: [{label, numeric?, unit?}], rows: [{cells: [string, ...]}]}, 3-50 rows and 2-8 columns, every header and cell exactly as in your table: all of its rows and columns, in its order. steps: {items: [string, ...]}, 3-15 items: all the items of that list, in its order.",
+ "description": "comparison: {columns: [{label, numeric?, unit?}], rows: [{cells: [string, ...]}]}, 3-50 rows and 2-8 columns, every header and cell exactly as in your table: all of its rows and columns, in its order. steps: {items: [string, ...]}, 3-15 items: all the items of that list, in its order. recipe: {ingredients: [string, ...], steps: [string, ...]}, 2-40 ingredient lines and 2-30 steps, each exactly as in your reply, in its order.",
},
},
"required": ["type", "data"],
@@ -112,6 +116,13 @@ fn declared(args: &Value) -> Result<Declared, String> {
}
let kind = args.get("type").and_then(Value::as_str).ok_or("`type` is missing")?;
let data = args.get("data").filter(|d| d.is_object()).ok_or("`data` is missing")?;
+ if kind == "recipe" {
+ // Where it goes is read from the reply itself, never from the call
+ let block = recipe(data)?;
+ let set = ResultSet { version: VERSION, blocks: vec![block.clone()] };
+ super::validate(&set, None).map_err(|why| format!("the block doesn't fit ({why})"))?;
+ return Ok(Declared { block, source: None });
+ }
let source = match args.get("source") {
None | Some(Value::Null) => None,
Some(s) => {
@@ -185,7 +196,7 @@ fn comparison(data: &Value, source: Option<(bool, usize)>) -> Result<Block, Stri
Ok(Block::Comparison(Comparison {
id: "b0".into(),
title: None,
- source: Source { kind: "markdown_table".into(), index: source.map(|s| s.1), ordered: None },
+ source: Source { kind: "markdown_table".into(), index: source.map(|s| s.1), ..Source::default() },
columns,
rows,
highlight_row: None,
@@ -203,10 +214,40 @@ fn steps(data: &Value, source: Option<(bool, usize)>) -> Result<Block, String> {
.enumerate()
.map(|(k, it)| it.as_str().map(|t| Step { id: format!("s{k}"), text: t.to_string(), done: None, when: None, owner: None }).ok_or("every step must be a string"))
.collect::<Result<Vec<_>, _>>()?;
- let source = Source { kind: "markdown_list".into(), index: source.map(|s| s.1), ordered: Some(true) };
+ let source = Source { kind: "markdown_list".into(), index: source.map(|s| s.1), ordered: Some(true), ..Source::default() };
Ok(Block::Steps(Steps { id: "b0".into(), title: None, variant: super::Variant::Steps, source, items, provenance: Provenance::reply_text() }))
}
+/// A declared recipe: its ingredient lines (held whole in `text`) and steps. The block that is
+/// stored is the reply's own (see [`ground`]); this one only carries what to match.
+fn recipe(data: &Value) -> Result<Block, String> {
+ let strings = |key: &str| -> Result<Vec<String>, String> {
+ data.get(key)
+ .and_then(Value::as_array)
+ .ok_or(format!("`data.{key}` is missing"))?
+ .iter()
+ .map(|v| v.as_str().map(str::to_string).ok_or(format!("every one of `data.{key}` must be a string")))
+ .collect()
+ };
+ let ingredients = strings("ingredients")?
+ .into_iter()
+ .enumerate()
+ .map(|(k, text)| Ingredient { id: format!("i{k}"), text, qty: None, group: None })
+ .collect();
+ let steps = strings("steps")?.into_iter().enumerate().map(|(k, text)| RecipeStep { id: format!("s{k}"), text }).collect();
+ Ok(Block::Recipe(Recipe {
+ id: "b0".into(),
+ title: None,
+ source: Source::section((0, false), (0, true), 0),
+ serves: None,
+ times: Vec::new(),
+ ingredients,
+ steps,
+ notes: Vec::new(),
+ provenance: Provenance::reply_text(),
+ }))
+}
+
/// `declared` held to `reply`, as a block with `bot_declared` provenance, or the reason it isn't.
///
/// A declaration is the whole table (or numbered list) it names, in the same order, because that
@@ -264,6 +305,26 @@ fn ground(declared: Declared, reply: &str, tool_call_id: String) -> Result<Block
}
s.provenance = Provenance::bot_declared(tool_call_id);
}
+ Block::Recipe(declared) => {
+ let mut read = recipe_of(reply).ok_or("the reply has no recipe kwant can read")?;
+ if declared.ingredients.len() != read.ingredients.len() || declared.steps.len() != read.steps.len() {
+ return Err("the ingredients and steps aren't all of the reply's recipe".into());
+ }
+ for (d, r) in declared.ingredients.iter().zip(&read.ingredients) {
+ check_urls(&d.text, &links)?;
+ if !same_cell(&d.text, &r.line()) {
+ return Err("an ingredient isn't the recipe's line at that position".into());
+ }
+ }
+ for (d, r) in declared.steps.iter().zip(&read.steps) {
+ check_urls(&d.text, &links)?;
+ if !same_cell(&d.text, &r.text) {
+ return Err("a step isn't the recipe's step at that position".into());
+ }
+ }
+ read.provenance = Provenance::bot_declared(tool_call_id);
+ return Ok(Block::Recipe(read));
+ }
_ => return Err("not declarable".into()),
}
Ok(block)
diff --git a/src/server/smart_results/present_result_tests.rs b/src/server/smart_results/present_result_tests.rs
index 063db547..37cf0672 100644
--- a/src/server/smart_results/present_result_tests.rs
+++ b/src/server/smart_results/present_result_tests.rs
@@ -62,12 +62,12 @@ fn with(mut args: Value, f: impl FnOnce(&mut Value)) -> Value {
}
#[test]
-fn the_tool_is_offered_with_its_two_types_only() {
+fn the_tool_is_offered_with_its_three_types_only() {
let tools = tools();
assert_eq!(tools.len(), 1);
assert!(handles("present_result") && !handles("share_file"));
let types = &tools[0]["inputSchema"]["properties"]["type"]["enum"];
- assert_eq!(types, &json!(["comparison", "steps"]));
+ assert_eq!(types, &json!(["comparison", "steps", "recipe"]));
}
#[test]
@@ -414,3 +414,44 @@ fn a_declaration_with_the_replys_exact_numbers_is_still_accepted() {
"rows": [{"cells": ["Basic", "5"]}, {"cells": ["Team", "9"]}, {"cells": ["Business", "7"]}]}});
assert!(pick(reply, args).is_some());
}
+
+const RECIPE_REPLY: &str = "Try this.\n\n## Pancakes\n\n### Ingredients\n- 1 cup flour\n- 2 eggs\n- 1 cup milk\n\n### Method\n1. Whisk everything together.\n2. Cook ladlefuls in a hot pan.\n\nWant a vegan version?\n";
+
+fn recipe_args(ingredients: &[&str], steps: &[&str]) -> Value {
+ json!({"type": "recipe", "data": {"ingredients": ingredients, "steps": steps}})
+}
+
+#[test]
+fn a_recipe_grounds_as_the_reply_s_own_recipe() {
+ let args = recipe_args(&["1 cup flour", "2 eggs", "1 cup milk"], &["Whisk everything together.", "Cook ladlefuls in a hot pan."]);
+ let Some(Block::Recipe(r)) = pick(RECIPE_REPLY, args) else { panic!("no recipe") };
+ assert_eq!(r.provenance, Provenance::bot_declared("t1".into()));
+ let Some(Block::Recipe(read)) = crate::server::smart_results::compute(RECIPE_REPLY).map(|s| s.blocks[0].clone()) else { panic!() };
+ assert_eq!(Recipe { provenance: r.provenance.clone(), ..read }, r);
+ assert_eq!(r.title.as_deref(), Some("Pancakes"));
+}
+
+#[test]
+fn a_recipe_that_differs_from_the_reply_does_not_ground() {
+ let steps = ["Whisk everything together.", "Cook ladlefuls in a hot pan."];
+ for ingredients in [
+ &["1 cup flour", "3 eggs", "1 cup milk"][..],
+ &["1 cup flour", "1 cup milk", "2 eggs"][..],
+ &["1 cup flour", "2 eggs"][..],
+ &["1 cup flour", "2 eggs", "1 cup milk", "Salt"][..],
+ ] {
+ assert!(pick(RECIPE_REPLY, recipe_args(ingredients, &steps)).is_none(), "{ingredients:?}");
+ }
+ let ingredients = ["1 cup flour", "2 eggs", "1 cup milk"];
+ assert!(pick(RECIPE_REPLY, recipe_args(&ingredients, &["Whisk.", "Cook ladlefuls in a hot pan."])).is_none());
+ assert!(pick(RECIPE_REPLY, recipe_args(&ingredients, &steps[..1])).is_none());
+}
+
+#[test]
+fn a_recipe_needs_one_in_the_reply() {
+ let args = recipe_args(&["1 cup flour", "2 eggs"], &["Whisk everything together.", "Cook ladlefuls in a hot pan."]);
+ assert!(pick("You need 1 cup flour and 2 eggs. Whisk everything together, then cook.\n", args.clone()).is_none());
+ assert!(pick(STEPS_REPLY, args).is_none());
+ assert!(declared(&json!({"type": "recipe", "data": {"ingredients": ["<b>x</b>", "y"], "steps": ["a", "b"]}})).is_err());
+ assert!(declared(&json!({"type": "recipe", "data": {"ingredients": "x", "steps": []}})).is_err());
+}
diff --git a/src/server/smart_results/recipe.rs b/src/server/smart_results/recipe.rs
new file mode 100644
index 00000000..45ab946b
--- /dev/null
+++ b/src/server/smart_results/recipe.rs
@@ -0,0 +1,671 @@
+//! The recipe selector: one recipe in a reply, read as a `recipe` block whose source is the run of
+//! top-level blocks it fills, from the dish heading to its last list.
+//!
+//! It reads only the shape bots write: an optional dish heading and Serves/Prep line, an
+//! "Ingredients" heading (or line), one or more bullet lists (each optionally under a group label
+//! like "For the sauce:"), then the method (a numbered list, or a list under Method / Instructions
+//! / Steps / Directions / Preparation), then optional Notes / Tips. Every block of that run must
+//! be one of these; anything else between, or more than one recipe in the reply, and there is no
+//! block. Contract: docs/smart-results.md.
+
+use super::selector::{is_task, parse, words, Doc, List, Top};
+use super::validate::{has_html, utf16_len};
+use super::{Ingredient, Provenance, Recipe, RecipeStep, RecipeTime, Source, MAX_REPLY};
+
+pub(super) const INGREDIENTS: (usize, usize) = (2, 40);
+pub(super) const STEPS: (usize, usize) = (2, 30);
+pub(super) const MAX_NOTES: usize = 6;
+pub(super) const MAX_TIMES: usize = 3;
+pub(super) const SERVES: (u32, u32) = (1, 24);
+pub(super) const MAX_LEAD: usize = 12;
+pub(super) const TITLE_MAX: usize = 300;
+pub(super) const TIME_LABEL_MAX: usize = 40;
+pub(super) const TIME_TEXT_MAX: usize = 60;
+pub(super) const INGREDIENT_MAX: usize = 300;
+pub(super) const QTY_MAX: usize = 40;
+pub(super) const GROUP_MAX: usize = 100;
+pub(super) const STEP_MAX: usize = 600;
+pub(super) const NOTE_MAX: usize = 600;
+
+/// The fraction glyphs an amount may use (design.md §3, `scaleQty`'s `LEAD`).
+pub(super) const GLYPHS: [char; 6] = ['¼', '½', '¾', '⅓', '⅔', '⅛'];
+
+/// The reply's one recipe, as [`recipe`] reads it (for grounding a `present_result` call).
+pub fn recipe_of(text: &str) -> Option<Recipe> {
+ if text.len() > MAX_REPLY {
+ return None;
+ }
+ recipe(&parse(text)).map(|(_, r)| r)
+}
+
+/// The reply's one recipe and the line its section starts on.
+pub(super) fn recipe(doc: &Doc) -> Option<(usize, Recipe)> {
+ // Exactly one ingredients cue, and at most one method cue, in the whole reply
+ let mut cue = None;
+ let mut cues = 0;
+ let mut methods = 0;
+ for k in 0..doc.blocks.len() {
+ if let Some(c) = ingredients_cue(doc, k) {
+ cues += 1;
+ cue = Some((k, c));
+ }
+ if label_at(doc, k).is_some_and(|t| is_method(label(t))) {
+ methods += 1;
+ }
+ }
+ if cues != 1 || methods > 1 {
+ return None;
+ }
+ let (c, cue) = cue?;
+ let mut meta = Meta::default();
+ let mut title = None;
+ // Where the section starts, and where the walk forward from the cue does
+ let (start, mut k) = match cue {
+ Cue::Unplaceable => return None,
+ // "Here's what you'll need for the ingredients:" stays text; the section starts at its list
+ Cue::Intro => (c + 1, c + 1),
+ Cue::Exact(serves) => {
+ meta.serve(serves)?;
+ // Back from the cue: Serves/Prep lines, then the dish heading
+ let mut start = c;
+ while start > 0 && meta_at(doc, start - 1, true).is_some() {
+ start -= 1;
+ }
+ for j in start..c {
+ meta.merge(meta_at(doc, j, true)?)?;
+ }
+ if start > 0 {
+ if let Some(t) = title_at(doc, start - 1) {
+ title = Some(t);
+ start -= 1;
+ }
+ }
+ // Forward: a Serves/Prep line right under the cue
+ let mut k = c + 1;
+ if let Some(m) = meta_at(doc, k, false) {
+ meta.merge(m)?;
+ k += 1;
+ }
+ (start, k)
+ }
+ };
+ // The ingredient lists, each under an optional group label
+ let mut groups: Vec<(Option<&str>, &List)> = Vec::new();
+ loop {
+ if let Some(l) = bullets_at(doc, k) {
+ groups.push((None, l));
+ k += 1;
+ continue;
+ }
+ match (label_at(doc, k).filter(|t| is_group(doc, k, t)), bullets_at(doc, k + 1)) {
+ (Some(t), Some(l)) => {
+ groups.push((Some(label(t)), l));
+ k += 2;
+ }
+ _ => break,
+ }
+ }
+ if groups.is_empty() {
+ return None;
+ }
+ // The method: a list under a method cue, a numbered list under a one-line intro, or a
+ // numbered list straight after the ingredients
+ let (method, at) = match (label_at(doc, k), list_at(doc, k), list_at(doc, k + 1)) {
+ (Some(t), _, Some(l)) if is_method(label(t)) => (l, k + 1),
+ (Some(t), _, Some(l)) if l.ordered && is_step_intro(doc, k, t) => (l, k + 1),
+ (_, Some(l), _) if l.ordered => (l, k),
+ _ => return None,
+ };
+ let mut end = at;
+ let k = at + 1;
+ // A second list right after the method (a split method, more steps): not one card
+ if list_at(doc, k).is_some() {
+ return None;
+ }
+ let mut notes: Option<&List> = None;
+ if let (Some(t), Some(l)) = (label_at(doc, k), list_at(doc, k + 1)) {
+ if is_notes(label(t)) && (1..=MAX_NOTES).contains(&l.items.len()) {
+ notes = Some(l);
+ end = k + 1;
+ } else if l.ordered {
+ // "For the sauce:" then more numbered steps
+ return None;
+ }
+ }
+ // Every list of the section reads the same in the chat, and nothing up to its end is uncertain
+ let section = &doc.blocks[start..=end];
+ let lists: Vec<&List> = section
+ .iter()
+ .filter_map(|b| match b {
+ Top::List(n) => Some(&doc.lists[*n]),
+ _ => None,
+ })
+ .collect();
+ if lists.iter().any(|l| !l.clean || l.start >= doc.list_unsure_at(l.ordered)) {
+ return None;
+ }
+ let after = doc.starts.get(end + 1).copied().unwrap_or(doc.lines.len());
+ if doc.unsure_at() < after {
+ return None;
+ }
+ let lead = section.iter().position(|b| matches!(b, Top::List(_)))?;
+ if lead > MAX_LEAD {
+ return None;
+ }
+ let (head, tail) = (lists[0], lists[lists.len() - 1]);
+ // Another ingredients-then-numbered-list pair outside the section: a second dish
+ if second_pair(doc, start, end) {
+ return None;
+ }
+ // A plan by day or meal is not a method
+ if method.items.iter().filter(|t| plan_like(t)).count() >= 2 {
+ return None;
+ }
+
+ let mut ingredients = Vec::new();
+ for (group, l) in &groups {
+ for item in &l.items {
+ let (qty, text) = split_qty(strip_task(item));
+ ingredients.push(Ingredient {
+ id: format!("i{}", ingredients.len()),
+ text: text.to_string(),
+ qty: qty.map(str::to_string),
+ group: group.map(str::to_string),
+ });
+ }
+ }
+ let steps = method.items.iter().enumerate().map(|(n, t)| RecipeStep { id: format!("s{n}"), text: t.to_string() });
+ let r = Recipe {
+ id: "b0".into(),
+ title: title.map(str::to_string),
+ source: Source::section((head.index, head.ordered), (tail.index, tail.ordered), lead),
+ serves: meta.serves,
+ times: meta.times.iter().map(|(l, t)| RecipeTime { label: l.to_string(), text: t.to_string() }).collect(),
+ ingredients,
+ steps: steps.collect(),
+ notes: notes.map(|l| l.items.iter().map(|t| strip_task(t).to_string()).collect()).unwrap_or_default(),
+ provenance: Provenance::reply_text(),
+ };
+ fits(&r).then_some((doc.starts[start], r))
+}
+
+/// Within the contract's limits (the ones `validate` checks), so a reply past one stays text
+/// rather than becoming a refused block.
+fn fits(r: &Recipe) -> bool {
+ let within = |s: &str, max: usize| !s.trim().is_empty() && utf16_len(s) <= max && !has_html(s);
+ (INGREDIENTS.0..=INGREDIENTS.1).contains(&r.ingredients.len())
+ && (STEPS.0..=STEPS.1).contains(&r.steps.len())
+ && r.notes.len() <= MAX_NOTES
+ && r.times.len() <= MAX_TIMES
+ && r.title.as_deref().is_none_or(|t| within(t, TITLE_MAX))
+ && r.times.iter().all(|t| within(&t.label, TIME_LABEL_MAX) && within(&t.text, TIME_TEXT_MAX))
+ && r.ingredients.iter().all(|i| {
+ within(&i.text, INGREDIENT_MAX)
+ && i.qty.as_deref().is_none_or(|q| within(q, QTY_MAX))
+ && i.group.as_deref().is_none_or(|g| within(g, GROUP_MAX))
+ })
+ && r.steps.iter().all(|s| within(&s.text, STEP_MAX))
+ && r.notes.iter().all(|n| within(n, NOTE_MAX))
+}
+
+// The blocks of a section
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Cue {
+ /// "Ingredients", alone or with a servings count ("Ingredients (serves 4)", "Ingredients for 4").
+ Exact(Option<u32>),
+ /// A one-line intro ending in ":" that names the ingredients, right before a bullet list.
+ Intro,
+ /// A heading or label that mentions ingredients some other way ("## Ingredients and method"):
+ /// it counts as the reply's cue, but this reader doesn't place it.
+ Unplaceable,
+}
+
+fn ingredients_cue(doc: &Doc, k: usize) -> Option<Cue> {
+ let t = label_at(doc, k)?;
+ let l = label(t);
+ let lower = l.to_lowercase();
+ if matches!(lower.as_str(), "ingredients" | "ingredient list" | "ingredients list") {
+ return Some(Cue::Exact(None));
+ }
+ if let Some(rest) = lower.strip_prefix("ingredients") {
+ let rest = rest.trim();
+ let rest = rest.strip_prefix('(').and_then(|r| r.strip_suffix(')')).unwrap_or(rest);
+ if let Some(n) = serves_in(rest) {
+ return Some(Cue::Exact(Some(n)));
+ }
+ }
+ if !words(l).iter().any(|w| w == "ingredients" || w == "ingredient") {
+ return None;
+ }
+ let one_line_para = matches!(doc.blocks[k], Top::Para { .. });
+ if one_line_para && ends_with_colon(t) && bullets_at(doc, k + 1).is_some() {
+ return Some(Cue::Intro);
+ }
+ if matches!(doc.blocks[k], Top::Heading(_)) || emphasised(t) || ends_with_colon(t) {
+ return Some(Cue::Unplaceable);
+ }
+ None
+}
+
+/// A heading's text, or a one-line paragraph's line.
+fn label_at<'a>(doc: &Doc<'a>, k: usize) -> Option<&'a str> {
+ match doc.blocks.get(k)? {
+ Top::Heading(h) => Some(h),
+ Top::Para { start, end } if start == end => Some(doc.lines[*start].trim()),
+ _ => None,
+ }
+}
+
+fn list_at<'d>(doc: &'d Doc, k: usize) -> Option<&'d List<'d>> {
+ match doc.blocks.get(k)? {
+ Top::List(n) => Some(&doc.lists[*n]),
+ _ => None,
+ }
+}
+
+fn bullets_at<'d>(doc: &'d Doc, k: usize) -> Option<&'d List<'d>> {
+ list_at(doc, k).filter(|l| !l.ordered)
+}
+
+/// `t` without wrapping emphasis or a trailing ":": "**For the sauce:**" → "For the sauce".
+pub(super) fn label(t: &str) -> &str {
+ let mut s = t.trim();
+ loop {
+ let before = s;
+ s = s.strip_suffix(':').unwrap_or(s).trim_end();
+ for w in ["**", "__", "*", "_"] {
+ if s.len() > 2 * w.len() && s.starts_with(w) && s.ends_with(w) {
+ s = s[w.len()..s.len() - w.len()].trim();
+ break;
+ }
+ }
+ if s == before {
+ return s;
+ }
+ }
+}
+
+/// Wrapped in `**`/`__` (or `*`/`_`) as a whole, a trailing ":" aside.
+fn emphasised(t: &str) -> bool {
+ let s = t.trim();
+ let s = s.strip_suffix(':').unwrap_or(s).trim_end();
+ ["**", "__", "*", "_"].iter().any(|w| s.len() > 2 * w.len() && s.starts_with(w) && s.ends_with(w))
+}
+
+fn ends_with_colon(t: &str) -> bool {
+ t.trim_end().trim_end_matches(['*', '_']).trim_end().ends_with(':')
+}
+
+const METHOD: [&str; 5] = ["method", "instructions", "steps", "directions", "preparation"];
+
+/// "Method", "Instructions:", "**Steps**", "How to make it".
+fn is_method(l: &str) -> bool {
+ let w = words(l);
+ !l.contains(|c: char| c.is_ascii_digit())
+ && (1..=6).contains(&w.len())
+ && (METHOD.contains(&w[0].as_str()) || w.starts_with(&["how".into(), "to".into(), "make".into()]))
+}
+
+/// "Notes", "Tips:", "Cook's notes".
+fn is_notes(l: &str) -> bool {
+ let w = words(l);
+ !l.contains(|c: char| c.is_ascii_digit())
+ && (1..=4).contains(&w.len())
+ && w.iter().any(|w| matches!(w.as_str(), "notes" | "note" | "tips" | "tip"))
+}
+
+/// "Then follow these steps:" before a numbered method.
+fn is_step_intro(doc: &Doc, k: usize, t: &str) -> bool {
+ matches!(doc.blocks[k], Top::Para { .. }) && ends_with_colon(t) && words(t).len() <= 12 && !is_notes(label(t))
+}
+
+/// "For the sauce:", "**Topping**", "### Dressing" over an ingredient list.
+fn is_group(doc: &Doc, k: usize, t: &str) -> bool {
+ let l = label(t);
+ let w = words(l);
+ !l.is_empty()
+ && l.chars().count() <= 60
+ && (matches!(doc.blocks[k], Top::Heading(_)) || ends_with_colon(t) || emphasised(t))
+ && !is_method(l)
+ && !is_notes(l)
+ && !w.iter().any(|w| matches!(w.as_str(), "step" | "steps" | "method" | "instructions" | "directions"))
+ && meta_at(doc, k, false).is_none()
+}
+
+/// The dish name: a heading, or a line in bold, of at most 120 characters.
+fn title_at<'a>(doc: &Doc<'a>, k: usize) -> Option<&'a str> {
+ let t = label_at(doc, k)?;
+ if !matches!(doc.blocks[k], Top::Heading(_)) && !emphasised(t) {
+ return None;
+ }
+ let l = label(t);
+ (!l.is_empty() && l.chars().count() <= 120 && !is_method(l) && !is_notes(l)).then_some(l)
+}
+
+/// A bullet list, then within two blocks a numbered list, both outside `start..=end`.
+fn second_pair(doc: &Doc, start: usize, end: usize) -> bool {
+ let outside = |p: usize| p < start || p > end;
+ (0..doc.blocks.len()).filter(|&p| outside(p)).any(|p| {
+ bullets_at(doc, p).is_some_and(|l| l.items.len() >= 2)
+ && (p + 1..=p + 3).take_while(|&q| outside(q)).any(|q| list_at(doc, q).is_some_and(|l| l.ordered && l.items.len() >= 2))
+ })
+}
+
+const PLAN_WORDS: [&str; 14] = [
+ "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday", "day", "breakfast", "brunch", "lunch",
+ "dinner", "supper", "snack",
+];
+
+fn plan_like(item: &str) -> bool {
+ words(item).first().is_some_and(|w| PLAN_WORDS.contains(&w.as_str()))
+}
+
+fn strip_task(item: &str) -> &str {
+ if is_task(item) {
+ item[3..].trim_start()
+ } else {
+ item
+ }
+}
+
+// Serves and times
+
+#[derive(Default, Debug)]
+struct Meta<'a> {
+ serves: Option<u32>,
+ times: Vec<(&'a str, &'a str)>,
+}
+
+impl<'a> Meta<'a> {
+ /// `None` when it says a different number of servings than before.
+ fn serve(&mut self, n: Option<u32>) -> Option<()> {
+ match (self.serves, n) {
+ (Some(a), Some(b)) if a != b => None,
+ (_, Some(b)) => {
+ self.serves = Some(b);
+ Some(())
+ }
+ _ => Some(()),
+ }
+ }
+ fn merge(&mut self, m: Meta<'a>) -> Option<()> {
+ self.serve(m.serves)?;
+ self.times.extend(m.times);
+ (self.times.len() <= MAX_TIMES).then_some(())
+ }
+}
+
+/// A paragraph (or, `lists` allowed, a list) that says only how many it serves and how long it
+/// takes: "**Serves 4** · Prep 15 min · Cook 35 min".
+fn meta_at<'a>(doc: &Doc<'a>, k: usize, lists: bool) -> Option<Meta<'a>> {
+ let texts: Vec<&'a str> = match doc.blocks.get(k)? {
+ Top::Para { start, end } => doc.lines[*start..=*end].to_vec(),
+ Top::List(n) if lists => doc.lists[*n].items.clone(),
+ _ => return None,
+ };
+ let mut m = Meta::default();
+ let mut any = false;
+ for t in texts {
+ for seg in segments(t) {
+ let (l, v) = parts(seg);
+ if l.is_empty() && v.is_empty() {
+ continue;
+ }
+ if let Some(n) = serves_of(l, v) {
+ m.serve(Some(n))?;
+ } else if is_time(l, v) {
+ m.times.push((l, v));
+ } else {
+ return None;
+ }
+ any = true;
+ }
+ }
+ (any && m.times.len() <= MAX_TIMES).then_some(m)
+}
+
+/// `s` cut at `·`, `•`, `|`, `;`, a spaced dash and ", ".
+fn segments(s: &str) -> Vec<&str> {
+ const WIDE: [&str; 4] = [" — ", " – ", " - ", ", "];
+ let mut out = Vec::new();
+ let mut from = 0;
+ let mut i = 0;
+ while i < s.len() {
+ if let Some(w) = WIDE.iter().find(|w| s[i..].starts_with(**w)) {
+ out.push(&s[from..i]);
+ i += w.len();
+ from = i;
+ continue;
+ }
+ let c = s[i..].chars().next().unwrap_or(' ');
+ if matches!(c, '·' | '•' | '|' | ';') {
+ out.push(&s[from..i]);
+ from = i + c.len_utf8();
+ }
+ i += c.len_utf8();
+ }
+ out.push(&s[from..]);
+ out
+}
+
+/// A segment's label and value: "**Prep:** 15 min" → ("Prep", "15 min"), "Serves 4" →
+/// ("Serves", "4"), "4 servings" → ("", "4 servings"), "Chill overnight" → ("Chill", "overnight").
+fn parts(seg: &str) -> (&str, &str) {
+ fn t(s: &str) -> &str {
+ s.trim_matches(|c: char| c.is_whitespace() || c == '*' || c == '_')
+ }
+ let seg = t(seg);
+ if let Some((l, v)) = seg.split_once(':') {
+ return (t(l), t(v));
+ }
+ let cut = seg.find(|c: char| c.is_ascii_digit() || GLYPHS.contains(&c)).or_else(|| seg.to_ascii_lowercase().find("overnight"));
+ match cut {
+ Some(i) => (t(&seg[..i]), t(&seg[i..])),
+ None => (seg, ""),
+ }
+}
+
+/// "Serves 4", "Servings: 4", "Yield: 4", "4 servings", "for 4 people", "Makes 4 portions".
+fn serves_of(label: &str, value: &str) -> Option<u32> {
+ let mut w = value.split_whitespace();
+ let n: u32 = w.next()?.parse().ok()?;
+ let unit = w.next().map(str::to_lowercase);
+ if w.next().is_some() {
+ return None;
+ }
+ let unit_ok = unit.as_deref().is_none_or(|u| matches!(u, "servings" | "serving" | "people" | "persons" | "portions" | "portion"));
+ let label_ok = match label.to_lowercase().as_str() {
+ "serves" | "servings" | "serving" | "yield" | "yields" | "feeds" | "portions" | "for" => unit_ok,
+ "" | "makes" => unit.is_some() && unit_ok,
+ _ => false,
+ };
+ (label_ok && (SERVES.0..=SERVES.1).contains(&n)).then_some(n)
+}
+
+fn serves_in(s: &str) -> Option<u32> {
+ let (l, v) = parts(s);
+ serves_of(l, v)
+}
+
+const TIME_LABELS: [&str; 37] = [
+ "prep", "preparation", "prep time", "preparation time", "cook", "cooking", "cook time", "cooking time", "bake",
+ "baking", "bake time", "baking time", "total", "total time", "time", "rest", "resting", "resting time", "chill",
+ "chilling", "chill time", "chilling time", "marinate", "marinating", "active", "active time", "inactive",
+ "inactive time", "ready in", "rise", "rising", "proof", "proofing", "simmer", "roast", "roasting", "hands-on time",
+];
+const TIME_UNITS: [&str; 16] =
+ ["min", "mins", "minute", "minutes", "hr", "hrs", "hour", "hours", "h", "m", "sec", "secs", "second", "seconds", "day", "days"];
+
+/// "Prep" + "15 min", "Total time" + "1 hr 10 min", "Chill" + "overnight".
+fn is_time(label: &str, value: &str) -> bool {
+ let label = label.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ");
+ if !TIME_LABELS.contains(&label.as_str()) {
+ return false;
+ }
+ let v = value.to_lowercase();
+ if v == "overnight" {
+ return true;
+ }
+ if !value.starts_with(|c: char| c.is_ascii_digit() || GLYPHS.contains(&c)) {
+ return false;
+ }
+ let runs: Vec<&str> = v.split(|c: char| !c.is_alphabetic()).filter(|r| !r.is_empty()).collect();
+ runs.iter().any(|r| TIME_UNITS.contains(r))
+ && runs.iter().all(|r| TIME_UNITS.contains(r) || matches!(*r, "and" | "to" | "or" | "plus"))
+}
+
+// Amounts
+
+/// Units written straight after an amount ("200g") or after one space ("1 tbsp."), which may
+/// keep a ".".
+const ABBREV: [&str; 17] = ["g", "kg", "mg", "ml", "l", "dl", "cl", "oz", "lb", "lbs", "tbsp", "tbs", "tsp", "pt", "qt", "cm", "mm"];
+/// Unit words and Mira's countables, after one space.
+const UNIT_WORDS: [&str; 78] = [
+ "cup", "cups", "tablespoon", "tablespoons", "teaspoon", "teaspoons", "clove", "cloves", "can", "cans", "tin", "tins",
+ "slice", "slices", "stick", "sticks", "sprig", "sprigs", "pinch", "pinches", "handful", "handfuls", "bunch", "bunches",
+ "piece", "pieces", "jar", "jars", "packet", "packets", "package", "packages", "head", "heads", "stalk", "stalks",
+ "sheet", "sheets", "knob", "knobs", "dash", "dashes", "drop", "drops", "pint", "pints", "quart", "quarts", "pound",
+ "pounds", "ounce", "ounces", "gram", "grams", "kilogram", "kilograms", "litre", "litres", "liter", "liters",
+ "millilitre", "millilitres", "milliliter", "milliliters", "onion", "onions", "lemon", "lemons", "egg", "eggs",
+ "carrot", "carrots", "potato", "potatoes", "tomato", "tomatoes", "bulb", "bulbs",
+];
+
+/// An ingredient line's leading amount (with its unit) and the rest, such that the line is
+/// `qty + " " + text`, or `qty + text` when `text` starts with ",". `(None, line)` when the line
+/// doesn't start with an amount or doesn't split that way.
+pub(super) fn split_qty(line: &str) -> (Option<&str>, &str) {
+ let Some(amount) = amount_end(line) else { return (None, line) };
+ let rest = &line[amount..];
+ // "350 °F oven" is a temperature, not an amount to scale
+ if is_temperature(line, rest) {
+ return (None, line);
+ }
+ let glued = alpha_run(rest);
+ let (qty, text) = if !glued.is_empty() {
+ // "200g flour": only a known abbreviation may be glued on
+ if !ABBREV.contains(&glued.to_lowercase().as_str()) {
+ return (None, line);
+ }
+ let q = amount + glued.len();
+ match line[q..].strip_prefix(' ') {
+ Some(t) => (&line[..q], t),
+ None if line[q..].starts_with(',') => (&line[..q], &line[q..]),
+ None => return (None, line),
+ }
+ } else if rest.starts_with(',') {
+ (&line[..amount], rest)
+ } else if let Some(after) = rest.strip_prefix(' ') {
+ let w = alpha_run(after);
+ let lower = w.to_lowercase();
+ let abbrev = ABBREV.contains(&lower.as_str());
+ let mut q = amount + 1 + w.len();
+ if abbrev && line[q..].starts_with('.') {
+ q += 1;
+ }
+ let tail = &line[q..];
+ let unit = !w.is_empty() && (abbrev || UNIT_WORDS.contains(&lower.as_str()));
+ match tail.strip_prefix(' ') {
+ Some(t) if unit && !t.is_empty() => (&line[..q], t),
+ _ if unit && tail.starts_with(',') => (&line[..q], tail),
+ // No unit, or one that would end the line ("3 eggs"): the amount alone
+ _ => (&line[..amount], after),
+ }
+ } else {
+ return (None, line);
+ };
+ let joined = if text.starts_with(',') { format!("{qty}{text}") } else { format!("{qty} {text}") };
+ if text.is_empty() || text.starts_with(char::is_whitespace) || joined != line {
+ return (None, line);
+ }
+ (Some(qty), text)
+}
+
+/// What follows an amount marks it as a temperature: a degree sign (`°`, `º`, `℃`, `℉`), a
+/// capital `F` on its own ("350F"), a capital `C` on its own after 90 or more ("180 C"; below
+/// that, as in "1 C sugar", it is a cup), or a degree word ("350 degrees").
+fn is_temperature(line: &str, rest: &str) -> bool {
+ let r = rest.trim_start();
+ if r.starts_with(['°', 'º', '℃', '℉']) {
+ return true;
+ }
+ match alpha_run(r) {
+ "F" => true,
+ "C" => whole_part(line) >= 90,
+ w => matches!(w.to_lowercase().as_str(), "degree" | "degrees" | "deg" | "fahrenheit" | "celsius" | "centigrade"),
+ }
+}
+
+/// The whole number an amount starts with: 2 for "2½", 0 for "½", 350 for "350–375".
+fn whole_part(line: &str) -> u64 {
+ match digits(line, 0) {
+ 0 => 0,
+ d => line[..d].parse().unwrap_or(u64::MAX),
+ }
+}
+
+/// The leading letters of `s`.
+fn alpha_run(s: &str) -> &str {
+ let end = s.find(|c: char| !c.is_alphabetic()).unwrap_or(s.len());
+ &s[..end]
+}
+
+fn digits(s: &str, i: usize) -> usize {
+ s[i..].bytes().take_while(u8::is_ascii_digit).count()
+}
+
+/// The end of `\d+/\d+` at `i`.
+fn fraction(s: &str, i: usize) -> Option<usize> {
+ let a = digits(s, i);
+ if a == 0 || !s[i + a..].starts_with('/') {
+ return None;
+ }
+ let b = digits(s, i + a + 1);
+ (b > 0).then_some(i + a + 1 + b)
+}
+
+/// The end of one `NUM` of `LEAD` at `i`: `1 1/2`, `1/2`, `1.5`, `1,5`, `1½`, `1 ½`, `½`.
+fn number(s: &str, i: usize) -> Option<usize> {
+ let first = s[i..].chars().next()?;
+ if GLYPHS.contains(&first) {
+ return Some(i + first.len_utf8());
+ }
+ let d = digits(s, i);
+ if d == 0 {
+ return None;
+ }
+ let mut j = i + d;
+ if s[j..].starts_with(' ') {
+ if let Some(e) = fraction(s, j + 1) {
+ return Some(e);
+ }
+ }
+ if let Some(e) = fraction(s, i) {
+ return Some(e);
+ }
+ if s[j..].starts_with(['.', ',']) && digits(s, j + 1) > 0 {
+ j += 1 + digits(s, j + 1);
+ }
+ let spaces = s[j..].len() - s[j..].trim_start().len();
+ if s[j + spaces..].starts_with(GLYPHS) {
+ j += spaces + s[j + spaces..].chars().next().map_or(0, char::len_utf8);
+ }
+ Some(j)
+}
+
+/// The end of the amount a line starts with: one number, or a range of two (`1–2`, `1 - 2`).
+fn amount_end(s: &str) -> Option<usize> {
+ let a = number(s, 0)?;
+ let after = s[a..].trim_start();
+ if let Some(dash) = after.strip_prefix(['–', '-']) {
+ let b = s.len() - dash.trim_start().len();
+ if let Some(e) = number(s, b) {
+ return Some(e);
+ }
+ }
+ Some(a)
+}
+
+#[cfg(test)]
+#[path = "recipe_tests.rs"]
+mod tests;
diff --git a/src/server/smart_results/recipe_tests.rs b/src/server/smart_results/recipe_tests.rs
new file mode 100644
index 00000000..ebb24a91
--- /dev/null
+++ b/src/server/smart_results/recipe_tests.rs
@@ -0,0 +1,490 @@
+//! The recipe block: the contract example, recipe-shaped replies, near misses, the qty/text split
+//! and the checks. All data is made up.
+use serde_json::json;
+
+use super::*;
+use crate::server::smart_results::{compute, validate, Block, ResultSet, Source, VERSION};
+
+fn first(text: &str) -> Option<Block> {
+ compute(text).map(|set| set.blocks.into_iter().next().expect("one block"))
+}
+
+fn kind(text: &str) -> Option<&'static str> {
+ first(text).map(|b| b.kind())
+}
+
+fn recipe_in(text: &str) -> Recipe {
+ match first(text) {
+ Some(Block::Recipe(r)) => r,
+ other => panic!("no recipe: {other:?}"),
+ }
+}
+
+/// (qty, text) of every ingredient.
+fn split(r: &Recipe) -> Vec<(Option<&str>, &str)> {
+ r.ingredients.iter().map(|i| (i.qty.as_deref(), i.text.as_str())).collect()
+}
+
+fn src(r: &Recipe) -> (usize, bool, usize, bool, usize) {
+ let s = &r.source;
+ assert_eq!(s.kind, "markdown_section");
+ (s.index.unwrap(), s.ordered.unwrap(), s.last_index.unwrap(), s.last_ordered.unwrap(), s.lead.unwrap())
+}
+
+const CONTRACT: &str = "Here's a cosy stew for tonight.
+
+## Golden squash and lentil stew
+
+**Serves 4** · Prep 15 min · Cook 35 min
+
+### Ingredients
+
+**For the stew**
+- 1 tbsp olive oil
+- 1 onion, diced
+- 2 cloves garlic, crushed
+- 500 g squash, peeled and cubed
+- 1 can (400 g) chopped tomatoes
+- Salt to taste
+
+**For the topping:**
+- ½ cup plain yogurt
+- 1–2 tsp chili flakes
+
+### Method
+
+1. Warm the oil in a large pot over medium heat. Add the onion and cook for 5 minutes, until soft.
+2. Stir in the garlic and cook for 1 minute.
+3. Add the squash and tomatoes and simmer for 25 minutes.
+4. Serve with the yogurt and chili flakes.
+
+### Notes
+
+- Keeps 3 days in the fridge.
+- Sweet potato works in place of the squash.
+
+Want a vegan version?
+";
+
+// --- the contract
+
+#[test]
+fn the_contract_example_is_exact() {
+ let set = compute(CONTRACT).expect("a block");
+ let expected = json!({
+ "version": 1,
+ "blocks": [{
+ "type": "recipe",
+ "id": "b0",
+ "title": "Golden squash and lentil stew",
+ "source": { "kind": "markdown_section", "index": 0, "ordered": false, "last_index": 2, "last_ordered": false, "lead": 4 },
+ "serves": 4,
+ "times": [ { "label": "Prep", "text": "15 min" }, { "label": "Cook", "text": "35 min" } ],
+ "ingredients": [
+ { "id": "i0", "text": "olive oil", "qty": "1 tbsp", "group": "For the stew" },
+ { "id": "i1", "text": ", diced", "qty": "1 onion", "group": "For the stew" },
+ { "id": "i2", "text": "garlic, crushed", "qty": "2 cloves", "group": "For the stew" },
+ { "id": "i3", "text": "squash, peeled and cubed", "qty": "500 g", "group": "For the stew" },
+ { "id": "i4", "text": "(400 g) chopped tomatoes", "qty": "1 can", "group": "For the stew" },
+ { "id": "i5", "text": "Salt to taste", "qty": null, "group": "For the stew" },
+ { "id": "i6", "text": "plain yogurt", "qty": "½ cup", "group": "For the topping" },
+ { "id": "i7", "text": "chili flakes", "qty": "1–2 tsp", "group": "For the topping" }
+ ],
+ "steps": [
+ { "id": "s0", "text": "Warm the oil in a large pot over medium heat. Add the onion and cook for 5 minutes, until soft." },
+ { "id": "s1", "text": "Stir in the garlic and cook for 1 minute." },
+ { "id": "s2", "text": "Add the squash and tomatoes and simmer for 25 minutes." },
+ { "id": "s3", "text": "Serve with the yogurt and chili flakes." }
+ ],
+ "notes": [ "Keeps 3 days in the fridge.", "Sweet potato works in place of the squash." ],
+ "provenance": { "kind": "reply_text" }
+ }]
+ });
+ assert_eq!(serde_json::to_value(&set).unwrap(), expected);
+ // And it reads back as the same block
+ let back: ResultSet = serde_json::from_value(expected).unwrap();
+ assert_eq!(back, set);
+ assert!(validate(&back, Some(CONTRACT)).is_ok());
+}
+
+#[test]
+fn every_ingredient_line_is_qty_and_text_joined() {
+ let r = recipe_in(CONTRACT);
+ let lines: Vec<String> = r.ingredients.iter().map(Ingredient::line).collect();
+ assert_eq!(lines[1], "1 onion, diced");
+ assert_eq!(lines[4], "1 can (400 g) chopped tomatoes");
+ for l in &lines {
+ assert!(CONTRACT.contains(&format!("- {l}\n")), "{l}");
+ }
+}
+
+// --- recipe-shaped replies
+
+#[test]
+fn a_plain_recipe_with_a_heading_and_instructions() {
+ let r = recipe_in(
+ "## Fluffy pancakes\n\n### Ingredients\n\n- 1 cup flour\n- 2 eggs\n- 1 cup milk\n- 1 tsp baking powder\n\n### Instructions\n\n1. Whisk everything together.\n2. Cook ladlefuls in a hot pan, 2 minutes a side.\n",
+ );
+ assert_eq!(r.title.as_deref(), Some("Fluffy pancakes"));
+ assert_eq!((r.serves, r.times.len(), r.notes.len()), (None, 0, 0));
+ assert_eq!(src(&r), (0, false, 0, true, 2));
+ assert_eq!(split(&r)[1], (Some("2"), "eggs"));
+ assert_eq!(r.steps[1].text, "Cook ladlefuls in a hot pan, 2 minutes a side.");
+ assert!(r.ingredients.iter().all(|i| i.group.is_none()));
+}
+
+#[test]
+fn groups_under_headings_and_bold_labels() {
+ let text = "Here you go!\n\n# Lemon tart\n\n## Ingredients\n\n#### For the pastry\n- 200g plain flour\n- 100 g cold butter, cubed\n- 1 egg yolk\n\n#### For the filling\n- 3 lemons, zest and juice\n- 150 g sugar\n- 3 eggs\n\n__Topping:__\n- Icing sugar, to dust\n\n## Method\n1. Rub the butter into the flour, add the yolk and chill for 30 minutes.\n2. Roll out, line a tin and blind bake for 15 minutes.\n3. Whisk the filling, pour in and bake for 25 minutes.\n";
+ let r = recipe_in(text);
+ assert_eq!(r.title.as_deref(), Some("Lemon tart"));
+ let groups: Vec<_> = r.ingredients.iter().map(|i| i.group.as_deref()).collect();
+ assert_eq!(groups, [Some("For the pastry"), Some("For the pastry"), Some("For the pastry"), Some("For the filling"), Some("For the filling"), Some("For the filling"), Some("Topping")]);
+ assert_eq!(split(&r)[0], (Some("200g"), "plain flour"));
+ assert_eq!(split(&r)[3], (Some("3 lemons"), ", zest and juice"));
+ assert_eq!(split(&r)[6], (None, "Icing sugar, to dust"));
+ // # Lemon tart, ## Ingredients, #### For the pastry, then ul#0; last is ol#0
+ assert_eq!(src(&r), (0, false, 0, true, 3));
+}
+
+#[test]
+fn ranges_and_fractions_keep_the_amount_as_written() {
+ let r = recipe_in(
+ "### Ingredients\n- 1–2 tsp chili flakes\n- 1/2 cup rice\n- 1 1/2 cups stock\n- 1½ cups water\n- 2-3 cloves garlic\n- 1 - 2 tbsp. soy sauce\n- ¼ tsp salt\n- 1,5 l broth\n\n### Steps\n1. Toast the rice.\n2. Add everything else and simmer.\n",
+ );
+ assert_eq!(
+ split(&r),
+ [
+ (Some("1–2 tsp"), "chili flakes"),
+ (Some("1/2 cup"), "rice"),
+ (Some("1 1/2 cups"), "stock"),
+ (Some("1½ cups"), "water"),
+ (Some("2-3 cloves"), "garlic"),
+ (Some("1 - 2 tbsp."), "soy sauce"),
+ (Some("¼ tsp"), "salt"),
+ (Some("1,5 l"), "broth"),
+ ]
+ );
+ assert_eq!(r.title, None);
+ assert_eq!(src(&r).4, 1);
+}
+
+#[test]
+fn no_serves_no_times_no_title() {
+ let r = recipe_in("**Ingredients:**\n- 2 slices bread\n- 1 tbsp butter\n\n**Method:**\n1. Butter the bread.\n2. Toast it.\n\nEnjoy!\n");
+ assert_eq!((r.title.as_deref(), r.serves, r.times.len()), (None, None, 0));
+ assert_eq!(src(&r), (0, false, 0, true, 1));
+}
+
+#[test]
+fn servings_in_the_cue_and_a_numbered_method_straight_after() {
+ let r = recipe_in("A quick one.\n\nIngredients (serves 2):\n- 2 eggs\n- 1 knob butter\n- Salt and pepper\n\n1. Beat the eggs.\n2. Melt the butter and stir the eggs until just set.\n");
+ assert_eq!(r.serves, Some(2));
+ assert_eq!(split(&r)[1], (Some("1 knob"), "butter"));
+ assert_eq!(src(&r), (0, false, 0, true, 1));
+}
+
+#[test]
+fn an_intro_line_naming_the_ingredients_stays_text() {
+ let text = "## Hummus\n\nHere are the ingredients you'll need:\n\n- 1 can chickpeas, drained\n- 2 tbsp tahini\n- 1 lemon, juiced\n\nThen follow these steps:\n\n1. Blend everything until smooth.\n2. Loosen with water.\n";
+ let r = recipe_in(text);
+ // The section starts at the list: the heading and the intro stay above the card
+ assert_eq!(r.title, None);
+ assert_eq!(src(&r), (0, false, 0, true, 0));
+ assert_eq!(split(&r)[0], (Some("1 can"), "chickpeas, drained"));
+}
+
+#[test]
+fn a_meta_list_and_times_above_the_cue() {
+ let text = "### Green salad\n\n- **Serves:** 2\n- **Prep time:** 10 minutes\n- Total: 1 hr 10 min\n\n### Ingredients\n- 1 head lettuce\n- 2 tbsp olive oil\n\n### Directions\n1. Wash and dry the lettuce.\n2. Dress and serve.\n";
+ let r = recipe_in(text);
+ assert_eq!(r.title.as_deref(), Some("Green salad"));
+ assert_eq!(r.serves, Some(2));
+ let times: Vec<_> = r.times.iter().map(|t| (t.label.as_str(), t.text.as_str())).collect();
+ assert_eq!(times, [("Prep time", "10 minutes"), ("Total", "1 hr 10 min")]);
+ // The meta list is the section's first list (ul#0), the method ol#0; lead 1 (the title heading)
+ assert_eq!(src(&r), (0, false, 0, true, 1));
+}
+
+#[test]
+fn tips_after_the_method_and_task_boxes_on_ingredients() {
+ let text = "**Overnight oats**\n\nServes 1 | Chill: overnight\n\nIngredients\n- [ ] 1/2 cup oats\n- [x] 1/2 cup milk\n- [ ] 1 tbsp honey\n\nInstructions\n1. Stir everything in a jar.\n2. Chill overnight.\n\n**Tips:**\n- Add berries in the morning.\n";
+ let r = recipe_in(text);
+ assert_eq!(r.title.as_deref(), Some("Overnight oats"));
+ assert_eq!((r.serves, r.times[0].label.as_str(), r.times[0].text.as_str()), (Some(1), "Chill", "overnight"));
+ assert_eq!(split(&r)[0], (Some("1/2 cup"), "oats"));
+ assert_eq!(r.notes, ["Add berries in the morning."]);
+ assert_eq!(src(&r), (0, false, 1, false, 3));
+}
+
+#[test]
+fn task_boxes_on_notes_are_dropped_like_on_ingredients() {
+ // F-4: a task-list Tips list loses its boxes, as the ingredients do
+ let text = "### Garlic bread
+
+### Ingredients
+- [ ] 1 baguette
+- [x] 3 cloves garlic
+
+### Method
+1. Spread the garlic butter.
+2. Bake.
+
+### Tips
+- [ ] Use fresh garlic
+- [x] Wrap in foil to keep it soft
+- [X] Serve warm
+- Plain tip
+";
+ let r = recipe_in(text);
+ assert_eq!(split(&r)[1], (Some("3 cloves"), "garlic"));
+ assert_eq!(r.notes, ["Use fresh garlic", "Wrap in foil to keep it soft", "Serve warm", "Plain tip"]);
+ assert!(r.ingredients.iter().all(|i| !i.text.contains('[')));
+}
+
+#[test]
+fn a_setext_title_and_a_bullet_method_under_its_heading() {
+ let text = "Tomato soup\n===========\n\nIngredients\n-----------\n\n- 1 kg tomatoes\n- 1 onion\n- 500 ml stock\n\nMethod\n------\n\n- Soften the onion.\n- Add the tomatoes and stock, simmer 20 minutes, blend.\n";
+ let r = recipe_in(text);
+ assert_eq!(r.title.as_deref(), Some("Tomato soup"));
+ assert_eq!(split(&r)[1], (Some("1"), "onion"));
+ assert_eq!(src(&r), (0, false, 1, false, 2));
+}
+
+#[test]
+fn a_meta_line_it_cannot_read_stays_text_above_the_card() {
+ // "Serves 4–6" is no single count: the line and the title above it stay text
+ let text = "## Chili\n\nServes 4–6\n\n### Ingredients\n- 500 g beans\n- 2 tsp cumin\n\n### Method\n1. Fry the spices.\n2. Add the beans and simmer.\n";
+ let r = recipe_in(text);
+ assert_eq!((r.title.as_deref(), r.serves), (None, None));
+ assert_eq!(src(&r).4, 1);
+}
+
+#[test]
+fn a_recipe_ranks_above_a_table_and_the_steps_it_holds() {
+ let text = "| Pan | Size |\n|---|---|\n| Small | 20 cm |\n| Large | 28 cm |\n| Tray | 30 cm |\n\n### Ingredients\n- 2 cups flour\n- 1 cup sugar\n\n### Method\n1. Mix.\n2. Bake for 30 minutes.\n3. Cool.\n";
+ assert_eq!(kind(text), Some("recipe"));
+}
+
+// --- near misses
+
+#[test]
+fn a_shopping_list_alone_is_not_a_recipe() {
+ assert_ne!(kind("Here's your shopping list:\n\n- 2 onions\n- 1 kg potatoes\n- Milk\n- 6 eggs\n"), Some("recipe"));
+ assert_ne!(kind("### Ingredients\n- 2 onions\n- 1 kg potatoes\n- Milk\n\nBuy them at the market.\n"), Some("recipe"));
+}
+
+#[test]
+fn a_packing_list_is_not_a_recipe() {
+ let text = "### Packing list\n- Tent\n- 2 sleeping bags\n- 1 stove\n\n### Before you go\n1. Check the weather.\n2. Tell someone your route.\n3. Charge your phone.\n";
+ assert_ne!(kind(text), Some("recipe"));
+}
+
+#[test]
+fn a_how_to_without_ingredients_stays_steps() {
+ let text = "### What you need\n- A drill\n- 4 screws\n\n### Steps\n1. Mark the holes.\n2. Drill them.\n3. Screw the shelf on.\n";
+ assert_eq!(kind(text), Some("steps"));
+ assert_eq!(kind("How to reset it:\n\n1. Unplug the router.\n2. Wait 30 seconds.\n3. Plug it back in.\n"), Some("steps"));
+}
+
+#[test]
+fn a_meal_plan_with_several_dishes_is_not_a_recipe() {
+ let two = "## Monday: pasta\n\n**Ingredients:**\n- 200 g pasta\n- 1 jar pesto\n\n**Method:**\n1. Boil the pasta.\n2. Stir in the pesto.\n\n## Tuesday: soup\n\n**Ingredients:**\n- 1 kg carrots\n- 1 l stock\n\n1. Simmer.\n2. Blend.\n";
+ assert_ne!(kind(two), Some("recipe"));
+ let by_day = "### Ingredients\n- 1 kg pasta\n- 2 jars sauce\n- 1 bag salad\n\n1. Monday: pasta with sauce\n2. Tuesday: salad\n3. Wednesday: leftovers\n";
+ assert_ne!(kind(by_day), Some("recipe"));
+}
+
+#[test]
+fn a_second_dish_without_its_own_cue_is_not_one_recipe() {
+ let text = "## Rice\n\n### Ingredients\n- 1 cup rice\n- 2 cups water\n\n### Method\n1. Rinse.\n2. Simmer 15 minutes.\n\n## And a dal\n\n- 1 cup lentils\n- 3 cups water\n\n1. Rinse.\n2. Simmer 25 minutes.\n";
+ assert_ne!(kind(text), Some("recipe"));
+}
+
+#[test]
+fn a_weather_reply_is_not_a_recipe() {
+ let text = "**Today:** 18°C, light rain\n**Tomorrow:** 21°C, sunny\n\n- Bring an umbrella in the morning.\n- Wind 12 km/h.\n";
+ assert_ne!(kind(text), Some("recipe"));
+}
+
+#[test]
+fn a_method_in_prose_or_a_block_in_between_is_not_a_card() {
+ let prose = "### Ingredients\n- 2 eggs\n- 1 cup milk\n\n### Method\nWhisk them and cook in a hot pan for 2 minutes.\n";
+ assert_ne!(kind(prose), Some("recipe"));
+ let code = "### Ingredients\n- 2 eggs\n- 1 cup milk\n\n```\noven: 180C\n```\n\n1. Whisk.\n2. Bake.\n";
+ assert_ne!(kind(code), Some("recipe"));
+ let para = "### Ingredients\n- 2 eggs\n- 1 cup milk\n\nYou can swap the milk for water if you like, it works fine.\n\n1. Whisk.\n2. Bake.\n";
+ assert_ne!(kind(para), Some("recipe"));
+}
+
+#[test]
+fn a_cue_it_cannot_place_or_a_split_method_is_not_a_card() {
+ let mixed = "## Ingredients and method\n- 2 eggs\n- 1 cup milk\n\n1. Whisk.\n2. Bake.\n";
+ assert_ne!(kind(mixed), Some("recipe"));
+ let split_method = "### Ingredients\n- 2 eggs\n- 1 cup milk\n\n### Method\n1. Whisk.\n2. Bake.\n\n**For the glaze:**\n1. Melt.\n2. Pour.\n";
+ assert_ne!(kind(split_method), Some("recipe"));
+ let one = "### Ingredients\n- 2 eggs\n\n### Method\n1. Boil.\n2. Peel.\n";
+ assert_ne!(kind(one), Some("recipe"));
+}
+
+#[test]
+fn html_in_a_step_is_not_a_card() {
+ let text = "### Ingredients\n- 2 eggs\n- 1 cup milk\n\n### Method\n1. Whisk <b>well</b>.\n2. Bake.\n";
+ assert_ne!(kind(text), Some("recipe"));
+}
+
+// --- qty and text
+
+#[test]
+fn split_qty_takes_the_leading_amount_as_written() {
+ let cases: &[(&str, Option<&str>, &str)] = &[
+ ("2 cups flour, sifted", Some("2 cups"), "flour, sifted"),
+ ("1 onion, diced", Some("1 onion"), ", diced"),
+ ("3 eggs", Some("3"), "eggs"),
+ ("2 cups", Some("2"), "cups"),
+ ("2 large onions", Some("2"), "large onions"),
+ ("200g flour", Some("200g"), "flour"),
+ ("250ml milk", Some("250ml"), "milk"),
+ ("1 tbsp. olive oil", Some("1 tbsp."), "olive oil"),
+ ("1 Tbsp olive oil", Some("1 Tbsp"), "olive oil"),
+ ("1,000 g water", Some("1,000 g"), "water"),
+ ("½ cup yogurt", Some("½ cup"), "yogurt"),
+ ("1 ½ cups milk", Some("1 ½ cups"), "milk"),
+ ("2 1/2 cups flour", Some("2 1/2 cups"), "flour"),
+ ("12–15 cherry tomatoes", Some("12–15"), "cherry tomatoes"),
+ ("2 x 400g tins tomatoes", Some("2"), "x 400g tins tomatoes"),
+ ("1 can (400 g) tomatoes", Some("1 can"), "(400 g) tomatoes"),
+ ("Salt to taste", None, "Salt to taste"),
+ ("A pinch of salt", None, "A pinch of salt"),
+ ("Zest of 1 lemon", None, "Zest of 1 lemon"),
+ ("**2 cups** flour", None, "**2 cups** flour"),
+ ("1-inch piece ginger", None, "1-inch piece ginger"),
+ ("2x eggs", None, "2x eggs"),
+ ("2 cups flour", None, "2 cups flour"),
+ ("3", None, "3"),
+ ("500g/1lb beef", None, "500g/1lb beef"),
+ // A temperature is not an amount (F-2): no qty, so it never scales
+ ("350 °F oven", None, "350 °F oven"),
+ ("350°F oven", None, "350°F oven"),
+ ("180 °C fan oven", None, "180 °C fan oven"),
+ ("180ºC oven", None, "180ºC oven"),
+ ("200 ℃ oven", None, "200 ℃ oven"),
+ ("350F oven", None, "350F oven"),
+ ("350 F oven", None, "350 F oven"),
+ ("180 C fan", None, "180 C fan"),
+ ("100 C", None, "100 C"),
+ ("90 C oven", None, "90 C oven"),
+ ("350 degrees oven", None, "350 degrees oven"),
+ ("180 Degrees C", None, "180 Degrees C"),
+ ("350–375 °F oven", None, "350–375 °F oven"),
+ ("400 deg. oven", None, "400 deg. oven"),
+ ("180 Celsius oven", None, "180 Celsius oven"),
+ // Near misses that stay amounts: a unit or word that only starts with F or C
+ ("2 cups flour", Some("2 cups"), "flour"),
+ ("2 Cups flour", Some("2 Cups"), "flour"),
+ ("1 can chickpeas", Some("1 can"), "chickpeas"),
+ ("2 c. flour", Some("2"), "c. flour"),
+ ("3 Fuji apples", Some("3"), "Fuji apples"),
+ ("1 cl rum", Some("1 cl"), "rum"),
+ ("4 fl oz cream", Some("4"), "fl oz cream"),
+ // A lone capital C under 90 is a US cup, so it still scales
+ ("1 C sugar", Some("1"), "C sugar"),
+ ("2½ C flour", Some("2½"), "C flour"),
+ ("1 1/2 C milk", Some("1 1/2"), "C milk"),
+ ("½ C butter", Some("½"), "C butter"),
+ ("89 C water", Some("89"), "C water"),
+ ];
+ for (line, qty, text) in cases {
+ let got = split_qty(line);
+ assert_eq!(got, (*qty, *text), "{line}");
+ let i = Ingredient { id: "i0".into(), text: got.1.into(), qty: got.0.map(Into::into), group: None };
+ assert_eq!(i.line(), *line, "{line} rebuilds");
+ }
+}
+
+// --- the checks
+
+fn contract_set() -> ResultSet {
+ compute(CONTRACT).expect("a block")
+}
+
+fn tampered(f: impl FnOnce(&mut Recipe)) -> ResultSet {
+ let mut set = contract_set();
+ let Block::Recipe(r) = &mut set.blocks[0] else { panic!() };
+ f(r);
+ set
+}
+
+#[test]
+fn validate_holds_a_recipe_to_its_limits() {
+ let bad: Vec<(&str, ResultSet)> = vec![
+ ("serves 0", tampered(|r| r.serves = Some(0))),
+ ("serves 25", tampered(|r| r.serves = Some(25))),
+ ("qty", tampered(|r| r.ingredients[0].qty = Some("a lot".into()))),
+ ("ingredient id", tampered(|r| r.ingredients[1].id = "i7".into())),
+ ("step id", tampered(|r| r.steps[0].id = "x".into())),
+ ("one step", tampered(|r| r.steps.truncate(1))),
+ ("one ingredient", tampered(|r| r.ingredients.truncate(1))),
+ ("7 notes", tampered(|r| r.notes = vec!["Keeps 3 days in the fridge.".into(); 7])),
+ ("4 times", tampered(|r| r.times = vec![r.times[0].clone(); 4])),
+ ("empty step", tampered(|r| r.steps[0].text = " ".into())),
+ ("html", tampered(|r| r.steps[0].text = "Warm <script>x</script>".into())),
+ ("list source", tampered(|r| r.source = Source::list(0, false))),
+ ("lead", tampered(|r| r.source.lead = Some(13))),
+ ("ends before it starts", tampered(|r| r.source.index = Some(3))),
+ ("no last list", tampered(|r| r.source.last_index = None)),
+ ("long step", tampered(|r| r.steps[0].text = "a".repeat(601))),
+ ("provenance", tampered(|r| r.provenance = Provenance::kwant_data("x".into()))),
+ ];
+ for (what, set) in bad {
+ assert!(validate(&set, None).is_err(), "{what}");
+ }
+ assert!(validate(&contract_set(), None).is_ok());
+}
+
+#[test]
+fn every_recipe_text_must_be_text_of_the_reply() {
+ let bad = [
+ tampered(|r| r.ingredients[0].text = "rapeseed oil".into()),
+ tampered(|r| r.ingredients[0].qty = Some("2 tbsp".into())),
+ tampered(|r| r.ingredients[0].group = Some("For the sauce".into())),
+ tampered(|r| r.serves = Some(9)),
+ tampered(|r| r.times[0].text = "20 min".into()),
+ tampered(|r| r.steps[3].text = "Serve hot.".into()),
+ tampered(|r| r.notes[0] = "Freezes well.".into()),
+ tampered(|r| r.title = Some("Pumpkin stew".into())),
+ ];
+ for (k, set) in bad.iter().enumerate() {
+ assert!(validate(set, Some(CONTRACT)).is_err(), "case {k}");
+ }
+}
+
+#[test]
+fn a_section_source_is_for_a_recipe_only() {
+ let steps = "Steps:\n\n1. Mix.\n2. Bake.\n3. Cool.\n";
+ let mut set = compute(steps).expect("steps");
+ let Block::Steps(s) = &mut set.blocks[0] else { panic!() };
+ s.source = Source::section((0, true), (0, true), 0);
+ assert!(validate(&set, Some(steps)).is_err());
+ // A list source can't carry section fields either
+ let mut set = compute(steps).expect("steps");
+ let Block::Steps(s) = &mut set.blocks[0] else { panic!() };
+ s.source.lead = Some(0);
+ assert!(validate(&set, Some(steps)).is_err());
+}
+
+#[test]
+fn optional_fields_may_be_missing_when_read_back() {
+ let v = json!({"version": 1, "blocks": [{
+ "type": "recipe", "id": "b0",
+ "source": {"kind": "markdown_section", "index": 0, "ordered": false, "last_index": 0, "last_ordered": true, "lead": 0},
+ "ingredients": [{"id": "i0", "text": "eggs"}, {"id": "i1", "text": "milk"}],
+ "steps": [{"id": "s0", "text": "Whisk."}, {"id": "s1", "text": "Bake."}],
+ "provenance": {"kind": "reply_text"}
+ }]});
+ let set: ResultSet = serde_json::from_value(v).unwrap();
+ let Block::Recipe(r) = &set.blocks[0] else { panic!() };
+ assert_eq!((r.title.as_deref(), r.serves, r.times.len(), r.notes.len(), r.ingredients[0].qty.as_deref()), (None, None, 0, 0, None));
+ assert_eq!(set.version, VERSION);
+ assert!(validate(&set, None).is_ok());
+}
diff --git a/src/server/smart_results/selector.rs b/src/server/smart_results/selector.rs
index 7498aab9..ef152e59 100644
--- a/src/server/smart_results/selector.rs
+++ b/src/server/smart_results/selector.rs
@@ -17,8 +17,19 @@ use super::{Block, Column, Comparison, Provenance, Role, Row, Source, Steps, Var
/// The order types win in when a reply has more than one candidate (plan §A.2), best first.
/// `present_result`, `verification` and `files` come from typed sources, not from these selectors.
-pub const PRIORITY: &[&str] =
- &["present_result", "verification", "chart", "comparison", "metrics", "findings", "cards", "steps", "facts", "files"];
+pub const PRIORITY: &[&str] = &[
+ "present_result",
+ "verification",
+ "recipe",
+ "chart",
+ "comparison",
+ "metrics",
+ "findings",
+ "cards",
+ "steps",
+ "facts",
+ "files",
+];
/// Where `block` stands in [`PRIORITY`] (lower wins); steps rank timeline, then checklist, then
/// plain steps.
@@ -46,6 +57,9 @@ pub fn candidates(text: &str) -> Vec<Block> {
let said = OnceCell::new();
let said = || said.get_or_init(|| recommending(&doc.prose)).as_deref();
let mut found: Vec<(usize, Block)> = Vec::new();
+ if let Some((start, r)) = super::recipe::recipe(&doc) {
+ found.push((start, Block::Recipe(r)));
+ }
let tables = doc.tables.iter().filter(|t| t.clean && t.start < doc.tables_unsure_at).take(MAX_TRIES);
for t in tables {
if let Some(b) = table_block(t, &said) {
@@ -166,10 +180,27 @@ pub(super) struct List<'a> {
pub heading: Option<&'a str>,
}
+/// A top-level block of the reply, in the chat's order of root children.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(super) enum Top<'a> {
+ /// A one-line heading (ATX, or setext over one line), its text.
+ Heading(&'a str),
+ /// A paragraph: its first and last line.
+ Para { start: usize, end: usize },
+ /// `Doc::lists[n]`.
+ List(usize),
+ /// Code, a table, a quote, HTML, a rule or a heading over several lines.
+ Other,
+}
+
#[derive(Default)]
-struct Doc<'a> {
- tables: Vec<Table<'a>>,
- lists: Vec<List<'a>>,
+pub(super) struct Doc<'a> {
+ pub lines: Vec<&'a str>,
+ pub blocks: Vec<Top<'a>>,
+ /// The line each of `blocks` starts on.
+ pub starts: Vec<usize>,
+ pub tables: Vec<Table<'a>>,
+ pub lists: Vec<List<'a>>,
/// Lines outside code, HTML and tables, where a pick can be named.
prose: Vec<&'a str>,
/// The first line from which table (numbered list, bullet list) counts may differ from the
@@ -181,6 +212,13 @@ struct Doc<'a> {
ul_count: usize,
}
+impl<'a> Doc<'a> {
+ fn push(&mut self, line: usize, top: Top<'a>) {
+ self.blocks.push(top);
+ self.starts.push(line);
+ }
+}
+
impl Doc<'_> {
fn unsure_tables(&mut self, line: usize) {
self.tables_unsure_at = self.tables_unsure_at.min(line);
@@ -205,7 +243,11 @@ impl Doc<'_> {
self.unsure_ul(line);
}
}
- fn list_unsure_at(&self, ordered: bool) -> usize {
+ /// The first line from which any count may differ from the chat's.
+ pub(super) fn unsure_at(&self) -> usize {
+ self.tables_unsure_at.min(self.ol_unsure_at).min(self.ul_unsure_at)
+ }
+ pub(super) fn list_unsure_at(&self, ordered: bool) -> usize {
if ordered {
self.ol_unsure_at
} else {
@@ -241,7 +283,7 @@ struct Fence {
inside: Option<usize>,
}
-fn parse(text: &str) -> Doc<'_> {
+pub(super) fn parse(text: &str) -> Doc<'_> {
let lines: Vec<&str> = text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)).collect();
let mut doc = Doc { tables_unsure_at: usize::MAX, ol_unsure_at: usize::MAX, ul_unsure_at: usize::MAX, ..Doc::default() };
// The chat takes the last `[DECISIONS]` block still in a reply out of it, code or not, and
@@ -455,6 +497,14 @@ fn parse(text: &str) -> Doc<'_> {
doc.unsure_tables(i);
}
heading = prev.map(str::trim);
+ if let Some(top) = doc.blocks.last_mut() {
+ if let Top::Para { start, end } = *top {
+ *top = match heading {
+ Some(h) if start == end => Top::Heading(h),
+ _ => Top::Other,
+ };
+ }
+ }
state = State::None;
break;
}
@@ -492,6 +542,7 @@ fn parse(text: &str) -> Doc<'_> {
break;
}
if indent >= 4 {
+ doc.push(i, Top::Other);
state = State::Code;
prose = false;
code = true;
@@ -503,23 +554,28 @@ fn parse(text: &str) -> Doc<'_> {
break;
}
if let Some((ch, len)) = fence_open(rest) {
+ doc.push(i, Top::Other);
fence = Some(Fence { ch, len, inside: None });
prose = false;
break;
}
if let Some(h) = atx_heading(rest) {
+ doc.push(i, Top::Heading(h));
heading = Some(h);
break;
}
if thematic_break(rest) {
+ doc.push(i, Top::Other);
break;
}
if rest.starts_with('>') {
+ doc.push(i, Top::Other);
doc.unsure_nested(i, rest);
state = State::Quote;
break;
}
if html_start(rest) {
+ doc.push(i, Top::Other);
doc.unsure(i);
prose = false;
state = State::Html;
@@ -532,6 +588,7 @@ fn parse(text: &str) -> Doc<'_> {
if fence_open(m.content).is_some() {
l.clean = false;
}
+ doc.push(i, Top::List(doc.lists.len()));
doc.lists.push(l);
fence = item_fence(m.content, m.offset);
state = State::List { list: doc.lists.len() - 1, offset: m.offset, blank: false };
@@ -544,6 +601,7 @@ fn parse(text: &str) -> Doc<'_> {
if fence_open(b.content).is_some() {
l.clean = false;
}
+ doc.push(i, Top::List(doc.lists.len()));
doc.lists.push(l);
fence = item_fence(b.content, b.offset);
state = State::Bullet { list: doc.lists.len() - 1, offset: b.offset, blank: false };
@@ -551,6 +609,7 @@ fn parse(text: &str) -> Doc<'_> {
}
if let Some(header) = table_start(&lines, i) {
let index = doc.tables.len();
+ doc.push(i, Top::Other);
doc.tables.push(Table { index, start: i, clean: true, header, rows: Vec::new() });
delimiter_row = Some(i + 1);
state = State::Table(index);
@@ -558,11 +617,17 @@ fn parse(text: &str) -> Doc<'_> {
in_table = true;
break;
}
+ doc.push(i, Top::Para { start: i, end: i });
state = State::Para;
}
}
break;
}
+ if matches!(state, State::Para) {
+ if let Some(Top::Para { end, .. }) = doc.blocks.last_mut() {
+ *end = i;
+ }
+ }
if !in_table && !code && delimiter_like(line) {
// A table this reader didn't take as top-level (in a quote or an item, or orphaned)
doc.unsure_tables(i);
@@ -577,6 +642,7 @@ fn parse(text: &str) -> Doc<'_> {
prev = Some(line);
}
}
+ doc.lines = lines;
doc
}
diff --git a/src/server/smart_results/validate.rs b/src/server/smart_results/validate.rs
index 23dfc728..421f1962 100644
--- a/src/server/smart_results/validate.rs
+++ b/src/server/smart_results/validate.rs
@@ -4,6 +4,10 @@ use std::collections::HashSet;
use super::items::severity_of;
use super::selector::plain;
+use super::recipe::{
+ GLYPHS, GROUP_MAX, INGREDIENTS, INGREDIENT_MAX, MAX_LEAD, MAX_NOTES, MAX_TIMES, NOTE_MAX, QTY_MAX, SERVES, STEPS, STEP_MAX,
+ TIME_LABEL_MAX, TIME_TEXT_MAX,
+};
use super::{AxisKind, Block, ChartKind, ResultSet, Role, Variant, ENABLED_TYPES, MAX_PAYLOAD, PICK_REASON, VERSION};
/// `Ok` when `set` is a block set this build may store and serve. With `reply`, every label, unit,
@@ -28,11 +32,11 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
texts.push(title);
}
check_source(block)?;
- // `present_result` may declare a comparison or steps block itself (`bot_declared`, grounded
- // against the reply by its call); the typed task and file blocks come from kwant's data.
+ // `present_result` may declare a comparison, steps or recipe block itself (`bot_declared`,
+ // grounded against the reply by its call); the typed task and file blocks come from kwant's data.
let prov = block.provenance().kind.as_str();
let prov_ok = match block {
- Block::Comparison(_) | Block::Steps(_) => matches!(prov, "reply_text" | "bot_declared"),
+ Block::Comparison(_) | Block::Steps(_) | Block::Recipe(_) => matches!(prov, "reply_text" | "bot_declared"),
Block::Verification(_) | Block::Files(_) => prov == "kwant_data",
_ => prov == "reply_text",
};
@@ -42,6 +46,63 @@ pub fn validate(set: &ResultSet, reply: Option<&str>) -> Result<(), String> {
// Only text copied from the reply is checked against it.
let strict = prov == "reply_text";
match block {
+ Block::Recipe(r) => {
+ if let Some(n) = r.serves {
+ if !(SERVES.0..=SERVES.1).contains(&n) || reply.is_some_and(|reply| !reply.contains(&n.to_string())) {
+ return Err(format!("serves {n}"));
+ }
+ }
+ if r.times.len() > MAX_TIMES {
+ return Err(format!("{} times", r.times.len()));
+ }
+ for t in &r.times {
+ check_text(&t.label, TIME_LABEL_MAX, "time label")?;
+ check_text(&t.text, TIME_TEXT_MAX, "time")?;
+ texts.push(&t.label);
+ texts.push(&t.text);
+ }
+ if !(INGREDIENTS.0..=INGREDIENTS.1).contains(&r.ingredients.len()) {
+ return Err(format!("{} ingredients", r.ingredients.len()));
+ }
+ for (k, i) in r.ingredients.iter().enumerate() {
+ if i.id != format!("i{k}") {
+ return Err(format!("ingredient id {:?}", i.id));
+ }
+ check_text(&i.text, INGREDIENT_MAX, "ingredient")?;
+ if let Some(q) = &i.qty {
+ check_text(q, QTY_MAX, "qty")?;
+ if !q.starts_with(|c: char| c.is_ascii_digit() || GLYPHS.contains(&c)) {
+ return Err(format!("qty {q:?}"));
+ }
+ }
+ if let Some(g) = &i.group {
+ check_text(g, GROUP_MAX, "group")?;
+ texts.push(g);
+ }
+ // qty + text is the line as the reply wrote it
+ let line = i.line();
+ if reply.is_some_and(|reply| !reply.contains(&line)) {
+ return Err(format!("{line:?} is not text of the reply"));
+ }
+ }
+ if !(STEPS.0..=STEPS.1).contains(&r.steps.len()) {
+ return Err(format!("{} steps", r.steps.len()));
+ }
+ for (k, step) in r.steps.iter().enumerate() {
+ if step.id != format!("s{k}") {
+ return Err(format!("step id {:?}", step.id));
+ }
+ check_text(&step.text, STEP_MAX, "step")?;
+ texts.push(&step.text);
+ }
+ if r.notes.len() > MAX_NOTES {
+ return Err(format!("{} notes", r.notes.len()));
+ }
+ for n in &r.notes {
+ check_text(n, NOTE_MAX, "note")?;
+ texts.push(n);
+ }
+ }
Block::Comparison(c) => {
if !(2..=8).contains(&c.columns.len()) {
return Err(format!("{} columns", c.columns.len()));
@@ -406,10 +467,22 @@ fn check_source(block: &Block) -> Result<(), String> {
let kind = block.kind();
let table_ok = matches!(kind, "comparison" | "chart" | "metrics");
let list_ok = matches!(kind, "steps" | "metrics" | "facts" | "cards" | "findings");
+ let section_only = s.last_index.is_none() && s.last_ordered.is_none() && s.lead.is_none();
let ok = match s.kind.as_str() {
- "markdown_table" => table_ok && s.ordered.is_none() && s.index.is_some_and(|i| i <= 10_000),
- "markdown_list" => list_ok && s.index.is_some_and(|i| i <= 10_000),
- "slot" => matches!(kind, "verification" | "files") && s.index.is_none() && s.ordered.is_none(),
+ "markdown_table" => table_ok && section_only && s.ordered.is_none() && s.index.is_some_and(|i| i <= 10_000),
+ "markdown_list" => list_ok && section_only && s.index.is_some_and(|i| i <= 10_000),
+ "markdown_section" => {
+ kind == "recipe"
+ && s.ordered.is_some()
+ && s.last_ordered.is_some()
+ && s.lead.is_some_and(|l| l <= MAX_LEAD)
+ && match (s.index, s.last_index) {
+ // The section can't end before it starts
+ (Some(a), Some(b)) => a <= 10_000 && b <= 10_000 && (s.ordered != s.last_ordered || a <= b),
+ _ => false,
+ }
+ }
+ "slot" => matches!(kind, "verification" | "files") && section_only && s.index.is_none() && s.ordered.is_none(),
_ => false,
};
if ok {
@@ -501,7 +574,7 @@ fn check_text(s: &str, max: usize, what: &str) -> Result<(), String> {
/// A text's length as the client counts it (UTF-16 units: an emoji is two), so a text the server
/// stores is one the client's own limit lets through.
-fn utf16_len(s: &str) -> usize {
+pub(super) fn utf16_len(s: &str) -> usize {
s.encode_utf16().count()
}
diff --git a/src/server/spend_stop.rs b/src/server/spend_stop.rs
index e09ad4e1..bc0b7e65 100644
--- a/src/server/spend_stop.rs
+++ b/src/server/spend_stop.rs
@@ -185,7 +185,7 @@ pub async fn check(state: &AppState, space: Option<&SpaceId>) -> Result<(), Stri
if !s.stopped {
return Ok(());
}
- tripped(state, &s, space).await;
+ tripped(state, &s, space, false).await;
Err(stop_error(&s))
}
@@ -197,8 +197,10 @@ const NOTIFY_KEY: &str = "notify";
/// so routines going quiet overnight are heard. It names no bot (the stop holds them all) but
/// carries `space`, the held turn's, so Telegram and push know where it belongs (Rigel's F-D1:
/// without it the Telegram "stuck" message was never sent). A tap opens Needs you, where
-/// Continue is.
-async fn tripped(state: &AppState, s: &Status, space: Option<&SpaceId>) {
+/// Continue is. `held_message` is true only when the held turn was the person's own message
+/// (D-1): a routine, mission or Jira task tripping the stop while the person writes from Telegram
+/// must not be told to them as "your message wasn't run".
+async fn tripped(state: &AppState, s: &Status, space: Option<&SpaceId>, held_message: bool) {
let key = match space {
Some(id) => format!("{NOTIFY_KEY}:{}", id.as_str()),
None => NOTIFY_KEY.to_string(),
@@ -214,13 +216,13 @@ async fn tripped(state: &AppState, s: &Status, space: Option<&SpaceId>) {
title: "Today's spending limit is reached".into(),
body: format!("Used {}, so bots won't start new work until tomorrow. Open to continue today.", used_of(s)),
};
- super::continuity::notify_in(state, n, space).await;
+ super::continuity::notify_held(state, n, space, held_message).await;
}
/// Before a turn takes its slot (`routes::turn_once`): `Err` when today's spending stop holds new
/// turns. Unless the turn is `quiet` (its caller records its own skip), the chat gets one notice
-/// a day, with Continue.
-pub(super) async fn gate(scope: &TurnScope, speaker: &Kwant, quiet: bool) -> Result<(), String> {
+/// a day, with Continue. `person` is true for a turn on the person's own message.
+pub(super) async fn gate(scope: &TurnScope, speaker: &Kwant, quiet: bool, person: bool) -> Result<(), String> {
let s = status(&scope.state).await;
if !s.stopped {
return Ok(());
@@ -228,7 +230,7 @@ pub(super) async fn gate(scope: &TurnScope, speaker: &Kwant, quiet: bool) -> Res
let context = scope.context_id(speaker);
tracing::info!(context = %context, day = %s.day, tokens = s.today_tokens, usd = s.today_usd, "daily spending stop: turn not started");
let space = scope.state.db.space_of_kwant(&speaker.id).await.ok().flatten();
- tripped(&scope.state, &s, space.as_ref()).await;
+ tripped(&scope.state, &s, space.as_ref(), person).await;
if !quiet && scope.state.db.first_spend_notice(&s.day, &format!("chat:{context}")).await.unwrap_or(false) {
let meta = json!({
"kind": REASON,
diff --git a/src/server/sse.rs b/src/server/sse.rs
index f1f9298e..d0f49bda 100644
--- a/src/server/sse.rs
+++ b/src/server/sse.rs
@@ -330,6 +330,7 @@ mod tests {
body: s("x"),
space_id: Some(s("spc_x")),
space_name: None,
+ held_message: false,
},
];
for e in &all {
diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rs
index 44b74fb1..fdc42770 100644
--- a/src/server/telegram/bridge.rs
+++ b/src/server/telegram/bridge.rs
@@ -417,8 +417,8 @@ async fn on_event(state: &AppState, event: &RuntimeEvent) {
approval_closed(state, id, &format!("<i>{}</i>", text::escape(copy::NO_LONGER_WAITING))).await
}
RuntimeEvent::HumanStepUpdated { step } => on_human_step(state, step).await,
- RuntimeEvent::Notify { kind, kwant_name, title, body, space_id: Some(space), channel_id, kwant_id, .. } => {
- on_notify(state, space, kind, kwant_name, title, body, channel_id.as_deref(), kwant_id).await
+ RuntimeEvent::Notify { kind, kwant_name, title, body, space_id: Some(space), channel_id, kwant_id, held_message, .. } => {
+ on_notify(state, space, kind, kwant_name, title, body, channel_id.as_deref(), kwant_id, *held_message).await
}
_ => {}
}
@@ -576,7 +576,7 @@ async fn on_human_step(state: &AppState, step: &Value) {
}
#[allow(clippy::too_many_arguments)]
-async fn on_notify(state: &AppState, space: &str, kind: &str, who: &str, title: &str, body: &str, channel: Option<&str>, kwant: &str) {
+async fn on_notify(state: &AppState, space: &str, kind: &str, who: &str, title: &str, body: &str, channel: Option<&str>, kwant: &str, held_message: bool) {
let tg_kind = if STUCK_KINDS.contains(&kind) {
"stuck"
} else if DONE_KINDS.contains(&kind) {
@@ -591,9 +591,11 @@ async fn on_notify(state: &AppState, space: &str, kind: &str, who: &str, title:
}
let head = if tg_kind == "done" { format!("Done: {}", text::escape(title)) } else { format!("<b>{}</b>", text::escape(title)) };
let mut html = head;
- // The spending stop while the person writes from here: what held is most likely their own
- // message, which isn't replayed after Continue, so say to send it again (Rigel's F-D1)
- let body = if kind == crate::server::spend_stop::REASON && link.reply_window_from.is_some() { copy::SPEND_HELD } else { body };
+ // The spending stop held the person's own message while they write from here: it isn't
+ // replayed after Continue, so say to send it again (Rigel's F-D1). A routine, mission or Jira
+ // task that tripped the stop inside the reply window keeps the plain line (D-1)
+ let own = kind == crate::server::spend_stop::REASON && held_message && link.reply_window_from.is_some();
+ let body = if own { copy::SPEND_HELD } else { body };
if !body.trim().is_empty() {
html.push('\n');
html.push_str(&text::escape(body));
diff --git a/src/setup.rs b/src/setup.rs
index 8dfb68a7..5c79a5a8 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -21,6 +21,10 @@ pub const UV_VERSION: &str = "0.13.5";
/// Playwright, whose `install chromium` puts a private Chromium in the person's cache. Pinned.
pub const PLAYWRIGHT_VERSION: &str = "1.64.1";
pub const CODEX_NPM: &str = "@openai/codex";
+/// Where Codex publishes its standalone builds (one tag per release, `rust-v<version>`).
+pub const CODEX_RELEASES: &str = "https://github.com/openai/codex/releases";
+/// The release's checksum file for its `codex-package-<target>.tar.gz` archives.
+pub const CODEX_SUMS: &str = "codex-package_SHA256SUMS";
/// A part `kwnt setup` can install.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize)]
@@ -220,6 +224,9 @@ pub enum Step {
LayaModel { label: String },
/// Opens the found Chrome without a window to check it starts.
CheckChrome { label: String },
+ /// Downloads Codex's standalone build from its latest GitHub release, checks it against the
+ /// release's SHA-256 list, and links it as `~/.local/bin/codex` (see [`install_codex_release`]).
+ CodexRelease { label: String },
/// Needs admin rights or a download page: shown to the person, never run.
Manual { label: String, command: String },
}
@@ -228,7 +235,7 @@ impl Step {
pub fn label(&self) -> &str {
match self {
Step::Run(c) => &c.label,
- Step::LayaModel { label } | Step::CheckChrome { label } | Step::Manual { label, .. } => label,
+ Step::LayaModel { label } | Step::CheckChrome { label } | Step::CodexRelease { label } | Step::Manual { label, .. } => label,
}
}
@@ -237,6 +244,9 @@ impl Step {
Step::Run(c) => c.display(),
Step::LayaModel { .. } => "(kwant starts Laya once to download and test its routing model)".into(),
Step::CheckChrome { .. } => "(kwant opens the browser once without a window to check it starts)".into(),
+ Step::CodexRelease { .. } => format!(
+ "(kwant downloads codex-package-<this computer>.tar.gz from {CODEX_RELEASES}/latest, checks it against {CODEX_SUMS}, and links ~/.local/bin/codex)"
+ ),
Step::Manual { command, .. } => command.clone(),
}
}
@@ -397,6 +407,10 @@ pub fn plan(item: ItemId, p: &Probe) -> Plan {
(Platform::Mac, None, Some(_)) => {
steps.push(Step::Run(Cmd::new("Install the Codex CLI with Homebrew", &["brew", "install", "--cask", "codex"])))
}
+ // No Node: Codex's own standalone build, which needs nothing else
+ (platform, None, _) if codex_target(platform).is_some() => steps.push(Step::CodexRelease {
+ label: "Download the Codex CLI from its GitHub release into ~/.local/bin (no Node needed)".into(),
+ }),
(Platform::Mac, None, None) => steps.push(Step::Manual {
label: "Install Node.js, then the Codex CLI".into(),
command: format!("Install Node.js from https://nodejs.org, then: npm install -g {CODEX_NPM}"),
@@ -666,6 +680,14 @@ pub async fn run_plan(plan: &Plan, config: &crate::config::Config, log: &(dyn Fn
log(format!("▸ {label}"));
check_chrome(log).await.map_err(|e| format!("{label}: {e}"))?;
}
+ Step::CodexRelease { label } => {
+ log(format!("▸ {label}"));
+ let home = dirs::home_dir().ok_or_else(|| format!("{label}: no home folder"))?;
+ let target = codex_target(Platform::detect()).ok_or_else(|| format!("{label}: no Codex build for this computer"))?;
+ let codex_home = std::env::var_os("CODEX_HOME").filter(|h| !h.is_empty()).map(PathBuf::from);
+ let at = CodexInstall::new(&home, codex_home, target).releases(&codex_releases_url());
+ install_codex_release(&at, log).await.map_err(|e| format!("{label}: {e}"))?;
+ }
}
}
Ok(())
@@ -976,6 +998,256 @@ pub async fn run_cli(config: &crate::config::Config, opts: Options) -> i32 {
}
}
+/// Codex's build name for this computer, as its releases name them (`codex-package-<target>`).
+/// `None` where Codex publishes no standalone build.
+pub fn codex_target(platform: Platform) -> Option<&'static str> {
+ match (platform, std::env::consts::ARCH) {
+ (Platform::Mac, "aarch64") => Some("aarch64-apple-darwin"),
+ (Platform::Mac, "x86_64") => Some("x86_64-apple-darwin"),
+ (Platform::Linux, "aarch64") => Some("aarch64-unknown-linux-musl"),
+ (Platform::Linux, "x86_64") => Some("x86_64-unknown-linux-musl"),
+ _ => None,
+ }
+}
+
+/// [`CODEX_RELEASES`], or in a test build `KWNT_CODEX_RELEASES_URL` (a local fake server).
+pub fn codex_releases_url() -> String {
+ #[cfg(feature = "test-seams")]
+ if let Some(url) = std::env::var("KWNT_CODEX_RELEASES_URL").ok().filter(|u| !u.is_empty()) {
+ return url;
+ }
+ CODEX_RELEASES.to_string()
+}
+
+/// Where [`install_codex_release`] downloads from and installs to. The layout is the one Codex's
+/// own `install.sh` uses, so its updater and kwant agree: each release unpacked in
+/// `$CODEX_HOME/packages/standalone/releases/<version>-<target>`, `current` linking the live one,
+/// and `~/.local/bin/codex` linking `current/bin/codex`.
+#[derive(Clone, Debug)]
+pub struct CodexInstall {
+ pub releases: String,
+ pub target: String,
+ /// `$CODEX_HOME/packages/standalone`.
+ pub root: PathBuf,
+ /// `~/.local/bin`.
+ pub bin_dir: PathBuf,
+ /// Largest archive accepted; the real ones are about 200 MB.
+ pub max_bytes: u64,
+}
+
+impl CodexInstall {
+ pub fn new(home: &Path, codex_home: Option<PathBuf>, target: &str) -> Self {
+ let codex_home = codex_home.unwrap_or_else(|| home.join(".codex"));
+ Self {
+ releases: CODEX_RELEASES.to_string(),
+ target: target.to_string(),
+ root: codex_home.join("packages").join("standalone"),
+ bin_dir: home.join(".local").join("bin"),
+ max_bytes: 1 << 30,
+ }
+ }
+
+ pub fn releases(mut self, url: &str) -> Self {
+ self.releases = url.trim_end_matches('/').to_string();
+ self
+ }
+
+ pub fn asset(&self) -> String {
+ format!("codex-package-{}.tar.gz", self.target)
+ }
+
+ /// `~/.local/bin/codex`.
+ pub fn command(&self) -> PathBuf {
+ self.bin_dir.join("codex")
+ }
+}
+
+/// Installs Codex's latest standalone build: finds the latest tag, reads the release's
+/// [`CODEX_SUMS`], downloads `codex-package-<target>.tar.gz` and checks its SHA-256 before
+/// anything is unpacked, then unpacks it next to earlier releases, switches `current` to it and
+/// links `~/.local/bin/codex`. A download that doesn't match is deleted and nothing changes.
+/// Returns the linked command.
+pub async fn install_codex_release(at: &CodexInstall, log: &(dyn Fn(String) + Send + Sync)) -> Result<PathBuf, String> {
+ use futures::StreamExt;
+ use sha2::{Digest, Sha256};
+ use tokio::io::AsyncWriteExt;
+
+ let client = reqwest::Client::builder()
+ .connect_timeout(Duration::from_secs(30))
+ .user_agent(concat!("kwnt/", env!("CARGO_PKG_VERSION")))
+ .build()
+ .map_err(|e| e.to_string())?;
+ let fetch = |url: String| {
+ let client = client.clone();
+ async move {
+ let r = client.get(&url).send().await.map_err(|e| format!("couldn't reach {url}: {e}"))?;
+ if !r.status().is_success() {
+ return Err(format!("{url} answered {}", r.status()));
+ }
+ Ok::<_, String>(r)
+ }
+ };
+
+ // The latest tag, from where /latest redirects to (…/releases/tag/rust-v0.167.0)
+ let latest = fetch(format!("{}/latest", at.releases)).await?;
+ let tag = latest
+ .url()
+ .path_segments()
+ .and_then(|mut s| s.next_back())
+ .map(str::to_string)
+ .filter(|t| t.starts_with("rust-v") && t.len() > 6 && t.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)))
+ .ok_or_else(|| format!("couldn't tell the latest Codex release from {}", latest.url()))?;
+ drop(latest);
+ let version = tag.trim_start_matches("rust-v").to_string();
+ let asset = at.asset();
+ log(format!(" Codex {version} ({asset})"));
+
+ let sums_url = format!("{}/download/{tag}/{CODEX_SUMS}", at.releases);
+ let sums = fetch(sums_url.clone()).await?.text().await.map_err(|e| format!("{sums_url}: {e}"))?;
+ let want = sums
+ .lines()
+ .filter_map(|l| {
+ let mut w = l.split_whitespace();
+ Some((w.next()?, w.next()?.trim_start_matches('*')))
+ })
+ .find(|(_, name)| *name == asset)
+ .map(|(sum, _)| sum.to_ascii_lowercase())
+ .filter(|sum| sum.len() == 64 && sum.chars().all(|c| c.is_ascii_hexdigit()))
+ .ok_or_else(|| format!("{CODEX_SUMS} of Codex {version} has no SHA-256 for {asset}"))?;
+
+ std::fs::create_dir_all(&at.root).map_err(|e| format!("couldn't make {}: {e}", at.root.display()))?;
+ let archive = at.root.join(format!(".download.{}.tar.gz", std::process::id()));
+ struct Cleanup(PathBuf);
+ impl Drop for Cleanup {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+ }
+ let _cleanup = Cleanup(archive.clone());
+
+ let url = format!("{}/download/{tag}/{asset}", at.releases);
+ let resp = fetch(url.clone()).await?;
+ let total = resp.content_length().filter(|n| *n > 0);
+ if total.is_some_and(|n| n > at.max_bytes) {
+ return Err(format!("{asset} is larger than {} MB", at.max_bytes >> 20));
+ }
+ let mut file = tokio::fs::File::create(&archive).await.map_err(|e| format!("couldn't write {}: {e}", archive.display()))?;
+ let mut hasher = Sha256::new();
+ let (mut got, mut next_note) = (0u64, 0u64);
+ let mut body = resp.bytes_stream();
+ loop {
+ let chunk = match tokio::time::timeout(Duration::from_secs(120), body.next()).await {
+ Err(_) => return Err(format!("the download of {asset} stalled")),
+ Ok(None) => break,
+ Ok(Some(c)) => c.map_err(|e| format!("the download of {asset} broke off: {e}"))?,
+ };
+ got += chunk.len() as u64;
+ if got > at.max_bytes {
+ return Err(format!("{asset} is larger than {} MB", at.max_bytes >> 20));
+ }
+ hasher.update(&chunk);
+ file.write_all(&chunk).await.map_err(|e| format!("couldn't write {}: {e}", archive.display()))?;
+ if got >= next_note {
+ match total {
+ Some(t) => log(format!(" downloaded {} of {} MB", got >> 20, t >> 20)),
+ None => log(format!(" downloaded {} MB", got >> 20)),
+ }
+ next_note = got + (25 << 20);
+ }
+ }
+ file.flush().await.map_err(|e| e.to_string())?;
+ drop(file);
+ let have: String = hasher.finalize().iter().map(|b| format!("{b:02x}")).collect();
+ if have != want {
+ return Err(format!(
+ "the download doesn't match the SHA-256 in Codex {version}'s {CODEX_SUMS}, so it wasn't installed (try again later)"
+ ));
+ }
+ log(format!(" SHA-256 matches {CODEX_SUMS}"));
+
+ // Unpack beside earlier releases, then switch over
+ let releases = at.root.join("releases");
+ let release = releases.join(format!("{version}-{}", at.target));
+ let staging = releases.join(format!(".staging.{version}-{}.{}", at.target, std::process::id()));
+ let _ = std::fs::remove_dir_all(&staging);
+ std::fs::create_dir_all(&staging).map_err(|e| format!("couldn't make {}: {e}", staging.display()))?;
+ let unpack = tokio::process::Command::new("tar")
+ .arg("-xzf")
+ .arg(&archive)
+ .arg("-C")
+ .arg(&staging)
+ .stdin(Stdio::null())
+ .output()
+ .await
+ .map_err(|e| format!("couldn't run tar: {e}"))?;
+ let codex = staging.join("bin").join("codex");
+ if !unpack.status.success() || !codex.is_file() {
+ let _ = std::fs::remove_dir_all(&staging);
+ let why = String::from_utf8_lossy(&unpack.stderr).lines().next().unwrap_or_default().to_string();
+ return Err(format!("{asset} didn't unpack to bin/codex {why}").trim_end().to_string());
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let _ = std::fs::set_permissions(&codex, std::fs::Permissions::from_mode(0o755));
+ let _ = std::os::unix::fs::symlink("bin/codex", staging.join("codex"));
+ }
+ if release.exists() {
+ std::fs::remove_dir_all(&release).map_err(|e| format!("couldn't replace {}: {e}", release.display()))?;
+ }
+ std::fs::rename(&staging, &release).map_err(|e| format!("couldn't move Codex into place: {e}"))?;
+
+ let current = at.root.join("current");
+ replace_with_symlink(&current, &release)?;
+ std::fs::create_dir_all(&at.bin_dir).map_err(|e| format!("couldn't make {}: {e}", at.bin_dir.display()))?;
+ let command = at.command();
+ replace_with_symlink(&command, &current.join("bin").join("codex"))?;
+ // Codex looks for its code-mode helper on the PATH on a Mac (as its own installer links it)
+ let helper = current.join("bin").join("codex-code-mode-host");
+ if at.target.ends_with("apple-darwin") && release.join("bin").join("codex-code-mode-host").is_file() {
+ replace_with_symlink(&at.bin_dir.join("codex-code-mode-host"), &helper)?;
+ }
+
+ let check = tokio::time::timeout(
+ Duration::from_secs(60),
+ tokio::process::Command::new(&command).arg("--version").stdin(Stdio::null()).output(),
+ )
+ .await;
+ match check {
+ Ok(Ok(out)) if out.status.success() => {
+ let said = String::from_utf8_lossy(&out.stdout).lines().next().unwrap_or_default().trim().to_string();
+ log(format!(" {} → {said}", command.display()));
+ Ok(command)
+ }
+ Ok(Ok(out)) => Err(format!("the installed codex didn't start ({})", out.status)),
+ Ok(Err(e)) => Err(format!("the installed codex didn't start: {e}")),
+ Err(_) => Err("the installed codex didn't answer --version within a minute".into()),
+ }
+}
+
+/// Points `link` at `target`, replacing what was there in one rename.
+fn replace_with_symlink(link: &Path, target: &Path) -> Result<(), String> {
+ #[cfg(unix)]
+ {
+ let tmp = link.with_file_name(format!(
+ ".{}.{}",
+ link.file_name().and_then(|n| n.to_str()).unwrap_or("link"),
+ std::process::id()
+ ));
+ let _ = std::fs::remove_file(&tmp);
+ std::os::unix::fs::symlink(target, &tmp).map_err(|e| format!("couldn't link {}: {e}", link.display()))?;
+ std::fs::rename(&tmp, link).map_err(|e| {
+ let _ = std::fs::remove_file(&tmp);
+ format!("couldn't link {}: {e}", link.display())
+ })
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = (link, target);
+ Err("Codex's standalone build is installed on a Mac or Linux only".into())
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1137,10 +1409,12 @@ mod tests {
assert_eq!(shown(&plan(ItemId::Claude, &p)), vec!["curl -fsSL https://claude.ai/install.sh | bash"]);
assert_eq!(shown(&plan(ItemId::Grok, &p)), vec!["curl -fsSL https://x.ai/cli/install.sh | bash"]);
- // codex: no Node on Linux → the person installs Node (sudo), nothing runs
+ // codex: no Node on Linux → Codex's standalone build, no sudo (0.7.6, O4)
let pl = plan(ItemId::Codex, &p);
- assert!(!pl.automatic());
- assert!(shown(&pl)[0].starts_with("sudo apt-get install -y nodejs npm, then: npm install -g --prefix ~/.local @openai/codex"));
+ assert!(pl.automatic());
+ assert!(matches!(pl.steps.as_slice(), [Step::CodexRelease { .. }]), "{pl:?}");
+ assert!(shown(&pl)[0].contains("codex-package_SHA256SUMS"), "{:?}", shown(&pl));
+ never_sudo(&pl);
let mut p = bare(Platform::Linux);
p.npm = Some("/usr/bin/npm".into());
@@ -1151,8 +1425,11 @@ mod tests {
let mut m = mac();
m.brew = Some("/opt/homebrew/bin/brew".into());
assert_eq!(shown(&plan(ItemId::Codex, &m)), vec!["brew install --cask codex"]);
+ // No Node and no Homebrew: Codex's standalone build (0.7.6, O4)
m.brew = None;
- assert!(shown(&plan(ItemId::Codex, &m))[0].contains("https://nodejs.org"));
+ let pl = plan(ItemId::Codex, &m);
+ assert!(pl.automatic());
+ assert!(matches!(pl.steps.as_slice(), [Step::CodexRelease { .. }]), "{pl:?}");
let mut installed = bare(Platform::Linux);
installed.clis[0].1 = Some("/home/u/.local/bin/claude".into());
@@ -1198,7 +1475,7 @@ mod tests {
assert!(row(ItemId::Browser).can_install);
assert_eq!(row(ItemId::Laya).need, Need::Recommended);
assert_eq!(row(ItemId::Claude).need, Need::Recommended);
- assert!(!row(ItemId::Codex).can_install, "codex needs Node via sudo here");
+ assert!(row(ItemId::Codex).can_install, "codex installs without Node (O4)");
assert_eq!(row(ItemId::Docker).need, Need::Optional);
assert!(!row(ItemId::Docker).can_install);
diff --git a/tests/browser_stream_test.rs b/tests/browser_stream_test.rs
index 123c5b2d..284c4750 100644
--- a/tests/browser_stream_test.rs
+++ b/tests/browser_stream_test.rs
@@ -542,6 +542,10 @@ async fn a_watcher_is_told_to_take_control_and_a_lost_frame_ack_does_not_drop_th
let other = ctrl.take_control().await.unwrap();
ws.send(WsMessage::Text(json!({"action":"history","direction":"reload","id":"o"}).to_string())).await.unwrap();
assert!(receive(&mut ws,"error").await["error"].as_str().unwrap().contains("controlled by a person"));
+ // Take over from here while that other view has it: the person's own hold, not a busy bot
+ ws.send(WsMessage::Text(json!({"action":"take_control"}).to_string())).await.unwrap();
+ assert_eq!(receive(&mut ws,"error").await, json!({"type":"error","code":"held_by_person",
+ "error":"You're controlling this browser in another window. Press Hand back there to take over here."}));
drop(other);
// the server stops waiting for the lost ack and keeps the stream (and control) alive
diff --git a/tests/chrome_download_test.rs b/tests/chrome_download_test.rs
new file mode 100644
index 00000000..83d3fee8
--- /dev/null
+++ b/tests/chrome_download_test.rs
@@ -0,0 +1,381 @@
+//! The bots' private browser without Node (0.7.6, O5): Chrome for Testing is downloaded the first
+//! time a bot needs a browser and there's no Chrome. Everything here talks to a local fake of
+//! Google's build list and storage; nothing is downloaded from the internet.
+mod common;
+
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use axum::extract::State;
+use axum::http::{StatusCode, Uri};
+use axum::response::{IntoResponse, Response};
+use axum::routing::get;
+use axum::{Json, Router};
+use kwnt::sandbox::chrome_download::{self, binary_in, cache_root, ChromeSetup, SetupState, FAILED_LINE};
+use kwnt::sandbox::computer::find_chrome;
+use serde_json::json;
+
+const VERSION: &str = "131.0.6778.85";
+
+/// A Chrome for Testing zip for linux64 whose `chrome` is a script answering `--version`.
+fn build(chrome: &str) -> Vec<u8> {
+ let mut out = std::io::Cursor::new(Vec::new());
+ {
+ let mut zip = zip::ZipWriter::new(&mut out);
+ let exe = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Stored)
+ .unix_permissions(0o755);
+ let file = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Stored)
+ .unix_permissions(0o644);
+ zip.add_directory("chrome-linux64/", exe).unwrap();
+ zip.start_file("chrome-linux64/chrome", exe).unwrap();
+ zip.write_all(chrome.as_bytes()).unwrap();
+ zip.start_file("chrome-linux64/resources.pak", file).unwrap();
+ zip.write_all(&vec![7u8; 4096]).unwrap();
+ zip.finish().unwrap();
+ }
+ out.into_inner()
+}
+
+fn good_build() -> Vec<u8> {
+ build(&format!("#!/bin/sh\necho 'Google Chrome for Testing {VERSION} '\n"))
+}
+
+#[derive(Clone)]
+struct Fake {
+ /// What storage answers: the zip, or an error status.
+ zip: Arc<Mutex<Result<Vec<u8>, u16>>>,
+ /// Where the build list says the download is (None: on the fake storage).
+ url: Arc<Mutex<Option<String>>>,
+ /// Storage answers the build's address with a 302 to here (relative or full).
+ redirect: Arc<Mutex<Option<String>>>,
+ base: String,
+ list_hits: Arc<AtomicUsize>,
+ zip_hits: Arc<AtomicUsize>,
+ /// Requests to /elsewhere/, a host path outside Google's storage.
+ elsewhere_hits: Arc<AtomicUsize>,
+}
+
+impl Fake {
+ fn serve(&self, zip: Result<Vec<u8>, u16>) {
+ *self.zip.lock().unwrap() = zip;
+ }
+ fn json(&self) -> String {
+ format!("{}/cft.json", self.base)
+ }
+ fn storage(&self) -> String {
+ format!("{}/storage/", self.base)
+ }
+ fn setup(&self, home: &Path) -> ChromeSetup {
+ ChromeSetup::new(cache_root("linux", home), Some("linux64")).source(&self.json(), &self.storage())
+ }
+}
+
+async fn list(State(f): State<Fake>) -> Json<serde_json::Value> {
+ f.list_hits.fetch_add(1, Ordering::SeqCst);
+ let url = f
+ .url
+ .lock()
+ .unwrap()
+ .clone()
+ .unwrap_or_else(|| format!("{}{VERSION}/linux64/chrome-linux64.zip", f.storage()));
+ Json(json!({
+ "timestamp": "2026-11-07T00:00:00.000Z",
+ "channels": {
+ "Stable": {
+ "channel": "Stable",
+ "version": VERSION,
+ "revision": "1381561",
+ "downloads": {
+ "chrome": [
+ {"platform": "mac-arm64", "url": format!("{}{VERSION}/mac-arm64/chrome-mac-arm64.zip", f.storage())},
+ {"platform": "linux64", "url": url},
+ ],
+ "chromedriver": []
+ }
+ },
+ "Beta": {"channel": "Beta", "version": "132.0.0.0", "downloads": {"chrome": []}}
+ }
+ }))
+}
+
+async fn storage(State(f): State<Fake>, uri: Uri) -> Response {
+ f.zip_hits.fetch_add(1, Ordering::SeqCst);
+ assert!(uri.path().ends_with("/linux64/chrome-linux64.zip"), "{}", uri.path());
+ let to = f.redirect.lock().unwrap().clone();
+ if let Some(to) = to.filter(|to| !to.ends_with(uri.path())) {
+ return Response::builder().status(StatusCode::FOUND).header("location", to).body(axum::body::Body::empty()).unwrap();
+ }
+ match f.zip.lock().unwrap().clone() {
+ Ok(bytes) => bytes.into_response(),
+ Err(code) => StatusCode::from_u16(code).unwrap().into_response(),
+ }
+}
+
+async fn elsewhere(State(f): State<Fake>) -> Response {
+ f.elsewhere_hits.fetch_add(1, Ordering::SeqCst);
+ f.zip.lock().unwrap().clone().unwrap_or_default().into_response()
+}
+
+async fn fake() -> Fake {
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let base = format!("http://{}", listener.local_addr().unwrap());
+ let f = Fake {
+ zip: Arc::new(Mutex::new(Ok(good_build()))),
+ url: Default::default(),
+ redirect: Default::default(),
+ base,
+ list_hits: Default::default(),
+ zip_hits: Default::default(),
+ elsewhere_hits: Default::default(),
+ };
+ let app = Router::new()
+ .route("/cft.json", get(list))
+ .route("/storage/*rest", get(storage))
+ .route("/elsewhere/*rest", get(elsewhere))
+ .with_state(f.clone());
+ tokio::spawn(async move {
+ let _ = axum::serve(listener, app).await;
+ });
+ f
+}
+
+/// Everything in the cache folder (names only), to show nothing half-done is left behind.
+fn left_in(root: &Path) -> Vec<String> {
+ let mut names: Vec<String> = std::fs::read_dir(root)
+ .map(|d| d.flatten().map(|e| e.file_name().to_string_lossy().to_string()).collect())
+ .unwrap_or_default();
+ names.sort();
+ names
+}
+
+fn installed_at(home: &Path) -> PathBuf {
+ cache_root("linux", home).join(format!("{VERSION}-linux64")).join(binary_in("linux64"))
+}
+
+#[tokio::test]
+async fn the_first_need_downloads_the_build_once_and_it_is_found_after() {
+ let f = fake().await;
+ let home = tempfile::tempdir().unwrap();
+ let setup = Arc::new(f.setup(home.path()));
+ assert!(setup.available());
+ assert_eq!(setup.view().state, SetupState::Idle);
+ assert_eq!(setup.installed(), None);
+
+ // two bots needing a browser at once share one download
+ let (a, b) = tokio::join!(setup.ensure(), setup.ensure());
+ let want = installed_at(home.path());
+ assert_eq!(a.unwrap(), want);
+ assert_eq!(b.unwrap(), want);
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 1);
+ assert_eq!(f.list_hits.load(Ordering::SeqCst), 1);
+
+ let v = setup.view();
+ assert_eq!(v.state, SetupState::Ready);
+ assert_eq!(v.error, None);
+ assert_eq!(v.version.as_deref(), Some(VERSION));
+ assert_eq!(left_in(&cache_root("linux", home.path())), vec![format!("{VERSION}-linux64")]);
+ let out = std::process::Command::new(&want).arg("--version").output().unwrap();
+ assert!(String::from_utf8_lossy(&out.stdout).contains(VERSION));
+
+ // the next need, and a restarted kwnt, use it without downloading again
+ assert_eq!(setup.ensure().await.unwrap(), want);
+ let after_restart = f.setup(home.path());
+ assert_eq!(after_restart.view().state, SetupState::Ready);
+ assert_eq!(after_restart.ensure().await.unwrap(), want);
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 1);
+ assert_eq!(f.list_hits.load(Ordering::SeqCst), 1);
+
+ // local mode finds it like any other Chrome, after an installed one
+ assert_eq!(chrome_download::downloaded_chrome("linux", home.path()), Some(want.clone()));
+ assert_eq!(find_chrome(None, "linux", Some(home.path()), Some("")), Some(want.clone()));
+ let bin = tempfile::tempdir().unwrap();
+ // never run here, so a plain executable file is enough
+ std::fs::write(bin.path().join("chromium"), "#!/bin/sh\n").unwrap();
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(bin.path().join("chromium"), std::fs::Permissions::from_mode(0o755)).unwrap();
+ }
+ assert_eq!(
+ find_chrome(None, "linux", Some(home.path()), Some(&bin.path().to_string_lossy())),
+ Some(bin.path().join("chromium"))
+ );
+}
+
+#[tokio::test]
+async fn a_failed_download_shows_the_line_and_try_again_fetches_it() {
+ let f = fake().await;
+ f.serve(Err(503));
+ let home = tempfile::tempdir().unwrap();
+ let setup = Arc::new(f.setup(home.path()));
+
+ let err = setup.ensure().await.unwrap_err();
+ assert!(err.starts_with(FAILED_LINE), "{err}");
+ let v = setup.view();
+ assert_eq!(v.state, SetupState::Failed);
+ assert_eq!(
+ v.error.as_deref(),
+ Some("The bots' browser couldn't be set up. Bots can still answer; web pages won't open.")
+ );
+ assert!(v.detail.as_deref().unwrap().contains("503"), "{v:?}");
+ assert_eq!(left_in(&cache_root("linux", home.path())), Vec::<String>::new());
+
+ // the next bot that needs it gets the failure at once, without another download
+ assert!(setup.ensure().await.unwrap_err().starts_with(FAILED_LINE));
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 1);
+
+ // "Try again"
+ f.serve(Ok(good_build()));
+ setup.retry();
+ for _ in 0..200 {
+ if setup.view().state == SetupState::Ready {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+ }
+ let v = setup.view();
+ assert_eq!(v.state, SetupState::Ready, "{v:?}");
+ assert_eq!((v.error, v.detail), (None, None));
+ assert_eq!(setup.installed(), Some(installed_at(home.path())));
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 2);
+}
+
+#[tokio::test]
+async fn a_broken_download_is_never_installed() {
+ let f = fake().await;
+ let no_browser = {
+ let mut out = std::io::Cursor::new(Vec::new());
+ let mut zip = zip::ZipWriter::new(&mut out);
+ zip.start_file("chrome-linux64/README", zip::write::SimpleFileOptions::default()).unwrap();
+ zip.write_all(b"hi").unwrap();
+ zip.finish().unwrap();
+ out.into_inner()
+ };
+ let cases = [
+ (b"<html>not a zip</html>".to_vec(), "isn't a readable zip"),
+ (no_browser, "has no browser inside"),
+ (build("#!/bin/sh\necho 'error while loading shared libraries' >&2\nexit 127\n"), "doesn't start here"),
+ (build("#!/bin/sh\necho hello\n"), "doesn't start here"),
+ ];
+ for (zip, why) in cases {
+ f.serve(Ok(zip));
+ let home = tempfile::tempdir().unwrap();
+ let setup = f.setup(home.path());
+ let err = setup.ensure().await.unwrap_err();
+ assert!(err.starts_with(FAILED_LINE) && err.contains(why), "{why}: {err}");
+ assert!(setup.view().detail.unwrap().contains(why));
+ assert_eq!(setup.installed(), None, "{why}");
+ assert_eq!(left_in(&cache_root("linux", home.path())), Vec::<String>::new(), "{why}");
+ assert_eq!(find_chrome(None, "linux", Some(home.path()), Some("")), None, "{why}");
+ }
+}
+
+#[tokio::test]
+async fn a_download_outside_googles_storage_or_over_the_size_cap_is_refused() {
+ let f = fake().await;
+ *f.url.lock().unwrap() = Some(format!("{}/elsewhere/{VERSION}/linux64/chrome-linux64.zip", f.base));
+ let home = tempfile::tempdir().unwrap();
+ let err = f.setup(home.path()).ensure().await.unwrap_err();
+ assert!(err.contains("somewhere other than Google's storage"), "{err}");
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 0);
+
+ *f.url.lock().unwrap() = Some(format!("{}{VERSION}/../../elsewhere/linux64/chrome-linux64.zip", f.storage()));
+ let err = f.setup(home.path()).ensure().await.unwrap_err();
+ assert!(err.contains("somewhere other than Google's storage"), "{err}");
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 0);
+
+ *f.url.lock().unwrap() = None;
+ let err = f.setup(home.path()).max_bytes(1000).ensure().await.unwrap_err();
+ assert!(err.contains("larger than"), "{err}");
+ assert_eq!(left_in(&cache_root("linux", home.path())), Vec::<String>::new());
+}
+
+#[tokio::test]
+async fn a_redirect_off_googles_storage_is_not_followed() {
+ let f = fake().await;
+ // N-3 (Rigel's x6): the build list points at storage, and storage redirects the zip elsewhere
+ let away = [
+ format!("{}/elsewhere/{VERSION}/linux64/chrome-linux64.zip", f.base),
+ format!("/storage/../elsewhere/{VERSION}/linux64/chrome-linux64.zip"),
+ ];
+ for to in away {
+ *f.redirect.lock().unwrap() = Some(to.clone());
+ let home = tempfile::tempdir().unwrap();
+ let setup = f.setup(home.path());
+ let err = setup.ensure().await.unwrap_err();
+ assert!(err.starts_with(FAILED_LINE) && err.contains("redirected away from Google's storage"), "{to}: {err}");
+ assert_eq!(setup.view().state, SetupState::Failed, "{to}");
+ assert_eq!(f.elsewhere_hits.load(Ordering::SeqCst), 0, "{to}: the redirect was followed");
+ assert_eq!(setup.installed(), None, "{to}");
+ assert_eq!(left_in(&cache_root("linux", home.path())), Vec::<String>::new(), "{to}");
+ }
+
+ // a hop that stays inside the storage folder is still followed
+ *f.redirect.lock().unwrap() = Some(format!("{}moved/{VERSION}/linux64/chrome-linux64.zip", f.storage()));
+ let home = tempfile::tempdir().unwrap();
+ let setup = f.setup(home.path());
+ assert_eq!(setup.ensure().await.unwrap(), installed_at(home.path()));
+ assert_eq!(f.elsewhere_hits.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn no_build_for_this_computer_downloads_nothing_and_shows_no_line() {
+ let f = fake().await;
+ let home = tempfile::tempdir().unwrap();
+ // Linux on ARM, say: Google has no build
+ let setup = Arc::new(ChromeSetup::new(cache_root("linux", home.path()), None).source(&f.json(), &f.storage()));
+ assert!(!setup.available());
+ assert!(setup.ensure().await.is_err());
+ setup.retry();
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ let v = setup.view();
+ assert_eq!(v.state, SetupState::Unavailable);
+ assert_eq!(v.error, None);
+ assert_eq!(f.list_hits.load(Ordering::SeqCst), 0);
+ assert_eq!(f.zip_hits.load(Ordering::SeqCst), 0);
+}
+
+#[tokio::test]
+async fn settings_show_the_setup_and_try_again_restarts_it() {
+ let f = fake().await;
+ f.serve(Err(500));
+ let home = tempfile::tempdir().unwrap();
+ let setup = f.setup(home.path());
+ let data = tempfile::tempdir().unwrap();
+ let env = common::setup_with(|state| {
+ state.browser_service = Arc::new(
+ kwnt::sandbox::service::BrowserService::new(data.path().to_path_buf(), None).with_chrome_setup(setup),
+ );
+ })
+ .await;
+ let (s, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert_eq!(v["browser_setup"]["state"], "idle", "{v}");
+ assert!(v["browser_setup"]["error"].is_null());
+
+ // a bot needed the browser and the download failed
+ assert!(env.state.browser_service.chrome_setup().ensure().await.is_err());
+ let (_, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;
+ assert_eq!(v["browser_setup"]["state"], "failed");
+ assert_eq!(v["browser_setup"]["error"], FAILED_LINE);
+
+ // only the person can press Try again
+ assert_eq!(common::call_remote(&env.app, "POST", "/api/settings/computer/browser").await, StatusCode::UNAUTHORIZED);
+
+ f.serve(Ok(good_build()));
+ let (s, v) = common::call(&env.app, "POST", "/api/settings/computer/browser", None).await;
+ assert_eq!(s, StatusCode::OK);
+ assert!(["downloading", "ready"].contains(&v["browser_setup"]["state"].as_str().unwrap()), "{v}");
+ common::wait_for("the private browser", || async {
+ let (_, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;
+ v["browser_setup"]["state"] == "ready"
+ })
+ .await;
+ let (_, v) = common::call(&env.app, "GET", "/api/settings/computer", None).await;
+ assert_eq!(v["browser_setup"]["version"], VERSION);
+ assert!(v["browser_setup"]["error"].is_null());
+}
diff --git a/tests/codex_release_test.rs b/tests/codex_release_test.rs
new file mode 100644
index 00000000..d40c9a27
--- /dev/null
+++ b/tests/codex_release_test.rs
@@ -0,0 +1,233 @@
+//! Codex without Node (0.7.6, O4): `install_codex_release` against a local fake of Codex's
+//! GitHub releases. Nothing here reaches the internet.
+#![cfg(unix)]
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ extract::{Path as UrlPath, State},
+ http::{header, StatusCode},
+ response::{IntoResponse, Response},
+ routing::get,
+ Router,
+};
+use kwnt::setup::{install_codex_release, CodexInstall, CODEX_SUMS};
+use sha2::{Digest, Sha256};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use tempfile::{tempdir, TempDir};
+
+const TARGET: &str = "aarch64-unknown-linux-musl";
+
+#[derive(Clone, Default)]
+struct Release {
+ tag: String,
+ sums: String,
+ archive: Vec<u8>,
+ hits: Arc<Mutex<Vec<String>>>,
+}
+
+async fn latest(State(r): State<Release>) -> Response {
+ r.hits.lock().unwrap().push("latest".into());
+ (StatusCode::FOUND, [(header::LOCATION, format!("/releases/tag/{}", r.tag))]).into_response()
+}
+
+async fn tag_page(UrlPath(_tag): UrlPath<String>) -> &'static str {
+ "<html>release</html>"
+}
+
+async fn download(State(r): State<Release>, UrlPath((tag, name)): UrlPath<(String, String)>) -> Response {
+ r.hits.lock().unwrap().push(format!("{tag}/{name}"));
+ if tag != r.tag {
+ return StatusCode::NOT_FOUND.into_response();
+ }
+ if name == CODEX_SUMS {
+ r.sums.clone().into_response()
+ } else if name.starts_with("codex-package-") && name.ends_with(".tar.gz") {
+ r.archive.clone().into_response()
+ } else {
+ StatusCode::NOT_FOUND.into_response()
+ }
+}
+
+async fn serve(r: Release) -> String {
+ let app = Router::new()
+ .route("/releases/latest", get(latest))
+ .route("/releases/tag/:tag", get(tag_page))
+ .route("/releases/download/:tag/:name", get(download))
+ .with_state(r);
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ format!("http://{addr}/releases")
+}
+
+/// A codex package as the release ships it: bin/codex, its helper, and rg.
+fn package(dir: &Path, version: &str) -> Vec<u8> {
+ let pkg = dir.join(format!("pkg-{version}"));
+ std::fs::create_dir_all(pkg.join("bin")).unwrap();
+ std::fs::create_dir_all(pkg.join("codex-path")).unwrap();
+ exe::write_executable(pkg.join("bin/codex"), format!("#!/bin/sh\necho \"codex-cli {version}\"\n"));
+ exe::write_executable(pkg.join("bin/codex-code-mode-host"), "#!/bin/sh\n");
+ exe::write_executable(pkg.join("codex-path/rg"), "#!/bin/sh\n");
+ std::fs::write(pkg.join("codex-package.json"), "{}").unwrap();
+ let out = dir.join(format!("pkg-{version}.tar.gz"));
+ let ok = std::process::Command::new("tar").arg("-czf").arg(&out).arg("-C").arg(&pkg).arg(".").status().unwrap();
+ assert!(ok.success());
+ std::fs::read(out).unwrap()
+}
+
+fn sha(bytes: &[u8]) -> String {
+ Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
+}
+
+fn release(tmp: &Path, version: &str) -> Release {
+ let archive = package(tmp, version);
+ let sums = format!(
+ "{} codex-app-server-package-{TARGET}.tar.gz\n{} codex-package-{TARGET}.tar.gz\n{} codex-package-x86_64-apple-darwin.tar.gz\n",
+ sha(b"other"),
+ sha(&archive),
+ sha(b"mac")
+ );
+ Release { tag: format!("rust-v{version}"), sums, archive, ..Default::default() }
+}
+
+struct Run {
+ at: CodexInstall,
+ home: PathBuf,
+ lines: Arc<Mutex<Vec<String>>>,
+ _tmp: TempDir,
+}
+
+fn run_in(tmp: TempDir, url: &str) -> Run {
+ let home = tmp.path().join("home");
+ let at = CodexInstall::new(&home, None, TARGET).releases(url);
+ Run { at, home, lines: Default::default(), _tmp: tmp }
+}
+
+async fn install(run: &Run) -> Result<PathBuf, String> {
+ let lines = run.lines.clone();
+ let log = move |l: String| lines.lock().unwrap().push(l);
+ install_codex_release(&run.at, &log).await
+}
+
+fn version_of(cmd: &Path) -> String {
+ let out = std::process::Command::new(cmd).arg("--version").output().unwrap();
+ String::from_utf8_lossy(&out.stdout).trim().to_string()
+}
+
+#[tokio::test]
+async fn installs_the_checked_build_into_local_bin_without_node() {
+ let tmp = tempdir().unwrap();
+ let rel = release(tmp.path(), "9.9.9");
+ let hits = rel.hits.clone();
+ let url = serve(rel).await;
+ let run = run_in(tmp, &url);
+
+ let cmd = install(&run).await.expect("installs");
+ assert_eq!(cmd, run.home.join(".local/bin/codex"));
+ assert_eq!(version_of(&cmd), "codex-cli 9.9.9");
+ // Codex's own installer layout: releases/<version>-<target>, current, ~/.local/bin/codex
+ let root = run.home.join(".codex/packages/standalone");
+ let release = root.join(format!("releases/9.9.9-{TARGET}"));
+ assert!(release.join("bin/codex").is_file());
+ assert!(release.join("codex-path/rg").is_file());
+ assert_eq!(std::fs::read_link(root.join("current")).unwrap(), release);
+ assert_eq!(std::fs::read_link(&cmd).unwrap(), root.join("current/bin/codex"));
+ // Linux: no helper link in ~/.local/bin (Codex's installer links it on a Mac only)
+ assert!(!run.home.join(".local/bin/codex-code-mode-host").exists());
+ // Nothing left behind: no archive, no staging folder
+ let leftovers: Vec<_> = std::fs::read_dir(&root).unwrap().map(|e| e.unwrap().file_name()).collect();
+ assert_eq!(leftovers.len(), 2, "{leftovers:?}");
+ assert_eq!(std::fs::read_dir(root.join("releases")).unwrap().count(), 1);
+
+ let lines = run.lines.lock().unwrap().join("\n");
+ assert!(lines.contains("Codex 9.9.9"), "{lines}");
+ assert!(lines.contains("SHA-256 matches"), "{lines}");
+ assert!(lines.contains("codex-cli 9.9.9"), "{lines}");
+ assert_eq!(
+ *hits.lock().unwrap(),
+ vec!["latest".to_string(), format!("rust-v9.9.9/{CODEX_SUMS}"), format!("rust-v9.9.9/codex-package-{TARGET}.tar.gz")]
+ );
+}
+
+#[tokio::test]
+async fn a_download_that_doesnt_match_the_release_sha256_is_never_installed() {
+ let tmp = tempdir().unwrap();
+ let mut rel = release(tmp.path(), "9.9.9");
+ // Same size, one byte changed in transit
+ let last = rel.archive.len() - 1;
+ rel.archive[last] ^= 0xff;
+ let url = serve(rel).await;
+ let run = run_in(tmp, &url);
+
+ let err = install(&run).await.unwrap_err();
+ assert!(err.contains("doesn't match the SHA-256"), "{err}");
+ assert!(!run.home.join(".local/bin/codex").exists());
+ let root = run.home.join(".codex/packages/standalone");
+ assert!(!root.join("releases").exists(), "unpacked an unchecked archive");
+ assert!(!root.join("current").exists());
+ assert_eq!(std::fs::read_dir(&root).unwrap().count(), 0, "the download was left behind");
+}
+
+#[tokio::test]
+async fn a_release_without_a_checksum_for_this_computer_is_refused() {
+ let tmp = tempdir().unwrap();
+ let mut rel = release(tmp.path(), "9.9.9");
+ rel.sums = rel.sums.lines().filter(|l| !l.ends_with(&format!("codex-package-{TARGET}.tar.gz"))).collect::<Vec<_>>().join("\n");
+ let hits = rel.hits.clone();
+ let url = serve(rel).await;
+ let run = run_in(tmp, &url);
+ let err = install(&run).await.unwrap_err();
+ assert!(err.contains("has no SHA-256 for"), "{err}");
+ assert!(!hits.lock().unwrap().iter().any(|h| h.ends_with(".tar.gz")), "downloaded without a checksum");
+ assert!(!run.home.join(".local/bin/codex").exists());
+}
+
+#[tokio::test]
+async fn a_newer_release_replaces_the_link_and_keeps_the_layout() {
+ let tmp = tempdir().unwrap();
+ let url = serve(release(tmp.path(), "9.9.9")).await;
+ let run = run_in(tmp, &url);
+ install(&run).await.unwrap();
+
+ let newer = serve(release(run._tmp.path(), "9.10.0")).await;
+ let at = run.at.clone().releases(&newer);
+ let log = |_: String| {};
+ let cmd = install_codex_release(&at, &log).await.unwrap();
+ assert_eq!(version_of(&cmd), "codex-cli 9.10.0");
+ let root = run.home.join(".codex/packages/standalone");
+ assert_eq!(std::fs::read_link(root.join("current")).unwrap(), root.join(format!("releases/9.10.0-{TARGET}")));
+ // Running it again is harmless
+ install_codex_release(&at, &log).await.unwrap();
+ assert_eq!(version_of(&cmd), "codex-cli 9.10.0");
+}
+
+#[tokio::test]
+async fn a_mac_build_also_links_the_code_mode_helper_and_codex_home_is_respected() {
+ let tmp = tempdir().unwrap();
+ let mut rel = release(tmp.path(), "9.9.9");
+ rel.sums = rel.sums.replace(&format!("codex-package-{TARGET}"), "codex-package-aarch64-apple-darwin");
+ let hits = rel.hits.clone();
+ let url = serve(rel).await;
+ let home = tmp.path().join("home");
+ let at = CodexInstall::new(&home, Some(tmp.path().join("codex-home")), "aarch64-apple-darwin").releases(&url);
+ let cmd = install_codex_release(&at, &|_| {}).await.unwrap();
+ assert!(hits.lock().unwrap().iter().any(|h| h.ends_with("codex-package-aarch64-apple-darwin.tar.gz")));
+ let current = tmp.path().join("codex-home/packages/standalone/current");
+ assert_eq!(std::fs::read_link(home.join(".local/bin/codex-code-mode-host")).unwrap(), current.join("bin/codex-code-mode-host"));
+ assert_eq!(std::fs::read_link(&cmd).unwrap(), current.join("bin/codex"));
+ assert!(!home.join(".codex").exists());
+}
+
+#[tokio::test]
+async fn a_latest_that_isnt_a_codex_tag_is_refused() {
+ let tmp = tempdir().unwrap();
+ let mut rel = release(tmp.path(), "9.9.9");
+ rel.tag = "nightly".into();
+ let url = serve(rel).await;
+ let run = run_in(tmp, &url);
+ let err = install(&run).await.unwrap_err();
+ assert!(err.contains("couldn't tell the latest Codex release"), "{err}");
+}
diff --git a/tests/dev_jira_test.rs b/tests/dev_jira_test.rs
index 55306a06..4d2b722e 100644
--- a/tests/dev_jira_test.rs
+++ b/tests/dev_jira_test.rs
@@ -164,7 +164,17 @@ async fn wait_state(env: &Env, key: &str, want: &[&str]) -> String {
async fn until_working(env: &Env, key: &str) {
let st = wait_state(env, key, &[dev_jira::WORKING, dev_jira::FAILED, dev_jira::NEEDS_ANSWER]).await;
assert_eq!(st, dev_jira::WORKING, "{key}: {:?}", events(env, key).await);
- assert_eq!(brief_state(env, key).await, dev_jira::WORKING, "the brief row mirrors the card");
+ // The brief row is written next to the card and can lag it a moment under load: wait for it
+ // (up to 30 s) instead of asserting at once
+ let mut brief = String::new();
+ for _ in 0..300 {
+ brief = brief_state(env, key).await;
+ if brief == dev_jira::WORKING {
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;
+ }
+ assert_eq!(brief, dev_jira::WORKING, "the brief row mirrors the card");
}
/// The brief row's state, from the brief route.
diff --git a/tests/engine_device_login_test.rs b/tests/engine_device_login_test.rs
new file mode 100644
index 00000000..42b7c3cc
--- /dev/null
+++ b/tests/engine_device_login_test.rs
@@ -0,0 +1,371 @@
+//! "Sign in with ChatGPT" and "Sign in with Grok" for the Codex and Grok engines (0.7.6, O3):
+//! `/api/engines/{codex,grok}/login…`, against fake CLIs that print a device link and code the
+//! way `codex login --device-auth` (0.162) and `grok login --device-auth` (1.0) do, and sign in
+//! once the test "approves" the code. No real account or network is used.
+#![cfg(unix)]
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ profiles::{login::LoginManager, Engine},
+ router::LayaRouter,
+ server::{
+ auth::{ApiToken, Require},
+ create_router,
+ engine_login::EngineLogin,
+ AppState,
+ },
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tempfile::{tempdir, TempDir};
+use tower::ServiceExt;
+
+const CODEX_CODE: &str = "WXYZ-12345";
+const GROK_CODE: &str = "QRST-6789";
+
+/// Waits for `approve` (signs in) or `expire` (says the code expired) in its home.
+const WAIT_LOOP: &str = r#"
+ i=0
+ while [ $i -lt 300 ]; do
+ if [ -f "$H/approve" ]; then echo '{}' > "$H/auth.json"; echo "Successfully logged in"; exit 0; fi
+ if [ -f "$H/expire" ]; then echo "Error: device code expired. Run login again."; exit 1; fi
+ sleep 0.1; i=$((i+1))
+ done
+ exit 1 ;;"#;
+
+fn fake_codex(home: &Path) -> String {
+ format!(
+ r#"#!/bin/sh
+H="${{CODEX_HOME:-{home}}}"
+case "$1 $2" in
+ "--version "*) echo "codex-cli 9.9.9" ;;
+ "login status")
+ if [ -f "$H/auth.json" ] && [ ! -f "$H/unusable" ]; then echo "Logged in using ChatGPT"
+ else echo "Not logged in"; exit 1; fi ;;
+ "debug models") echo '{{"models":[{{"slug":"gpt-test","display_name":"GPT Test","priority":1}}]}}' ;;
+ "login --device-auth")
+ echo $$ > "$H/login.pid"
+ printf '\nWelcome to Codex [v\033[90m9.9.9\033[0m]\n\nFollow these steps to sign in with ChatGPT using device code authorization:\n\n'
+ printf '1. Open this link in your browser and sign in to your account\n \033[94mhttps://auth.openai.com/codex/device\033[0m\n\n'
+ printf '2. Enter this one-time code \033[90m(expires in 15 minutes)\033[0m\n \033[94m{code}\033[0m\n\n'
+ printf '\033[90mContinue only if you started this login in Codex.\033[0m\n'{wait}
+ "logout ") rm -f "$H/auth.json"; echo "Successfully logged out" ;;
+esac
+"#,
+ home = home.display(),
+ code = CODEX_CODE,
+ wait = WAIT_LOOP,
+ )
+}
+
+fn fake_grok(home: &Path) -> String {
+ format!(
+ r#"#!/bin/sh
+H="${{GROK_HOME:-{home}}}"
+case "$1 $2" in
+ "--version "*) echo "grok 9.9.9 (test)" ;;
+ "models "*)
+ if [ -f "$H/auth.json" ]; then printf 'Default model: grok-test\nAvailable models:\n * grok-test (default)\n'
+ else echo "Not authenticated. Run grok login"; exit 1; fi ;;
+ "login --device-auth")
+ echo $$ > "$H/login.pid"
+ printf '\nTo sign in, open this URL in your browser:\n\n https://accounts.x.ai/oauth2/device?user_code={code}\n\n'
+ printf 'Confirm this code in your browser:\n\n {code}\n\n\033[90mOnly continue with a code you requested.\033[0m\n\nWaiting for authorization...\n'{wait}
+ "logout ") rm -f "$H/auth.json"; echo "Signed out" ;;
+esac
+"#,
+ home = home.display(),
+ code = GROK_CODE,
+ wait = WAIT_LOOP,
+ )
+}
+
+struct Env {
+ app: Router,
+ codex_home: PathBuf,
+ grok_home: PathBuf,
+ _tmp: TempDir,
+}
+
+async fn setup_with(timeout: Duration) -> Env {
+ logs();
+ let tmp = tempdir().unwrap();
+ let (codex_home, grok_home) = (tmp.path().join("codex-home"), tmp.path().join("grok-home"));
+ let (codex_bin, grok_bin) = (tmp.path().join("codex"), tmp.path().join("grok"));
+ exe::write_executable(&codex_bin, fake_codex(&codex_home));
+ exe::write_executable(&grok_bin, fake_grok(&grok_home));
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(ApiToken::for_tests("device-login-test-token-0123456789", Require::Auto, config.port));
+ let bin = |p: &Path| Some(p.to_string_lossy().into_owned());
+ state.codex_login = Arc::new(EngineLogin::for_engine(
+ Engine::Codex,
+ bin(&codex_bin),
+ Some(codex_home.clone()),
+ LoginManager::with_timeout(timeout),
+ ));
+ state.grok_login = Arc::new(EngineLogin::for_engine(
+ Engine::Grok,
+ bin(&grok_bin),
+ Some(grok_home.clone()),
+ LoginManager::with_timeout(timeout),
+ ));
+ Env { app: create_router(state), codex_home, grok_home, _tmp: tmp }
+}
+
+async fn setup() -> Env {
+ setup_with(Duration::from_secs(600)).await
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let b = Request::builder().method(method).uri(uri).header("content-type", "application/json");
+ let resp = app
+ .clone()
+ .oneshot(b.body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty)).unwrap())
+ .await
+ .unwrap();
+ let status = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+fn engine_status(engines: &Value, id: &str) -> String {
+ engines["engines"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|e| e["id"] == id)
+ .map(|e| e["status"].as_str().unwrap_or_default().to_string())
+ .unwrap()
+}
+
+fn login_pid(home: &Path) -> String {
+ std::fs::read_to_string(home.join("login.pid")).unwrap().trim().to_string()
+}
+
+fn alive(pid: &str) -> bool {
+ std::process::Command::new("kill").args(["-0", pid]).status().unwrap().success()
+}
+
+async fn wait_state(app: &Router, engine: &str, sid: &str, want: &str) -> Value {
+ let mut last = Value::Null;
+ for _ in 0..100 {
+ let (s, v) = call(app, "GET", &format!("/api/engines/{engine}/login/{sid}"), None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ if v["state"] == want {
+ return v;
+ }
+ last = v;
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("{engine} never reached {want}: {last}");
+}
+
+fn minutes_left(v: &Value) -> f64 {
+ let at = chrono::DateTime::parse_from_rfc3339(v["expires_at"].as_str().unwrap()).unwrap();
+ (at.with_timezone(&chrono::Utc) - chrono::Utc::now()).num_seconds() as f64 / 60.0
+}
+
+fn logs() -> Arc<Mutex<Vec<u8>>> {
+ static LOGS: std::sync::OnceLock<Arc<Mutex<Vec<u8>>>> = std::sync::OnceLock::new();
+ LOGS.get_or_init(install_log_capture).clone()
+}
+
+fn install_log_capture() -> Arc<Mutex<Vec<u8>>> {
+ #[derive(Clone)]
+ struct W(Arc<Mutex<Vec<u8>>>);
+ impl std::io::Write for W {
+ fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(b);
+ Ok(b.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ let buf = Arc::new(Mutex::new(Vec::new()));
+ let w = W(buf.clone());
+ let sub = tracing_subscriber::fmt()
+ .with_max_level(tracing::Level::TRACE)
+ .with_ansi(false)
+ .with_writer(move || w.clone())
+ .finish();
+ tracing::subscriber::set_global_default(sub).unwrap();
+ buf
+}
+
+#[tokio::test]
+async fn chatgpt_sign_in_shows_the_device_code_and_finishes_by_itself() {
+ let env = setup().await;
+ let app = &env.app;
+
+ let (s, v) = call(app, "POST", "/api/engines/codex/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ // The first answer already has both the link and the code
+ assert_eq!(v["state"], "waiting_for_approval", "{v}");
+ assert_eq!((v["engine"].as_str(), v["kind"].as_str()), (Some("codex"), Some("device_code")), "{v}");
+ assert_eq!(v["url"], "https://auth.openai.com/codex/device", "{v}");
+ assert_eq!(v["user_code"], CODEX_CODE, "{v}");
+ // The expiry is the code's own: Codex says 15 minutes
+ let left = minutes_left(&v);
+ assert!((14.5..=15.1).contains(&left), "{left} minutes left: {v}");
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ assert!(env.codex_home.is_dir(), "CODEX_HOME was not created for the CLI");
+
+ // A pasted code means nothing here
+ let (s, _) = call(app, "POST", &format!("/api/engines/codex/login/{sid}/code"), Some(json!({ "code": "abcdefgh123" }))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST);
+
+ // The person approves on chatgpt.com: kwnt notices with no button press
+ std::fs::write(env.codex_home.join("approve"), "").unwrap();
+ let done = wait_state(app, "codex", &sid, "done").await;
+ assert_eq!((&done["url"], &done["user_code"], &done["detail"]), (&Value::Null, &Value::Null, &Value::Null), "{done}");
+ let (_, engines) = call(app, "GET", "/api/engines", None).await;
+ assert_eq!(engine_status(&engines, "codex"), "ready", "{engines}");
+
+ let logs = String::from_utf8(logs().lock().unwrap().clone()).unwrap();
+ assert!(logs.contains("codex engine sign-in started"), "{logs}");
+ assert!(logs.contains("codex engine sign-in finished"), "{logs}");
+ for secret in [CODEX_CODE, GROK_CODE, "user_code"] {
+ assert!(!logs.contains(secret), "{secret} was logged:\n{logs}");
+ }
+
+ // Sign out goes through the CLI's own `logout`
+ let (s, engines) = call(app, "POST", "/api/engines/codex/logout", None).await;
+ assert_eq!(s, StatusCode::OK, "{engines}");
+ assert_eq!(engine_status(&engines, "codex"), "signed_out", "{engines}");
+}
+
+#[tokio::test]
+async fn grok_sign_in_shows_its_own_link_and_code_and_finishes_by_itself() {
+ let env = setup().await;
+ let app = &env.app;
+ let (s, v) = call(app, "POST", "/api/engines/grok/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_eq!(v["state"], "waiting_for_approval", "{v}");
+ assert_eq!(v["kind"], "device_code");
+ // The link as the CLI prints it, code in the query included
+ assert_eq!(v["url"], format!("https://accounts.x.ai/oauth2/device?user_code={GROK_CODE}"), "{v}");
+ assert_eq!(v["user_code"], GROK_CODE, "{v}");
+ // Grok prints no lifetime: the sign-in's own timeout
+ let left = minutes_left(&v);
+ assert!((9.5..=10.1).contains(&left), "{left} minutes left: {v}");
+ let sid = v["session_id"].as_str().unwrap().to_string();
+
+ std::fs::write(env.grok_home.join("approve"), "").unwrap();
+ wait_state(app, "grok", &sid, "done").await;
+ let (_, engines) = call(app, "GET", "/api/engines", None).await;
+ assert_eq!(engine_status(&engines, "grok"), "ready", "{engines}");
+}
+
+#[tokio::test]
+async fn only_one_device_sign_in_runs_per_engine_and_cancel_kills_it() {
+ let env = setup().await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/codex/login", None).await;
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ let pid = login_pid(&env.codex_home);
+ assert!(alive(&pid));
+
+ let (s, busy) = call(app, "POST", "/api/engines/codex/login", None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{busy}");
+ assert_eq!(busy["session_id"], sid.as_str());
+ // Grok's sign-in is separate and may run meanwhile
+ let (s, g) = call(app, "POST", "/api/engines/grok/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{g}");
+ // Another engine's session id isn't found under this engine
+ let (s, _) = call(app, "GET", &format!("/api/engines/grok/login/{sid}"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND);
+
+ let (s, _) = call(app, "DELETE", &format!("/api/engines/codex/login/{sid}"), None).await;
+ assert_eq!(s, StatusCode::NO_CONTENT);
+ let v = wait_state(app, "codex", &sid, "cancelled").await;
+ assert_eq!((&v["url"], &v["user_code"]), (&Value::Null, &Value::Null), "{v}");
+ assert!(!alive(&pid), "the CLI is still running after cancel");
+ assert!(!env.codex_home.join("auth.json").exists());
+
+ let (s, v) = call(app, "POST", "/api/engines/codex/login", None).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ assert_ne!(v["session_id"].as_str().unwrap(), sid);
+ let gsid = g["session_id"].as_str().unwrap();
+ call(app, "DELETE", &format!("/api/engines/grok/login/{gsid}"), None).await;
+ call(app, "DELETE", &format!("/api/engines/codex/login/{}", v["session_id"].as_str().unwrap()), None).await;
+}
+
+#[tokio::test]
+async fn a_code_the_cli_says_expired_is_expired_not_failed() {
+ let env = setup().await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/codex/login", None).await;
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ std::fs::write(env.codex_home.join("expire"), "").unwrap();
+ let v = wait_state(app, "codex", &sid, "expired").await;
+ assert!(v["detail"].as_str().unwrap().contains("code expired"), "{v}");
+ assert_eq!((&v["url"], &v["user_code"]), (&Value::Null, &Value::Null), "{v}");
+}
+
+#[tokio::test]
+async fn an_unanswered_device_sign_in_expires_and_its_cli_is_killed() {
+ let env = setup_with(Duration::from_millis(800)).await;
+ let app = &env.app;
+ let (_, v) = call(app, "POST", "/api/engines/grok/login", None).await;
+ assert_eq!(v["state"], "waiting_for_approval", "{v}");
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ let pid = login_pid(&env.grok_home);
+ let v = wait_state(app, "grok", &sid, "expired").await;
+ assert!(v["detail"].as_str().unwrap().contains("Get a new code"), "{v}");
+ assert!(!alive(&pid), "the CLI outlived its sign-in");
+}
+
+#[tokio::test]
+async fn a_sign_in_the_engine_still_cant_use_fails_with_the_reason() {
+ let env = setup().await;
+ let app = &env.app;
+ std::fs::create_dir_all(&env.codex_home).unwrap();
+ std::fs::write(env.codex_home.join("unusable"), "").unwrap();
+ let (_, v) = call(app, "POST", "/api/engines/codex/login", None).await;
+ let sid = v["session_id"].as_str().unwrap().to_string();
+ std::fs::write(env.codex_home.join("approve"), "").unwrap();
+ let v = wait_state(app, "codex", &sid, "failed").await;
+ assert_eq!(
+ v["detail"],
+ "Signed in, but Codex can't use this account: it still shows as signed out",
+ "{v}"
+ );
+}
+
+#[tokio::test]
+async fn engines_without_an_in_app_sign_in_are_404() {
+ let env = setup().await;
+ let app = &env.app;
+ for engine in ["custom", "ollama", "openai_api", "nope"] {
+ let (s, v) = call(app, "POST", &format!("/api/engines/{engine}/login"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{engine}: {v}");
+ let (s, _) = call(app, "POST", &format!("/api/engines/{engine}/logout"), None).await;
+ assert_eq!(s, StatusCode::NOT_FOUND, "{engine}");
+ }
+ for (m, uri) in [("GET", "/api/engines/codex/login/login_nope"), ("DELETE", "/api/engines/grok/login/login_nope")] {
+ assert_eq!(call(app, m, uri, None).await.0, StatusCode::NOT_FOUND, "{m} {uri}");
+ }
+ assert!(!env.codex_home.join("login.pid").exists());
+}
diff --git a/tests/goals_remediation_test.rs b/tests/goals_remediation_test.rs
index bb86596d..e2b58a6e 100644
--- a/tests/goals_remediation_test.rs
+++ b/tests/goals_remediation_test.rs
@@ -970,9 +970,15 @@ async fn lapse(e: &Env, g: &Goal) -> Goal {
let file = std::path::Path::new(&g.folder).join("ok.txt");
// Goals made in one space share the folder, so it may already be gone
let _ = std::fs::remove_file(&file);
+ // A lapse counts only strictly after the task finished, in whole milliseconds (the finish time
+ // rounds to the nearest one). On a fast machine the task's finish and these runs can share a
+ // millisecond, and then no lapse is found: start the runs a few milliseconds later
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
let first = run_now(e, &g.id).await;
assert_eq!((first.status.as_str(), first.fail_streak), ("met", 1), "one failure is not news");
- run_now(e, &g.id).await
+ let second = run_now(e, &g.id).await;
+ assert_eq!(second.status, "not_met", "the second failure confirms it");
+ second
}
fn restore(g: &Goal) {
@@ -984,7 +990,8 @@ async fn lapse_1_a_verified_task_whose_goal_goes_met_to_not_met_is_one_lapse() {
let e = setup().await;
let (task_id, g) = kept_task(&e, &e.bot, "Publish the site").await;
assert!(e.state.db.goal_lapses_of_bot(&e.bot, 0, 10).await.unwrap().is_empty(), "nothing before it fails");
- // One failed run is not a lapse
+ // One failed run is not a lapse (a few milliseconds on, as in `lapse`)
+ tokio::time::sleep(std::time::Duration::from_millis(5)).await;
std::fs::remove_file(std::path::Path::new(&g.folder).join("ok.txt")).unwrap();
assert_eq!(run_now(&e, &g.id).await.status, "met");
assert!(e.state.db.goal_lapses_of_bot(&e.bot, 0, 10).await.unwrap().is_empty(), "an unconfirmed failure is not a lapse");
@@ -1017,7 +1024,9 @@ async fn lapse_3_a_lapse_older_than_since_is_left_out() {
let e = setup().await;
let (_, g) = kept_task(&e, &e.bot, "Publish the site").await;
lapse(&e, &g).await;
- let at = e.state.db.goal_lapses_of_bot(&e.bot, 0, 10).await.unwrap()[0].lapsed_at;
+ let lapses = e.state.db.goal_lapses_of_bot(&e.bot, 0, 10).await.unwrap();
+ assert_eq!(lapses.len(), 1, "the lapse is found");
+ let at = lapses[0].lapsed_at;
assert_eq!(e.state.db.goal_lapses_of_bot(&e.bot, at, 10).await.unwrap().len(), 1, "since is inclusive");
assert!(e.state.db.goal_lapses_of_bot(&e.bot, at + 1, 10).await.unwrap().is_empty());
assert!(e.state.db.goal_lapses_of_bot(&e.bot, now() + 60_000, 10).await.unwrap().is_empty());
diff --git a/tests/rigel_076_test.rs b/tests/rigel_076_test.rs
index 3a87d7f9..4b1acfff 100644
--- a/tests/rigel_076_test.rs
+++ b/tests/rigel_076_test.rs
@@ -319,6 +319,16 @@ async fn rigel_x3_grok_and_custom_leads_never_read_a_ticket() {
assert!(invocations_with(&tag).is_empty(), "{model}: the ticket text reached a CLI");
let msg = row["ticket"]["error"]["message"].as_str().unwrap_or_default();
assert!(!msg.is_empty() && !msg.to_lowercase().starts_with("kwant"), "{model}: error {msg:?}");
+ // D6: the card says why: the engine was refused, in kwant's own words, not "stopped"
+ let code = row["ticket"]["error"]["code"].as_str().unwrap_or_default();
+ if model != "codex" {
+ assert_eq!(code, "engine_refused", "{model}: {row}");
+ assert_eq!(msg, "A Jira brief is prepared only on Claude or Codex, with tool checks on. Put the team's lead on one of them, then press Start.");
+ let (_, b) = call(&env.app, "GET", &uri(&format!("tickets/{key}/brief")), None).await;
+ assert_eq!(b["note"].as_str(), Some(msg), "{model}: the brief's note says the same: {b}");
+ } else {
+ eprintln!("codex without a codex CLI: {code}");
+ }
assert!(m.writes().is_empty());
}
}
diff --git a/tests/show_once_recorder_test.rs b/tests/show_once_recorder_test.rs
index 9834ee69..0065d393 100644
--- a/tests/show_once_recorder_test.rs
+++ b/tests/show_once_recorder_test.rs
@@ -1,6 +1,7 @@
//! Show it once: the recorder script in a real Chrome/Chromium, typed into with real key events
//! (`Input.dispatchKeyEvent`, the in-app viewer's path), its payloads read by the server's own
-//! parser. Covers S-F2: a field a script filled and the person then edited is masked. Skipped
+//! parser. Covers S-F2 (a field a script filled and the person then edited is masked) and S-F5
+//! (a field left by kwnt's own navigation, with no blur, is committed first, masked). Skipped
//! when no Chrome is installed.
#[path = "support/chrome_guard.rs"]
mod chrome_guard;
@@ -260,3 +261,102 @@ async fn a_pick_in_the_drawn_list_is_a_select_step_and_a_wrapping_label_names_th
let c = capture::parse(&payloads[0]).unwrap();
assert_eq!(c.step.label.as_deref(), Some("Note"));
}
+
+/// A sign-in form: a password field and a one-time code field.
+const SIGN_IN_PAGE: &str = "<!doctype html><title>sign in</title><body>\
+<input id=user name=user>\
+<input id=pw name=pw type=password>\
+<input id=otp name=otp autocomplete=one-time-code>";
+
+#[tokio::test]
+async fn leaving_by_the_address_bar_with_no_blur_records_the_secret_fields_masked() {
+ std::env::remove_var("DISPLAY");
+ std::env::remove_var("WAYLAND_DISPLAY");
+ if computer::local_chrome_path().is_none() {
+ eprintln!("skipped: no Chrome or Chromium installed");
+ return;
+ }
+ let tmp = tempfile::tempdir().unwrap();
+ let _chrome = ChromeGuard(tmp.path().join("local-chrome"));
+ let service = BrowserService::new(tmp.path().to_path_buf(), None);
+ service.set_mode(ComputerMode::Local).await;
+ let ctrl = service.session("bot", tmp.path()).await.expect("local session");
+ let url = serve(SIGN_IN_PAGE).await;
+ ctrl.navigate(&url).await.unwrap();
+
+ let tree = ctrl.send_cdp_command("Page.getFrameTree", json!({})).await.unwrap();
+ let frame = tree["frameTree"]["frame"]["id"].as_str().unwrap().to_string();
+ let world = ctrl.send_cdp_command("Page.createIsolatedWorld", json!({"frameId": frame, "worldName": capture::WORLD})).await.unwrap();
+ let ctx = world["executionContextId"].clone();
+ let in_world = |expr: String| {
+ let ctrl = &ctrl;
+ let ctx = ctx.clone();
+ async move {
+ let r = ctrl.send_cdp_command("Runtime.evaluate", json!({"expression": expr, "contextId": ctx, "returnByValue": true})).await.unwrap();
+ assert!(r.get("exceptionDetails").is_none(), "{r}");
+ r["result"]["value"].clone()
+ }
+ };
+ let sent = || in_world("JSON.stringify(__sent.splice(0))".to_string());
+ let take = |v: Value| -> Vec<String> { serde_json::from_str(v.as_str().unwrap()).unwrap() };
+ let ctrl_ref = &ctrl;
+ let commit = || {
+ let call = move |method: &'static str, params: Value| async move { ctrl_ref.send_cdp_command(method, params).await.ok() };
+ capture::commit_pending(call)
+ };
+ in_world(format!("globalThis.__sent = []; globalThis.{} = function (s) {{ __sent.push(s); }}; true", capture::BINDING)).await;
+
+ // no recording on: no recorder in its world, nothing taken
+ assert!(!commit().await, "no recorder, nothing committed");
+ in_world(capture::recorder_js()).await;
+ // the page's own scripts can't reach the commit
+ assert_eq!(page_js(&ctrl, "typeof globalThis.__kwntRecorderCommit").await, "undefined");
+
+ // the person types the user name, the password, then the code, and never leaves the code
+ // field: its edit is still pending
+ focus(&ctrl, "user").await;
+ person_types(&ctrl, "sam").await;
+ focus(&ctrl, "pw").await;
+ person_types(&ctrl, "hunter").await;
+ focus(&ctrl, "otp").await;
+ person_types(&ctrl, "4821").await;
+ let before = take(sent().await);
+ let labels = |ps: &[String]| -> Vec<String> { ps.iter().filter_map(|p| capture::parse(p)).map(|c| c.step.label.unwrap_or_default()).collect() };
+ assert!(!labels(&before).contains(&"otp".to_string()), "the code isn't a step yet: {before:?}");
+ // an address-bar navigation moves no focus, so kwnt's server commits before it navigates
+ assert!(commit().await, "the recorder took the commit");
+ let committed = take(sent().await);
+ assert!(labels(&committed).contains(&"otp".to_string()), "the pending code field: {committed:?}");
+
+ let all = [before, committed].concat();
+ let raw = all.join("\n");
+ for secret in ["hunter", "4821"] {
+ assert!(!raw.contains(secret), "{secret:?} left the page: {raw}");
+ }
+ let mut steps: BTreeMap<String, (Option<String>, Option<String>, String)> = BTreeMap::new();
+ for p in &all {
+ let c = capture::parse(p).unwrap_or_else(|| panic!("the server reads every payload: {p}"));
+ assert_eq!(c.step.kind, "type");
+ assert_eq!(c.page.path, "/form", "recorded on the page being left");
+ assert!(steps.insert(c.step.label.clone().unwrap_or_default(), (c.step.value, c.step.masked, c.page.path)).is_none(), "one step per field: {all:?}");
+ }
+ assert_eq!(steps.len(), 3, "{steps:?}");
+ assert_eq!(steps["user"].0.as_deref(), Some("sam"));
+ assert_eq!((steps["pw"].0.as_deref(), steps["pw"].1.as_deref()), (None, Some("password")), "recorded, masked");
+ assert_eq!((steps["otp"].0.as_deref(), steps["otp"].1.as_deref()), (None, Some("code")), "recorded, masked");
+
+ // nothing is left pending, and a second commit adds nothing
+ assert!(commit().await);
+ assert!(take(sent().await).is_empty(), "no duplicate step");
+ assert!(take(in_world(format!("JSON.stringify({})", capture::FLUSH)).await).is_empty());
+
+ // the same with a password left focused
+ focus(&ctrl, "pw").await;
+ person_types(&ctrl, "x").await;
+ assert!(commit().await);
+ let committed = take(sent().await);
+ assert_eq!(committed.len(), 1, "{committed:?}");
+ let c = capture::parse(&committed[0]).unwrap();
+ assert_eq!((c.step.value.as_deref(), c.step.masked.as_deref()), (None, Some("password")));
+ assert!(!committed[0].contains("hunterx"));
+}
diff --git a/tests/show_once_test.rs b/tests/show_once_test.rs
index 97a31a26..df52272b 100644
--- a/tests/show_once_test.rs
+++ b/tests/show_once_test.rs
@@ -309,6 +309,86 @@ async fn a_reply_that_isnt_a_draft_fails_the_write_and_keeps_the_steps() {
assert!(pending.as_array().unwrap().is_empty(), "{pending}");
}
+/// S-F3: a draft whose input takes its example from a step where nothing was typed (step 1 is a
+/// click). The engine is told the check's own words on the retry; the person's banner gets Mira's
+/// sentence, never the raw check. Any other failed check gets the fallback sentence.
+#[tokio::test]
+async fn a_draft_that_fails_a_check_shows_the_person_a_sentence_not_the_check() {
+ use kwnt::server::show_once::draft::{write_with, SHOWN_DRAFT_MISMATCH, SHOWN_NOTHING_TYPED};
+ let env = env().await;
+ let mut from_click: Value = serde_json::from_str(&canned_draft()).unwrap();
+ from_click["inputs"][0]["from_step"] = json!(1);
+ let mut no_checks: Value = serde_json::from_str(&canned_draft()).unwrap();
+ no_checks["checks"] = json!([]);
+ for (reply, shown, raw) in [
+ (from_click, SHOWN_NOTHING_TYPED, "input 1's from_step 1 has no value"),
+ (no_checks, SHOWN_DRAFT_MISMATCH, "\"checks\""),
+ ] {
+ let rec = stopped_recording(&env, "watch me").await;
+ let rec = env.state.db.begin_writing(&rec).await.unwrap();
+ let id = rec.id.clone();
+ let prompts = std::sync::Mutex::new(Vec::<String>::new());
+ let reply = reply.to_string();
+ write_with(&env.state, rec, "Rook", |p| {
+ prompts.lock().unwrap().push(p);
+ let r = reply.clone();
+ async move { Ok(r) }
+ })
+ .await;
+ let prompts = prompts.into_inner().unwrap();
+ assert_eq!(prompts.len(), 2, "asked once more after the failed check");
+ assert!(prompts[1].contains(raw), "the engine hears the check's own words: {}", prompts[1]);
+ let (_, v) = call(&env.app, "GET", &format!("/api/show-once/recordings/{id}"), None).await;
+ assert_eq!(v["recording"]["state"], "stopped", "{v}");
+ assert_eq!(v["recording"]["write_error"], shown, "{v}");
+ let banner = v["recording"]["write_error"].as_str().unwrap();
+ assert!(!banner.contains("from_step") && !banner.contains("input 1"), "{banner}");
+ assert_eq!(v["steps"].as_array().unwrap().len(), 3, "the steps are kept");
+ let (s, _) = call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+ assert!(s.is_success(), "the next case starts its own recording");
+ }
+}
+
+/// S-F9: a drafting turn that fails leaves the recording stopped with its steps, and
+/// `write_error` is one of Mira's four sentences: never the banner's lead again, never the
+/// engine's own words.
+#[tokio::test]
+async fn a_failed_drafting_turn_shows_a_sentence_never_the_engines_error() {
+ use kwnt::server::show_once::draft::{write_with, TIMED_OUT, WRITE_SPEND_STOP, WRITE_STOPPED, WRITE_TIMED_OUT};
+ let env = env().await;
+ let engine = kwnt::server::show_once::engine_for(&env.state, &env.a).await;
+ let other = kwnt::server::show_once::draft::failed_turn_reason("x", "Rook", engine.as_deref());
+ assert!(other.ends_with(" stopped with an error before the draft was done. Check that it's signed in under Settings › This space › Accounts."), "{other}");
+ let raw = "Error: 401 Unauthorized: OAuth token sk-ant-xyz has expired";
+ for (err, shown) in [
+ (TIMED_OUT.to_string(), WRITE_TIMED_OUT.to_string()),
+ ("stopped by the user".to_string(), WRITE_STOPPED.to_string()),
+ ("spend_stopped: 120k of 100k tokens today".to_string(), WRITE_SPEND_STOP.to_string()),
+ (raw.to_string(), other.clone()),
+ ] {
+ let rec = stopped_recording(&env, "watch me").await;
+ let rec = env.state.db.begin_writing(&rec).await.unwrap();
+ let id = rec.id.clone();
+ let asked = std::sync::atomic::AtomicUsize::new(0);
+ write_with(&env.state, rec, "Rook", |_| {
+ asked.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
+ let e = err.clone();
+ async move { Err(e) }
+ })
+ .await;
+ assert_eq!(asked.into_inner(), 1, "a failed turn isn't asked again");
+ let (_, v) = call(&env.app, "GET", &format!("/api/show-once/recordings/{id}"), None).await;
+ assert_eq!(v["recording"]["state"], "stopped", "{v}");
+ assert_eq!(v["recording"]["write_error"], shown.as_str(), "{v}");
+ let banner = v["recording"]["write_error"].as_str().unwrap();
+ assert!(!banner.contains("couldn't write the skill"), "the lead isn't repeated: {banner}");
+ assert!(!banner.contains("401") && !banner.contains("sk-ant") && !banner.contains("120k"), "{banner}");
+ assert_eq!(v["steps"].as_array().unwrap().len(), 3, "the steps are kept");
+ let (s, _) = call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+ assert!(s.is_success(), "the next case starts its own recording");
+ }
+}
+
#[tokio::test]
async fn approve_keeps_the_steps_seven_days_then_the_sweep_purges_them() {
let env = env().await;
@@ -775,6 +855,72 @@ async fn a_start_url_is_the_first_page_and_the_page_before_isnt_a_step() {
assert!(stage.on_start_failed(Some("http://127.0.0.1:9483/shop/orders.html")).await.iter().any(is_step));
let steps = steps_of(&env, &id).await;
assert_eq!(steps.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>(), ["note", "page"], "{steps:?}");
+ stage.handed_back().await;
+ call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+}
+
+/// Starts a recording with a `start_url` on `stage` and installs the recorder while the browser
+/// is still on `before`. The recording's id.
+async fn start_at(env: &Env, stage: &mut kwnt::server::show_once::stage::StageRecorder, start: &str, before: &str) -> String {
+ stage.claim().await;
+ let body = json!({"bot": env.b, "first_note": "watch me", "start_url": start});
+ let (s, v) = call(&env.app, "POST", "/api/show-once/recordings", Some(body)).await;
+ assert_eq!(s, StatusCode::CREATED, "{v}");
+ let id = v["recording"]["id"].as_str().unwrap().to_string();
+ let cmd = next_cmd_for(stage, &id).await;
+ stage.on_cmd(cmd).await;
+ assert!(stage.on_installed(before).await.is_empty(), "the page before Start isn't a step yet");
+ id
+}
+
+#[tokio::test]
+async fn a_start_url_that_cant_load_keeps_the_page_the_browser_was_on() {
+ use kwnt::server::show_once::stage::StageRecorder;
+ let env = env().await;
+ let before = "http://127.0.0.1:9483/shop/orders.html";
+ let error_page = "chrome-error://chromewebdata/";
+ let mut stage = StageRecorder::new(env.state.clone(), env.b.clone(), 32);
+ let kinds = |steps: &[(String, Option<String>)]| steps.iter().map(|(k, _)| k.clone()).collect::<Vec<_>>();
+
+ // S-F1: Page.navigate reports the failure and Chromium now shows its own error page there,
+ // which is never recorded: the page the browser was on when Start was pressed is step 1
+ let id = start_at(&env, &mut stage, "http://127.0.0.1:1/refused", before).await;
+ assert!(stage.on_start_failed(Some(error_page)).await.iter().any(is_step));
+ // the error page's own load event that follows adds nothing
+ assert!(stage.on_navigated(error_page).await.is_empty());
+ let steps = steps_of(&env, &id).await;
+ assert_eq!(kinds(&steps), ["note", "page"], "{steps:?}");
+ assert_eq!(steps[1].1.as_deref(), Some("/shop/orders.html"));
+ // the person goes on from there: the next page is recorded as usual
+ assert!(stage.on_navigated("http://127.0.0.1:9483/shop/new.html").await.iter().any(is_step));
+ assert_eq!(kinds(&steps_of(&env, &id).await), ["note", "page", "page"]);
+ stage.handed_back().await;
+ call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+
+ // the history can't be read either: still the page before
+ let id = start_at(&env, &mut stage, "http://no-such-host.invalid/", before).await;
+ assert!(stage.on_start_failed(None).await.iter().any(is_step));
+ let steps = steps_of(&env, &id).await;
+ assert_eq!((kinds(&steps), steps[1].1.clone()), (vec!["note".to_string(), "page".to_string()], Some("/shop/orders.html".to_string())));
+ stage.handed_back().await;
+ call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+
+ // Page.navigate didn't report it, but the error page is what loaded: the same
+ let id = start_at(&env, &mut stage, "http://no-such-host.invalid/", before).await;
+ assert!(stage.on_navigated(error_page).await.iter().any(is_step));
+ let steps = steps_of(&env, &id).await;
+ assert_eq!((kinds(&steps), steps[1].1.clone()), (vec!["note".to_string(), "page".to_string()], Some("/shop/orders.html".to_string())));
+ stage.handed_back().await;
+ call(&env.app, "DELETE", &format!("/api/show-once/recordings/{id}"), None).await;
+
+ // a start page that loads is still the first page step, and the page before never is
+ let id = start_at(&env, &mut stage, "http://127.0.0.1:9483/", before).await;
+ assert!(stage.on_navigated("http://127.0.0.1:9483/").await.iter().any(is_step));
+ // an error page later on (the person's own link to a dead host) is never a step
+ assert!(stage.on_navigated(error_page).await.is_empty());
+ let steps = steps_of(&env, &id).await;
+ assert_eq!(kinds(&steps), ["note", "page"], "{steps:?}");
+ assert_eq!(steps[1].1.as_deref(), Some("/"));
}
#[tokio::test]
diff --git a/tests/team_templates_test.rs b/tests/team_templates_test.rs
index abef2485..6c632e0a 100644
--- a/tests/team_templates_test.rs
+++ b/tests/team_templates_test.rs
@@ -225,6 +225,7 @@ async fn undo_keeps_a_chat_with_history_archived() {
let (_, t) = call(&e.app, "GET", &format!("/api/teams/{team_id}/template"), &[], None).await;
assert_eq!(needs_done(&t), json!(["what_you_sell"]), "{t}");
assert_eq!(t["chat_messages"], 2);
+ assert_eq!(t["archived_chat"], "archived-team-sales", "{t}");
let (s, u) = undo(&e, v["action_id"].as_str().unwrap()).await;
assert!(s.is_success(), "{s} {u}");
let chats = e.state.db.list_channels(&e.space).await.unwrap();
@@ -235,6 +236,46 @@ async fn undo_keeps_a_chat_with_history_archived() {
assert!(e.state.db.list_teams(&e.space).await.unwrap().iter().all(|t| t.name != "sales"));
}
+/// archived-name (N-6): the preview names the chat the Undo will leave, `-2` included when
+/// `#archived-team-<handle>` is already taken, and the Undo then uses that very name.
+#[tokio::test]
+async fn the_undo_preview_names_the_archived_chat_the_undo_leaves() {
+ let e = setup().await;
+ let mut names = Vec::new();
+ for round in 0..2 {
+ let (s, v) = create(&e, json!({"template_id": "sales"})).await;
+ assert_eq!(s, StatusCode::CREATED, "round {round}: {v}");
+ let chat_id = v["channel_id"].as_str().unwrap().to_string();
+ let team_id = v["team"]["id"].as_str().unwrap().to_string();
+ let uri = format!("/api/teams/{team_id}/template");
+ // An empty chat is deleted by Undo, so there is no archived name to show
+ let (_, t) = call(&e.app, "GET", &uri, &[], None).await;
+ assert_eq!((t["chat_messages"].as_i64(), &t["archived_chat"]), (Some(0), &Value::Null), "{t}");
+ e.state
+ .db
+ .insert_message(&NewMessage {
+ channel_id: Some(chat_id.clone()),
+ direct_kwant_id: None,
+ sender_role: "user".into(),
+ sender_id: "user".into(),
+ text: "Our first leads, please.".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ })
+ .await
+ .unwrap();
+ let (_, t) = call(&e.app, "GET", &uri, &[], None).await;
+ let shown = t["archived_chat"].as_str().expect("a chat with messages is kept").to_string();
+ let (s, u) = undo(&e, v["action_id"].as_str().unwrap()).await;
+ assert!(s.is_success(), "{s} {u}");
+ let kept = e.state.db.list_channels(&e.space).await.unwrap().into_iter().find(|c| c.id == chat_id).expect("kept");
+ assert_eq!(kept.name, shown, "round {round}: the preview showed the name the Undo used");
+ names.push(shown);
+ }
+ assert_eq!(names, ["archived-team-sales", "archived-team-sales-2"]);
+}
+
#[tokio::test]
async fn a_second_create_gets_free_names_and_a_clash_says_what_to_use() {
let e = setup().await;
diff --git a/tests/telegram_test.rs b/tests/telegram_test.rs
index 68c3be54..c95c1a7a 100644
--- a/tests/telegram_test.rs
+++ b/tests/telegram_test.rs
@@ -937,3 +937,36 @@ async fn the_spending_stop_tells_the_paired_chat_once() {
assert!(tg.sent(&bot).iter().all(|c| !c.text().contains("answer tg40")), "no turn, no answer");
assert!(common::messages(&env, &general).await.iter().all(|m| m.sender_role != "kwant"));
}
+
+/// D-1: a routine, mission or Jira task that trips the spending stop while the person writes from
+/// Telegram (the reply window is open) is not told to them as their own held message: the stuck
+/// message keeps the plain line, and nothing says "your message wasn't run".
+#[tokio::test]
+async fn a_routine_tripping_the_stop_inside_the_reply_window_keeps_the_plain_line() {
+ let env = setup().await;
+ let tg = mock_telegram::shared();
+ let bot = paired(&env, tg, 54).await;
+ let space = kwnt::db::spaces::SpaceId::default_space();
+ env.state.db.telegram_person_wrote(space.as_str(), chrono::Utc::now()).await.unwrap();
+ let link = env.state.db.telegram_link(space.as_str()).await.unwrap().unwrap();
+ assert!(link.reply_window_from.is_some(), "the person writes from Telegram");
+ let mut rx = env.state.event_sender.subscribe();
+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"daily_spend_stop_tokens": 10_000}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ kwnt::server::spend_stop::book(&env.state, 18_000, None).await;
+
+ // What routines, missions (Jira tasks among them) and AutoFix ask before they start work
+ let why = kwnt::server::spend_stop::held(&env.state, space.as_str()).await;
+ assert!(why.as_deref().is_some_and(|w| w.starts_with(kwnt::server::spend_stop::REASON)), "{why:?}");
+ let sent = tg.wait_send(&bot, |c| c.text().contains("Today's spending limit is reached")).await;
+ assert_eq!(sent.chat(), PERSON.id);
+ assert_eq!(
+ sent.text(),
+ "<b>Today's spending limit is reached</b>\nUsed 18k of 10k tokens, so bots won't start new work until tomorrow. Open to continue today.",
+ "a routine's stop is not the person's held message"
+ );
+ let n = spend_notifies(&mut rx);
+ assert_eq!(n.len(), 1, "{n:?}");
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(!tg.sent(&bot).iter().any(|c| c.text().contains("your message wasn't run")), "never the held-message line");
+}
diff --git a/tests/version_test.rs b/tests/version_test.rs
new file mode 100644
index 00000000..48c18e0b
--- /dev/null
+++ b/tests/version_test.rs
@@ -0,0 +1,38 @@
+//! kwnt reports the release's version (0.7.6, O8): `kwnt --version` and `/api/health` read the root
+//! crate's version, which a release bumps together with the Mac app's (the tag check in mac.yml
+//! fails otherwise). Before 0.7.6 the root crate stayed at 0.1.0 and both said "0.1.0".
+
+use std::path::Path;
+
+fn manifest_version(path: &Path) -> String {
+ let text = std::fs::read_to_string(path).unwrap();
+ let doc: toml::Value = toml::from_str(&text).unwrap();
+ doc["package"]["version"].as_str().unwrap().to_string()
+}
+
+#[test]
+fn kwnt_has_the_mac_apps_release_version() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR"));
+ let mac = manifest_version(&root.join("apps/mac/Cargo.toml"));
+ let tauri: serde_json::Value =
+ serde_json::from_str(&std::fs::read_to_string(root.join("apps/mac/tauri.conf.json")).unwrap()).unwrap();
+ assert_eq!(env!("CARGO_PKG_VERSION"), mac, "bump the root Cargo.toml with apps/mac/Cargo.toml");
+ assert_eq!(tauri["version"], mac);
+ assert_ne!(env!("CARGO_PKG_VERSION"), "0.1.0");
+}
+
+#[test]
+fn both_lockfiles_carry_the_same_kwnt_version() {
+ let root = Path::new(env!("CARGO_MANIFEST_DIR"));
+ for lock in ["Cargo.lock", "apps/mac/Cargo.lock"] {
+ let text = std::fs::read_to_string(root.join(lock)).unwrap();
+ let doc: toml::Value = toml::from_str(&text).unwrap();
+ let kwnt = doc["package"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .find(|p| p["name"].as_str() == Some("kwnt"))
+ .unwrap_or_else(|| panic!("no kwnt in {lock}"));
+ assert_eq!(kwnt["version"].as_str(), Some(env!("CARGO_PKG_VERSION")), "{lock}");
+ }
+}