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.

Make every kwant dependency easy to install: compose stack, kwnt doctor

Lin (kwant bot)8541af13da19
diff --git a/README.md b/README.md
index d0c40dee..88f37288 100644
--- a/README.md
+++ b/README.md
@@ -60,6 +60,8 @@ Screenshots come from a demo space with sample data.
- an Anthropic, OpenAI or xAI API key, which you add in the app under **Space settings → Accounts**.
- Optional: **Docker** for VM mode and the bots' shared browser, and [`uv`](https://docs.astral.sh/uv/) or `python3` for the Laya router.
+`kwnt doctor` (`cargo run -- doctor` from a clone) checks all of these and prints the install command for whatever is missing on your machine.
+
### Run from a fresh clone
```bash
@@ -127,16 +129,47 @@ systemctl enable --now kwnt
</details>
-### Docker Compose
+### VPS in 5 minutes (Docker Compose)
+
+One command starts everything kwant needs: kwnt, **Laya** (picks which bot answers, model baked in) and a private **Chromium** for the bots (VM mode), with no Docker socket mounted. You need Docker with Compose and about 4 GB of free RAM (Chromium is capped at 1.5 GB).
+
+```bash
+git clone https://github.com/alexsergivan/kwant.git && cd kwant
+KWNT_CLIS=claude,codex docker compose up -d --build # any of claude,codex,grok; leave out for none
+docker compose exec kwnt kwnt doctor # what works, and the fix for what doesn't
+docker compose exec kwnt claude auth login # sign a CLI in (codex login --device-auth, grok login --device-auth)
+docker compose exec kwnt kwnt token --raw # the token to paste on the sign-in screen
+```
+
+Or skip the CLIs and add an Anthropic, OpenAI or xAI API key in the app under **Space settings → Accounts**. CLI sign-ins live in the `kwnt-home` volume and data in `kwnt-data`, so both survive rebuilds.
+
+**HTTPS:** the UI is published on `127.0.0.1:8799` only. Put a TLS proxy in front, e.g. [Caddy](https://caddyserver.com) with this `Caddyfile`, and tell kwnt its address:
+
+```
+kwant.example.com {
+ reverse_proxy 127.0.0.1:8799
+}
+```
+
+```bash
+echo KWNT_ALLOWED_ORIGINS=https://kwant.example.com >> .env && docker compose up -d
+```
+
+`docker compose logs kwnt | grep kwnt_token` shows the sign-in link (open it once with your domain as the host); `docker compose exec kwnt kwnt token` prints it again.
+
+- **Image sizes** (measured): kwnt alone 0.2 GB; with `KWNT_CLIS=claude,codex,grok` 1.7 GB (the CLIs add about 0.9 GB, so they are off by default). Laya 3.2 GB, the browser 1.2 GB. Idle RAM: Laya about 1.7–2.3 GB, the browser about 0.4 GB, kwnt about 25 MB.
+- **kwant's own `execute_shell` tool** runs in per-team Docker containers, so it isn't available inside this stack: that would need the host's Docker socket, which is root on the host. The CLIs' own shell tools work inside the kwnt container.
+- **Upgrading from an older image:** kwnt now runs as uid 10001, not root. If it says `/data isn't writable`, run once: `docker compose run --rm -u root kwnt chown -R 10001:10001 /data`.
+
+### Without Docker
-`docker-compose.yml` runs kwnt with a Laya image that has the model baked in, so the server never downloads it at runtime:
+On Debian or Ubuntu, one script installs Chromium and Python 3 (for Laya), and optionally the CLIs for your user; it prints each command, and running it again changes nothing:
```bash
-docker compose up -d --build # UI on http://127.0.0.1:8799
-docker compose logs kwnt | grep kwnt_token # open that link once, with <this-host> as 127.0.0.1
+sh scripts/install-linux-deps.sh --clis claude,codex # then: kwnt serve, and kwnt doctor
```
-Data persists in the `kwnt-data` volume. `docker compose exec kwnt kwnt token` prints the sign-in link again, and `--raw` just the token to paste (`docker exec <container> kwnt token --raw` without Compose).
+On a Mac: `brew install --cask google-chrome` and `brew install python`; Docker Desktop is only needed for VM mode. `kwnt doctor` lists anything still missing, with the fix for your machine.
---
diff --git a/docker-compose.yml b/docker-compose.yml
index 10189286..3d641ede 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,5 +1,9 @@
-# Kwant + Laya for a VPS: docker compose up -d --build
-# The UI is bound to localhost; put a TLS reverse proxy in front (see docs/browser-service.md).
+# kwant on a server, everything in one command: docker compose up -d --build
+# 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
+# Check what's missing: docker compose exec kwnt kwnt doctor
services:
laya:
build:
@@ -10,23 +14,48 @@ services:
image: kwnt-laya:0.4.8
restart: unless-stopped
+ browser:
+ build:
+ context: docker
+ dockerfile: browser.Dockerfile
+ restart: unless-stopped
+ init: true
+ read_only: true
+ tmpfs:
+ - /tmp:rw,nosuid,size=512m
+ cap_drop: [ALL]
+ security_opt: ["no-new-privileges:true"]
+ mem_limit: 1536m
+ pids_limit: 512
+ # CDP is full control of the browser: reachable by kwnt on this network only, never published.
+ expose: ["9222"]
+
kwnt:
build:
context: .
dockerfile: docker/kwnt.Dockerfile
+ args:
+ KWNT_CLIS: ${KWNT_CLIS:-}
image: kwnt:latest
restart: unless-stopped
ports:
- - "127.0.0.1:8799:8799"
+ - "127.0.0.1:${KWNT_HOST_PORT:-8799}:8799"
environment:
LAYA_URL: http://laya:8000
KWNT_LAYA_MANAGED: "0"
- # KWNT_BROWSER_CDP_URL: http://browser:9222
+ KWNT_BROWSER_CDP_URL: http://browser:9222
+ # Your HTTPS address, e.g. https://kwant.example.com (comma list)
+ KWNT_ALLOWED_ORIGINS: ${KWNT_ALLOWED_ORIGINS:-}
volumes:
- kwnt-data:/data
+ # CLI sign-ins (~/.claude, ~/.codex, ~/.grok) survive rebuilds
+ - kwnt-home:/home/kwnt
depends_on:
laya:
condition: service_started
+ browser:
+ condition: service_started
volumes:
kwnt-data:
+ kwnt-home:
diff --git a/docker/kwnt-entrypoint.sh b/docker/kwnt-entrypoint.sh
new file mode 100644
index 00000000..c9592aa0
--- /dev/null
+++ b/docker/kwnt-entrypoint.sh
@@ -0,0 +1,10 @@
+#!/bin/sh
+# Images before the non-root user left /data owned by root; say how to fix that instead of failing later.
+set -eu
+data="${KWNT_DATA_DIR:-/data}"
+if [ "${1:-}" = kwnt ] && [ "${2:-}" = serve ] && ! [ -w "$data" ]; then
+ echo "kwnt: $data isn't writable by uid $(id -u) (volumes made by older kwant images belong to root)." >&2
+ echo "Fix it once with: docker compose run --rm -u root kwnt chown -R 10001:10001 $data" >&2
+ exit 1
+fi
+exec "$@"
diff --git a/docker/kwnt.Dockerfile b/docker/kwnt.Dockerfile
index 54dae886..90853847 100644
--- a/docker/kwnt.Dockerfile
+++ b/docker/kwnt.Dockerfile
@@ -1,4 +1,6 @@
# 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
FROM node:20-bookworm-slim AS web
WORKDIR /app/frontend
COPY frontend/package.json frontend/package-lock.json ./
@@ -14,16 +16,54 @@ COPY docker docker
COPY --from=web /app/frontend/dist frontend/dist
RUN cargo build --release --locked --bin kwnt
+# The CLIs asked for in KWNT_CLIS, with Node only if one of them needs it. Empty when none.
+FROM node:24-bookworm-slim AS clis
+ARG KWNT_CLIS=""
+RUN set -eu; mkdir -p /opt/clis/bin; \
+ want() { case ",$(echo "$KWNT_CLIS" | tr -d ' ')," in *",$1,"*) return 0;; *) return 1;; esac; }; \
+ for c in $(echo "$KWNT_CLIS" | tr ',' ' '); do \
+ case "$c" in claude|codex|grok) ;; *) echo "KWNT_CLIS: unknown CLI '$c' (use claude, codex, grok)" >&2; exit 1;; esac; \
+ done; \
+ pkgs=""; \
+ if want claude; then pkgs="$pkgs @anthropic-ai/claude-code"; fi; \
+ if want codex; then pkgs="$pkgs @openai/codex"; fi; \
+ if [ -n "$pkgs" ]; then \
+ npm install -g --prefix /opt/clis --no-fund --no-audit $pkgs && npm cache clean --force \
+ && cp /usr/local/bin/node /opt/clis/bin/node; \
+ fi; \
+ if want grok; then \
+ apt-get update && apt-get install -y --no-install-recommends curl ca-certificates; \
+ export HOME=/tmp/grok; mkdir -p "$HOME"; \
+ curl -fsSL https://x.ai/cli/install.sh | bash \
+ && cp -L "$HOME/.grok/bin/grok" /opt/clis/bin/grok; \
+ fi; \
+ ls /opt/clis/bin
+
FROM debian:bookworm-slim
+ARG KWNT_CLIS=""
+# The CLIs' own tools want git and a few basics; kwnt alone needs only CA certificates.
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
- && rm -rf /var/lib/apt/lists/*
+ $(if [ -n "$KWNT_CLIS" ]; then echo git curl procps ripgrep less; fi) \
+ && rm -rf /var/lib/apt/lists/* \
+ && 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
-ENV KWNT_HOST=0.0.0.0 \
+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 \
+ HOME=/home/kwnt \
+ KWNT_IN_DOCKER=1 \
+ KWNT_HOST=0.0.0.0 \
KWNT_PORT=8799 \
KWNT_DATA_DIR=/data \
KWNT_LAYA_MANAGED=0 \
LAYA_URL=http://laya:8000
+# Not root: CLI sign-ins (`docker compose exec kwnt claude auth login`) land in /home/kwnt.
+USER kwnt
+WORKDIR /home/kwnt
VOLUME /data
EXPOSE 8799
+ENTRYPOINT ["/usr/local/bin/kwnt-entrypoint"]
CMD ["kwnt", "serve"]
diff --git a/docs/browser-service.md b/docs/browser-service.md
index 5ab5a0d5..4ad8a6b9 100644
--- a/docs/browser-service.md
+++ b/docs/browser-service.md
@@ -55,6 +55,9 @@ The managed browser has a shared 1.5 GiB memory limit, rather than a separate Ch
## Existing/private browser service
+The repository's `docker-compose.yml` already does this: its `browser` service builds `docker/browser.Dockerfile` (read-only, all capabilities dropped, 1.5 GiB memory limit, CDP reachable on the compose network only) and kwnt gets `KWNT_BROWSER_CDP_URL=http://browser:9222`. `kwnt doctor` checks that the service answers.
+
+
Set the server-side CDP HTTP endpoint when an operator manages Chromium separately:
```bash
diff --git a/scripts/install-linux-deps.sh b/scripts/install-linux-deps.sh
new file mode 100755
index 00000000..04ce4c1e
--- /dev/null
+++ b/scripts/install-linux-deps.sh
@@ -0,0 +1,58 @@
+#!/bin/sh
+# Installs what kwant needs on a Debian/Ubuntu server without Docker: Chromium (the bots'
+# browser), Python 3 with venv (kwnt serve sets Laya up in it) and, if asked, the AI CLIs for
+# the current user. Prints every command before running it. Safe to run again.
+#
+# sh scripts/install-linux-deps.sh # browser + Python
+# sh scripts/install-linux-deps.sh --clis claude,codex # also the CLIs (claude, codex, grok)
+#
+# Then: kwnt doctor
+set -eu
+
+clis=""
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --clis) clis="${2:-}"; shift 2 ;;
+ --clis=*) clis="${1#--clis=}"; shift ;;
+ -h|--help) sed -n '2,9p' "$0"; exit 0 ;;
+ *) echo "unknown option: $1" >&2; exit 2 ;;
+ esac
+done
+
+run() { echo "+ $*"; "$@"; }
+sudo=""; [ "$(id -u)" -ne 0 ] && sudo="sudo"
+has() { command -v "$1" >/dev/null 2>&1; }
+
+if ! has apt-get; then
+ echo "This script is for Debian/Ubuntu (apt). Elsewhere install Chromium and Python 3 yourself, then run kwnt doctor." >&2
+ exit 1
+fi
+
+. /etc/os-release 2>/dev/null || true
+run $sudo apt-get update
+run $sudo apt-get install -y --no-install-recommends ca-certificates curl python3 python3-venv fonts-liberation
+if has chromium || has chromium-browser || has google-chrome || has google-chrome-stable; then
+ echo "Chrome/Chromium already installed"
+elif [ "${ID:-}" = ubuntu ]; then
+ # Ubuntu's chromium apt package is only a wrapper for the snap
+ run $sudo snap install chromium
+else
+ run $sudo apt-get install -y --no-install-recommends chromium
+fi
+
+for c in $(echo "$clis" | tr ',' ' '); do
+ case "$c" in
+ claude) has claude && echo "claude already installed" || { echo "+ curl -fsSL https://claude.ai/install.sh | bash"; curl -fsSL https://claude.ai/install.sh | bash; } ;;
+ grok) has grok && echo "grok already installed" || { echo "+ curl -fsSL https://x.ai/cli/install.sh | bash"; curl -fsSL https://x.ai/cli/install.sh | bash; } ;;
+ codex)
+ if has codex; then echo "codex already installed"
+ elif has npm; then run npm install -g @openai/codex
+ else echo "codex needs Node.js 18+ and npm: install them (https://nodejs.org), then: npm install -g @openai/codex" >&2
+ fi ;;
+ *) echo "unknown CLI '$c' (use claude, codex, grok)" >&2; exit 2 ;;
+ esac
+done
+
+echo
+echo "Done. Sign the CLIs in (claude auth login, codex login --device-auth, grok login --device-auth)"
+echo "or add an API key in the app, then run: kwnt doctor"
diff --git a/site-src/docs-install.html b/site-src/docs-install.html
index 18c12dd2..8e47f55a 100644
--- a/site-src/docs-install.html
+++ b/site-src/docs-install.html
@@ -59,13 +59,18 @@ WantedBy=multi-user.target</code></pre>
<pre><code>systemctl daemon-reload
systemctl enable --now kwnt</code></pre>
-<h2 id="docker">With Docker Compose</h2>
-<p><code>docker-compose.yml</code> runs kwant next to a Laya image with the model weights baked in, so the server never downloads them at runtime:</p>
-<pre><code>docker compose up -d --build <span class="c"># UI on http://127.0.0.1:8799</span>
-docker compose logs kwnt | grep kwnt_token <span class="c"># open that link once</span>
-docker compose exec kwnt kwnt token <span class="c"># print it again later</span>
-docker compose exec kwnt kwnt token --raw <span class="c"># just the token, to paste</span></code></pre>
-<p>Requests through Docker's published port arrive from the bridge network, so they count as remote: open the startup link once, using <code>127.0.0.1</code> as the host. An SSH tunnel doesn't skip sign-in here. Without Compose: <code>docker exec &lt;container&gt; kwnt token --raw</code>. Data persists in the <code>kwnt-data</code> volume.</p>
+<h2 id="docker">VPS in 5 minutes with Docker Compose</h2>
+<p>One command starts kwnt, Laya (with its model baked in) and a private Chromium for the bots, so VM mode works without mounting the Docker socket. You need Docker with Compose and about 4 GB of free RAM.</p>
+<pre><code>git clone https://github.com/alexsergivan/kwant.git &amp;&amp; cd kwant
+KWNT_CLIS=claude,codex docker compose up -d --build <span class="c"># any of claude,codex,grok; leave out for none</span>
+docker compose exec kwnt kwnt doctor <span class="c"># what works, and the fix for what doesn't</span>
+docker compose exec kwnt claude auth login <span class="c"># or codex login --device-auth, grok login --device-auth</span>
+docker compose exec kwnt kwnt token --raw <span class="c"># the token to paste on the sign-in screen</span></code></pre>
+<p>Instead of CLIs you can add an API key in the app under <strong>Space settings → Accounts</strong>. CLI sign-ins persist in the <code>kwnt-home</code> volume and data in <code>kwnt-data</code>. The UI is published on <code>127.0.0.1:8799</code> only: put HTTPS in front (below) and set <code>KWNT_ALLOWED_ORIGINS=https://your.domain</code> in <code>.env</code>. With Caddy that's a two-line <code>Caddyfile</code>: <code>your.domain { reverse_proxy 127.0.0.1:8799 }</code>.</p>
+<p>Requests through Docker's published port count as remote, so sign in with the token (<code>docker compose logs kwnt | grep kwnt_token</code> shows the link). kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
+
+<h2 id="deps">Without Docker: one script, then <code>kwnt doctor</code></h2>
+<p>On Debian or Ubuntu, <code>sh scripts/install-linux-deps.sh --clis claude,codex</code> installs Chromium, Python 3 for Laya and the CLIs you name; it prints each command and is safe to run again. On a Mac: <code>brew install --cask google-chrome</code> and <code>brew install python</code>. Then <code>kwnt doctor</code> lists anything still missing, with the exact fix for your machine.</p>
<h2 id="proxy">Behind an HTTPS reverse proxy</h2>
<p>Only the HTTPS port needs to be reachable from outside. Forward the original <code>Host</code> header, because the live browser stream checks <code>Origin</code> against it, and allow WebSocket upgrades:</p>
diff --git a/site/docs/install.html b/site/docs/install.html
index a2a04212..638fdcc7 100644
--- a/site/docs/install.html
+++ b/site/docs/install.html
@@ -108,13 +108,18 @@ WantedBy=multi-user.target</code></pre>
<pre><code>systemctl daemon-reload
systemctl enable --now kwnt</code></pre>
-<h2 id="docker">With Docker Compose</h2>
-<p><code>docker-compose.yml</code> runs kwant next to a Laya image with the model weights baked in, so the server never downloads them at runtime:</p>
-<pre><code>docker compose up -d --build <span class="c"># UI on http://127.0.0.1:8799</span>
-docker compose logs kwnt | grep kwnt_token <span class="c"># open that link once</span>
-docker compose exec kwnt kwnt token <span class="c"># print it again later</span>
-docker compose exec kwnt kwnt token --raw <span class="c"># just the token, to paste</span></code></pre>
-<p>Requests through Docker's published port arrive from the bridge network, so they count as remote: open the startup link once, using <code>127.0.0.1</code> as the host. An SSH tunnel doesn't skip sign-in here. Without Compose: <code>docker exec &lt;container&gt; kwnt token --raw</code>. Data persists in the <code>kwnt-data</code> volume.</p>
+<h2 id="docker">VPS in 5 minutes with Docker Compose</h2>
+<p>One command starts kwnt, Laya (with its model baked in) and a private Chromium for the bots, so VM mode works without mounting the Docker socket. You need Docker with Compose and about 4 GB of free RAM.</p>
+<pre><code>git clone https://github.com/alexsergivan/kwant.git &amp;&amp; cd kwant
+KWNT_CLIS=claude,codex docker compose up -d --build <span class="c"># any of claude,codex,grok; leave out for none</span>
+docker compose exec kwnt kwnt doctor <span class="c"># what works, and the fix for what doesn't</span>
+docker compose exec kwnt claude auth login <span class="c"># or codex login --device-auth, grok login --device-auth</span>
+docker compose exec kwnt kwnt token --raw <span class="c"># the token to paste on the sign-in screen</span></code></pre>
+<p>Instead of CLIs you can add an API key in the app under <strong>Space settings → Accounts</strong>. CLI sign-ins persist in the <code>kwnt-home</code> volume and data in <code>kwnt-data</code>. The UI is published on <code>127.0.0.1:8799</code> only: put HTTPS in front (below) and set <code>KWNT_ALLOWED_ORIGINS=https://your.domain</code> in <code>.env</code>. With Caddy that's a two-line <code>Caddyfile</code>: <code>your.domain { reverse_proxy 127.0.0.1:8799 }</code>.</p>
+<p>Requests through Docker's published port count as remote, so sign in with the token (<code>docker compose logs kwnt | grep kwnt_token</code> shows the link). kwant's own <code>execute_shell</code> tool isn't available in this stack, because it would need the host's Docker socket; the CLIs' shell tools work. Upgrading from an older image, where kwnt ran as root? If it says <code>/data isn't writable</code>, run once: <code>docker compose run --rm -u root kwnt chown -R 10001:10001 /data</code>.</p>
+
+<h2 id="deps">Without Docker: one script, then <code>kwnt doctor</code></h2>
+<p>On Debian or Ubuntu, <code>sh scripts/install-linux-deps.sh --clis claude,codex</code> installs Chromium, Python 3 for Laya and the CLIs you name; it prints each command and is safe to run again. On a Mac: <code>brew install --cask google-chrome</code> and <code>brew install python</code>. Then <code>kwnt doctor</code> lists anything still missing, with the exact fix for your machine.</p>
<h2 id="proxy">Behind an HTTPS reverse proxy</h2>
<p>Only the HTTPS port needs to be reachable from outside. Forward the original <code>Host</code> header, because the live browser stream checks <code>Origin</code> against it, and allow WebSocket upgrades:</p>
diff --git a/src/doctor.rs b/src/doctor.rs
new file mode 100644
index 00000000..81477079
--- /dev/null
+++ b/src/doctor.rs
@@ -0,0 +1,486 @@
+//! `kwnt doctor`: every part kwant needs on this machine, whether it works, and the exact command
+//! that fixes it here. The fix text is per platform (Mac, Linux, inside Docker), and Settings shows
+//! the same advice for the computer modes and the Laya card.
+
+use crate::config::Config;
+use crate::profiles::Engine;
+use std::path::Path;
+use std::time::Duration;
+
+/// Where kwnt runs, which decides how a missing part is installed.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Platform {
+ Mac,
+ Linux,
+ /// Inside a container, e.g. the compose stack: parts come from compose services and build args.
+ Docker,
+}
+
+impl Platform {
+ /// This process's platform. `KWNT_IN_DOCKER=1` (set by kwant's image) or `/.dockerenv` means
+ /// Docker.
+ pub fn detect() -> Self {
+ let flagged = std::env::var("KWNT_IN_DOCKER").is_ok_and(|v| v == "1");
+ Self::from_parts(std::env::consts::OS, flagged || Path::new("/.dockerenv").exists())
+ }
+
+ pub fn from_parts(os: &str, in_docker: bool) -> Self {
+ match (in_docker, os) {
+ (true, _) => Platform::Docker,
+ (false, "macos") => Platform::Mac,
+ _ => Platform::Linux,
+ }
+ }
+
+ pub fn label(self) -> &'static str {
+ match self {
+ Platform::Mac => "Mac",
+ Platform::Linux => "Linux",
+ Platform::Docker => "Docker container",
+ }
+ }
+}
+
+/// How to get a Chrome for local mode.
+pub fn chrome_fix(p: Platform) -> &'static str {
+ match p {
+ Platform::Mac => "brew install --cask google-chrome (or set KWNT_CHROME_PATH to a Chrome you have)",
+ Platform::Linux => "sudo apt-get install -y chromium (Ubuntu: sudo snap install chromium; or set KWNT_CHROME_PATH)",
+ Platform::Docker => "Inside Docker, use VM mode with the compose browser service: docker compose up -d browser",
+ }
+}
+
+/// How to make VM mode's browser available.
+pub fn vm_fix(p: Platform) -> &'static str {
+ match p {
+ Platform::Mac => "Install and open Docker Desktop: brew install --cask docker",
+ Platform::Linux => "Install Docker: curl -fsSL https://get.docker.com | sudo sh && sudo usermod -aG docker $USER (then log in again), or set KWNT_BROWSER_CDP_URL to a private Chromium",
+ Platform::Docker => "Set KWNT_BROWSER_CDP_URL=http://browser:9222 for kwnt and start the compose browser service: docker compose up -d browser",
+ }
+}
+
+/// How to get Laya answering at the configured URL.
+pub fn laya_fix(p: Platform, managed: bool) -> &'static str {
+ match (p, managed) {
+ (Platform::Docker, _) => "Start the Laya service: docker compose up -d laya (logs: docker compose logs laya; kwnt reads LAYA_URL=http://laya:8000)",
+ (Platform::Mac, true) => "`kwnt serve` installs and starts Laya itself (the first start downloads ~420 MB); it needs Python 3: brew install python (or uv: brew install uv)",
+ (Platform::Linux, true) => "`kwnt serve` installs and starts Laya itself (the first start downloads ~420 MB); it needs Python 3 with venv: sudo apt-get install -y python3-venv",
+ (_, false) => "Let kwnt run Laya: start `kwnt serve` without --no-laya and without KWNT_LAYA_MANAGED=0, or start laya-serve at LAYA_URL yourself",
+ }
+}
+
+/// How to install an engine's CLI here.
+pub fn cli_install_fix(engine: Engine, p: Platform) -> &'static str {
+ match (engine, p) {
+ (_, Platform::Docker) => "Rebuild the image with the CLIs: KWNT_CLIS=claude,codex,grok docker compose up -d --build",
+ (Engine::Claude, _) => "curl -fsSL https://claude.ai/install.sh | bash",
+ (Engine::Codex, Platform::Mac) => "brew install --cask codex (or npm install -g @openai/codex)",
+ (Engine::Codex, _) => "npm install -g @openai/codex (needs Node.js 18+)",
+ (Engine::Grok, _) => "curl -fsSL https://x.ai/cli/install.sh | bash",
+ (Engine::Custom, _) => "Add a Custom API account in the app: Space settings → Accounts",
+ }
+}
+
+/// How to sign an engine's CLI in here (or the API-key alternative).
+pub fn cli_sign_in_fix(engine: Engine, p: Platform) -> String {
+ let (cmd, key) = match engine {
+ Engine::Claude => ("claude auth login", "ANTHROPIC_API_KEY"),
+ Engine::Codex => ("codex login --device-auth", "OPENAI_API_KEY"),
+ Engine::Grok => ("grok login --device-auth", "XAI_API_KEY"),
+ Engine::Custom => return cli_install_fix(engine, p).to_string(),
+ };
+ let run = match p {
+ Platform::Docker => format!("docker compose exec kwnt {cmd}"),
+ _ => cmd.to_string(),
+ };
+ format!("{run} (or set {key}, or use Sign in / an API key in the app: Space settings → Accounts)")
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Status {
+ Ok,
+ /// Works without it, but something is missing or worth doing.
+ Warn,
+ /// kwant can't do its job without it.
+ Fail,
+ /// Not used on this platform.
+ Skip,
+}
+
+impl Status {
+ fn mark(self) -> &'static str {
+ match self {
+ Status::Ok => "ok ",
+ Status::Warn => "warn",
+ Status::Fail => "FAIL",
+ Status::Skip => " - ",
+ }
+ }
+}
+
+#[derive(Clone, Debug)]
+pub struct Check {
+ pub name: String,
+ pub status: Status,
+ pub detail: String,
+ pub fix: Option<String>,
+}
+
+impl Check {
+ fn new(name: &str, status: Status, detail: impl Into<String>, fix: Option<String>) -> Self {
+ Self { name: name.into(), status, detail: detail.into(), fix }
+ }
+}
+
+/// What the checks found on this machine; gathered by [`gather`], judged by [`checks`].
+#[derive(Clone, Debug)]
+pub struct Facts {
+ pub data_dir: String,
+ pub data_dir_writable: Result<(), String>,
+ pub laya_url: String,
+ pub laya_managed: bool,
+ pub laya_up: bool,
+ pub cdp_url: Option<String>,
+ pub cdp_up: bool,
+ pub docker: bool,
+ pub chrome: Option<String>,
+ /// Per engine: installed binary, signed in (`None`: unknown), signed in via an API key env.
+ pub clis: Vec<(Engine, Option<String>, Option<bool>, bool)>,
+ pub loopback_bind: bool,
+ pub token: bool,
+ pub https_origin: Option<String>,
+}
+
+/// Turns the facts into checks with fixes for `p`.
+pub fn checks(f: &Facts, p: Platform) -> Vec<Check> {
+ let mut out = Vec::new();
+ out.push(match &f.data_dir_writable {
+ Ok(()) => Check::new("Data folder", Status::Ok, format!("{} is writable", f.data_dir), None),
+ Err(e) => Check::new(
+ "Data folder",
+ Status::Fail,
+ format!("{}: {e}", f.data_dir),
+ Some(match p {
+ Platform::Docker => "docker compose run --rm -u root kwnt chown -R 10001:10001 /data".into(),
+ _ => format!("Run kwnt as the user that owns {0}, or: sudo chown -R $USER {0}", f.data_dir),
+ }),
+ ),
+ });
+
+ out.push(if f.laya_up {
+ Check::new("Laya router", Status::Ok, format!("answers at {}", f.laya_url), None)
+ } else {
+ Check::new(
+ "Laya router",
+ Status::Warn,
+ format!("not answering at {}; bots are picked by keywords", f.laya_url),
+ Some(laya_fix(p, f.laya_managed).into()),
+ )
+ });
+
+ // The browser: VM (a CDP service or Docker) and/or local Chrome; one of them is enough.
+ let vm = match &f.cdp_url {
+ Some(url) if f.cdp_up => (Status::Ok, format!("browser service answers at {url}")),
+ Some(url) => (Status::Fail, format!("browser service at {url} isn't answering")),
+ None if f.docker => (Status::Ok, "Docker is running; kwant starts its browser container on first use".into()),
+ None => (Status::Fail, "no Docker and no KWNT_BROWSER_CDP_URL".into()),
+ };
+ let local = match (&f.chrome, p) {
+ (_, Platform::Docker) => (Status::Skip, "not used inside Docker".to_string()),
+ (Some(path), _) => (Status::Ok, format!("Chrome at {path}")),
+ (None, _) => (Status::Fail, "no Chrome or Chromium found".to_string()),
+ };
+ let any_browser = vm.0 == Status::Ok || local.0 == Status::Ok;
+ let soften = |s: Status| if s == Status::Fail && any_browser { Status::Warn } else { s };
+ let vm_status = soften(vm.0);
+ out.push(Check::new("Browser (VM)", vm_status, vm.1, (vm_status != Status::Ok).then(|| vm_fix(p).into())));
+ let local_status = soften(local.0);
+ out.push(Check::new(
+ "Browser (local)",
+ local_status,
+ local.1,
+ matches!(local_status, Status::Warn | Status::Fail).then(|| chrome_fix(p).into()),
+ ));
+
+ out.push(match p {
+ Platform::Docker => Check::new(
+ "kwant shell",
+ Status::Skip,
+ "kwant's own execute_shell needs Docker on the host; inside the container bots use their CLI's shell tools",
+ None,
+ ),
+ _ if f.docker => Check::new("kwant shell", Status::Ok, "Docker runs kwant's execute_shell containers", None),
+ _ => Check::new(
+ "kwant shell",
+ Status::Warn,
+ "no Docker: kwant's execute_shell is off in VM mode (the CLIs' own shell tools still work)",
+ Some(vm_fix(p).into()),
+ ),
+ });
+
+ let mut ready = 0;
+ for (engine, bin, signed_in, via_key) in &f.clis {
+ let name = engine.as_str();
+ let check = match (bin, signed_in, via_key) {
+ (_, _, true) => {
+ ready += 1;
+ Check::new(name, Status::Ok, "API key set in the environment", None)
+ }
+ (None, _, _) => Check::new(name, Status::Warn, "not installed", Some(cli_install_fix(*engine, p).into())),
+ (Some(path), Some(true), _) => {
+ ready += 1;
+ Check::new(name, Status::Ok, format!("{path}, signed in"), None)
+ }
+ (Some(path), state, _) => Check::new(
+ name,
+ Status::Warn,
+ format!("{path}, {}", if state.is_none() { "sign-in state unknown" } else { "not signed in" }),
+ Some(cli_sign_in_fix(*engine, p)),
+ ),
+ };
+ out.push(check);
+ }
+ if ready == 0 {
+ out.push(Check::new(
+ "AI account",
+ Status::Warn,
+ "no CLI is signed in here (API keys added in the app aren't checked by doctor)",
+ Some("Sign one CLI in (see above) or add an API key in the app: Space settings → Accounts".into()),
+ ));
+ }
+
+ out.push(if f.loopback_bind {
+ Check::new("Access", Status::Ok, "listening on this machine only", None)
+ } else if !f.token {
+ Check::new(
+ "Access",
+ Status::Warn,
+ "no sign-in token yet; `kwnt serve` creates one on first start",
+ Some(match p {
+ Platform::Docker => "docker compose exec kwnt kwnt token --raw".into(),
+ _ => "kwnt token".into(),
+ }),
+ )
+ } else if let Some(origin) = &f.https_origin {
+ Check::new("Access", Status::Ok, format!("token set; HTTPS origin {origin}"), None)
+ } else {
+ Check::new(
+ "Access",
+ Status::Warn,
+ "token set, but no HTTPS origin: don't open kwant to the internet over plain http",
+ Some("Put HTTPS in front, e.g. Caddy: `your.domain { reverse_proxy 127.0.0.1:8799 }`, and set KWNT_ALLOWED_ORIGINS=https://your.domain".into()),
+ )
+ });
+ out
+}
+
+/// Looks at this machine. Network checks time out after a few seconds each.
+pub async fn gather(config: &Config) -> Facts {
+ let http = reqwest::Client::builder().timeout(Duration::from_secs(3)).build().unwrap_or_default();
+ let laya_url = config.laya_url.trim_end_matches('/').to_string();
+ let laya_up = http
+ .get(format!("{laya_url}/health"))
+ .send()
+ .await
+ .is_ok_and(|r| r.status().is_success());
+ let cdp_url = config.browser_cdp_url.clone().filter(|u| !u.trim().is_empty());
+ let cdp_up = match &cdp_url {
+ // Chrome only answers its HTTP endpoints for an IP or localhost Host header
+ Some(url) => http
+ .get(format!("{}/json/version", url.trim_end_matches('/')))
+ .header(reqwest::header::HOST, "localhost")
+ .send()
+ .await
+ .is_ok_and(|r| r.status().is_success()),
+ None => false,
+ };
+ let docker = crate::sandbox::SandboxManager::new().is_docker_available().await;
+ let chrome = crate::sandbox::computer::local_chrome_path().map(|p| p.display().to_string());
+
+ let mut clis = Vec::new();
+ for (engine, key) in [(Engine::Claude, "ANTHROPIC_API_KEY"), (Engine::Codex, "OPENAI_API_KEY"), (Engine::Grok, "XAI_API_KEY")] {
+ let bin = crate::drivers::find_cli_binary(engine.as_str());
+ let signed_in = if bin.is_some() {
+ crate::profiles::status::probe(engine, None).await.signed_in
+ } else {
+ None
+ };
+ let via_key = std::env::var(key).is_ok_and(|v| !v.trim().is_empty());
+ clis.push((engine, bin, signed_in, via_key));
+ }
+
+ let https_origin = std::env::var("KWNT_ALLOWED_ORIGINS")
+ .ok()
+ .and_then(|v| v.split(',').map(str::trim).find(|o| o.starts_with("https://")).map(String::from));
+ Facts {
+ data_dir: config.data_dir.display().to_string(),
+ data_dir_writable: writable(&config.data_dir),
+ laya_url,
+ laya_managed: config.laya_managed,
+ laya_up,
+ cdp_url,
+ cdp_up,
+ docker,
+ chrome,
+ clis,
+ // In a container kwnt binds 0.0.0.0 and the published port decides; judge by token+HTTPS
+ loopback_bind: Platform::detect() != Platform::Docker && crate::server::auth::is_loopback_bind(&config.host),
+ token: crate::server::auth::env_token().is_some() || crate::server::auth::read_existing(&config.data_dir).is_ok(),
+ https_origin,
+ }
+}
+
+fn writable(dir: &Path) -> Result<(), String> {
+ std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
+ let probe = dir.join(format!(".kwnt-doctor-{}", std::process::id()));
+ std::fs::write(&probe, b"ok").map_err(|e| e.to_string())?;
+ let _ = std::fs::remove_file(probe);
+ Ok(())
+}
+
+/// The report `kwnt doctor` prints.
+pub fn render(checks: &[Check], p: Platform) -> String {
+ let mut s = format!("kwant doctor · {}\n\n", p.label());
+ for c in checks {
+ s.push_str(&format!(" {} {:<16} {}\n", c.status.mark(), c.name, c.detail));
+ if let Some(fix) = &c.fix {
+ s.push_str(&format!(" fix: {fix}\n"));
+ }
+ }
+ let fails = checks.iter().filter(|c| c.status == Status::Fail).count();
+ let warns = checks.iter().filter(|c| c.status == Status::Warn).count();
+ s.push('\n');
+ s.push_str(&match (fails, warns) {
+ (0, 0) => "Everything kwant needs is here.\n".to_string(),
+ (0, w) => format!("kwant can run. {w} optional part(s) missing or not set up; see the fixes above.\n"),
+ (f, _) => format!("{f} required part(s) missing; kwant can't work fully until they're fixed.\n"),
+ });
+ s
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn healthy() -> Facts {
+ Facts {
+ data_dir: "/data".into(),
+ data_dir_writable: Ok(()),
+ laya_url: "http://laya:8000".into(),
+ laya_managed: false,
+ laya_up: true,
+ cdp_url: Some("http://browser:9222".into()),
+ cdp_up: true,
+ docker: false,
+ chrome: None,
+ clis: vec![
+ (Engine::Claude, Some("/opt/clis/bin/claude".into()), Some(false), false),
+ (Engine::Codex, None, None, false),
+ (Engine::Grok, None, None, false),
+ ],
+ loopback_bind: false,
+ token: true,
+ https_origin: Some("https://kwant.example".into()),
+ }
+ }
+
+ fn by_name<'a>(cs: &'a [Check], name: &str) -> &'a Check {
+ cs.iter().find(|c| c.name == name).unwrap()
+ }
+
+ #[test]
+ fn platform_detection() {
+ assert_eq!(Platform::from_parts("macos", false), Platform::Mac);
+ assert_eq!(Platform::from_parts("linux", false), Platform::Linux);
+ assert_eq!(Platform::from_parts("macos", true), Platform::Docker);
+ assert_eq!(Platform::from_parts("linux", true), Platform::Docker);
+ }
+
+ #[test]
+ fn compose_stack_is_green_except_unsigned_clis() {
+ let cs = checks(&healthy(), Platform::Docker);
+ assert!(cs.iter().all(|c| c.status != Status::Fail));
+ for name in ["Data folder", "Laya router", "Browser (VM)", "Access"] {
+ assert_eq!(by_name(&cs, name).status, Status::Ok, "{name}");
+ }
+ assert_eq!(by_name(&cs, "Browser (local)").status, Status::Skip);
+ let claude = by_name(&cs, "claude");
+ assert_eq!(claude.status, Status::Warn);
+ assert!(claude.fix.as_deref().unwrap().starts_with("docker compose exec kwnt claude auth login"));
+ assert!(by_name(&cs, "codex").fix.as_deref().unwrap().contains("KWNT_CLIS="));
+ }
+
+ #[test]
+ fn no_browser_at_all_fails_with_platform_fixes() {
+ let mut f = healthy();
+ f.cdp_url = None;
+ let docker = checks(&f, Platform::Docker);
+ assert_eq!(by_name(&docker, "Browser (VM)").status, Status::Fail);
+ assert!(by_name(&docker, "Browser (VM)").fix.as_deref().unwrap().contains("docker compose up -d browser"));
+
+ let linux = checks(&f, Platform::Linux);
+ assert_eq!(by_name(&linux, "Browser (VM)").status, Status::Fail);
+ assert_eq!(by_name(&linux, "Browser (local)").status, Status::Fail);
+ let fix = by_name(&linux, "Browser (VM)").fix.clone().unwrap();
+ assert!(fix.contains("get.docker.com") && !fix.contains("Docker Desktop"));
+ assert!(by_name(&linux, "Browser (local)").fix.as_deref().unwrap().contains("apt-get install -y chromium"));
+
+ let mac = checks(&f, Platform::Mac);
+ assert!(by_name(&mac, "Browser (VM)").fix.as_deref().unwrap().contains("Docker Desktop"));
+ assert!(by_name(&mac, "Browser (local)").fix.as_deref().unwrap().contains("brew install --cask google-chrome"));
+ }
+
+ #[test]
+ fn one_working_browser_is_enough() {
+ let mut f = healthy();
+ f.cdp_url = None;
+ f.chrome = Some("/usr/bin/chromium".into());
+ let cs = checks(&f, Platform::Linux);
+ assert_eq!(by_name(&cs, "Browser (local)").status, Status::Ok);
+ assert_eq!(by_name(&cs, "Browser (VM)").status, Status::Warn);
+ assert!(cs.iter().all(|c| c.status != Status::Fail));
+ }
+
+ #[test]
+ fn laya_and_data_dir_fixes() {
+ let mut f = healthy();
+ f.laya_up = false;
+ f.data_dir_writable = Err("Permission denied".into());
+ let cs = checks(&f, Platform::Docker);
+ assert_eq!(by_name(&cs, "Laya router").status, Status::Warn);
+ assert!(by_name(&cs, "Laya router").fix.as_deref().unwrap().contains("docker compose up -d laya"));
+ assert_eq!(by_name(&cs, "Data folder").status, Status::Fail);
+ assert!(by_name(&cs, "Data folder").fix.as_deref().unwrap().contains("chown -R 10001:10001 /data"));
+ f.laya_managed = true;
+ assert!(laya_fix(Platform::Linux, true).contains("python3-venv"));
+ assert!(laya_fix(Platform::Mac, true).contains("brew install python"));
+ }
+
+ #[test]
+ fn api_key_or_sign_in_counts_as_ready() {
+ let mut f = healthy();
+ let cs = checks(&f, Platform::Docker);
+ assert_eq!(by_name(&cs, "AI account").status, Status::Warn);
+ f.clis[0].3 = true;
+ let cs = checks(&f, Platform::Docker);
+ assert_eq!(by_name(&cs, "claude").status, Status::Ok);
+ assert!(cs.iter().all(|c| c.name != "AI account"));
+ }
+
+ #[test]
+ fn access_without_https_warns() {
+ let mut f = healthy();
+ f.https_origin = None;
+ let cs = checks(&f, Platform::Linux);
+ assert_eq!(by_name(&cs, "Access").status, Status::Warn);
+ f.loopback_bind = true;
+ assert_eq!(by_name(&checks(&f, Platform::Linux), "Access").status, Status::Ok);
+ }
+
+ #[test]
+ fn render_summarises() {
+ let out = render(&checks(&healthy(), Platform::Docker), Platform::Docker);
+ assert!(out.starts_with("kwant doctor · Docker container"));
+ assert!(out.contains("kwant can run."));
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 6dab7d00..a17b75bc 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1,6 +1,7 @@
pub mod broker;
pub mod config;
pub mod db;
+pub mod doctor;
pub mod documents;
pub mod drivers;
pub mod embedded;
diff --git a/src/main.rs b/src/main.rs
index 3b231223..6928f892 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -36,6 +36,10 @@ pub enum Commands {
/// Print the resolved config and whether local data files exist
Status,
+ /// Check everything kwant needs here (Laya, browser, AI CLIs, data folder, access) and print
+ /// the command that fixes each missing part on this platform. Exits 1 if a required part is missing
+ Doctor,
+
/// List kwants stored in the local database
Agents,
@@ -122,6 +126,14 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.map_err(|e| e as Box<dyn std::error::Error>)?;
}
Some(Commands::Status) => print_status(&config),
+ Some(Commands::Doctor) => {
+ let platform = kwnt::doctor::Platform::detect();
+ let checks = kwnt::doctor::checks(&kwnt::doctor::gather(&config).await, platform);
+ print!("{}", kwnt::doctor::render(&checks, platform));
+ if checks.iter().any(|c| c.status == kwnt::doctor::Status::Fail) {
+ std::process::exit(1);
+ }
+ }
Some(Commands::Agents) => print_agents(&config).await?,
Some(Commands::Teams) => print_teams(&config).await?,
Some(Commands::Channels) => print_channels(&config).await?,
diff --git a/src/router/sidecar.rs b/src/router/sidecar.rs
index 9a3c080a..f5fd463c 100644
--- a/src/router/sidecar.rs
+++ b/src/router/sidecar.rs
@@ -67,12 +67,17 @@ async fn supervise(router: LayaRouter, opts: SidecarOptions, shutdown: Cancellat
let port = match local_port(&router.base_url) {
Some(port) if opts.managed => port,
_ => {
+ let platform = crate::doctor::Platform::detect();
let why = if opts.managed {
- "Laya URL is not on this machine, so the app cannot start it"
+ let fix = match platform {
+ crate::doctor::Platform::Docker => crate::doctor::laya_fix(platform, false),
+ _ => "Start laya-serve at that address, or unset LAYA_URL so kwnt runs Laya here",
+ };
+ format!("Laya URL is not on this machine, so the app cannot start it. {fix}")
} else {
- "Laya is not answering and the app is not managing it; using keyword routing"
+ format!("Laya is not answering and the app is not managing it; using keyword routing. {}", crate::doctor::laya_fix(platform, false))
};
- router.set_status(LayaState::Offline, why, false);
+ router.set_status(LayaState::Offline, &why, false);
return monitor_external(router, shutdown).await;
}
};
@@ -85,7 +90,8 @@ async fn supervise(router: LayaRouter, opts: SidecarOptions, shutdown: Cancellat
let bin = match ensure_installed(&router, &dir).await {
Ok(bin) => bin,
Err(e) => {
- router.set_status(LayaState::Failed, &format!("Install failed: {e}"), true);
+ let fix = crate::doctor::laya_fix(crate::doctor::Platform::detect(), true);
+ router.set_status(LayaState::Failed, &format!("Install failed: {e}. {fix}"), true);
if wait_or_cancel(&shutdown, Duration::from_secs(300)).await {
return;
}
diff --git a/src/sandbox/browser.rs b/src/sandbox/browser.rs
index 75f80111..19012118 100644
--- a/src/sandbox/browser.rs
+++ b/src/sandbox/browser.rs
@@ -15,6 +15,27 @@ use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
+/// The DevTools WebSocket request for `url`. Chrome refuses a DevTools connection whose Host is a
+/// name other than localhost (500 on the upgrade), so a plain-ws name such as the compose service
+/// `browser` gets `Host: localhost`, as the `/json` requests do. IPs and wss (a hosted service
+/// that may need its own Host) are left alone.
+pub(crate) fn cdp_ws_request(url: &str) -> Result<tokio_tungstenite::tungstenite::handshake::client::Request, BrowserError> {
+ use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+ let mut req = url.into_client_request().map_err(|e| BrowserError::Ws(e.to_string()))?;
+ let named_host = req.uri().scheme_str() == Some("ws")
+ && req.uri().host().is_some_and(|h| h != "localhost" && h.trim_matches(['[', ']']).parse::<std::net::IpAddr>().is_err());
+ if named_host {
+ req.headers_mut().insert(reqwest::header::HOST, reqwest::header::HeaderValue::from_static("localhost"));
+ }
+ Ok(req)
+}
+
+/// Opens a DevTools WebSocket (see [`cdp_ws_request`]).
+pub(crate) async fn connect_cdp(url: &str) -> Result<WsStream, BrowserError> {
+ let (ws, _) = connect_async(cdp_ws_request(url)?).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
+ Ok(ws)
+}
+
/// `function(needle)` evaluated in the page. Collects visible interactive elements (incl. open
/// shadow roots and same-origin iframes), topmost first. With a needle, picks the best label match
/// and either returns its viewport center (when nothing covers it) or clicks it directly.
@@ -378,10 +399,7 @@ impl BrowserController {
) -> Result<(), BrowserError> {
if guard.is_none() {
let ws_url = self.get_ws_url().await?;
- let (ws, _) = connect_async(&ws_url)
- .await
- .map_err(|e| BrowserError::Ws(e.to_string()))?;
- **guard = Some(ws);
+ **guard = Some(connect_cdp(&ws_url).await?);
}
Ok(())
}
@@ -855,3 +873,22 @@ impl BrowserController {
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::cdp_ws_request;
+
+ fn host(url: &str) -> String {
+ cdp_ws_request(url).unwrap().headers()["host"].to_str().unwrap().to_string()
+ }
+
+ #[test]
+ fn cdp_ws_host_is_localhost_for_service_names() {
+ // Chrome answers 500 to a DevTools upgrade with Host: browser:9222
+ assert_eq!(host("ws://browser:9222/devtools/browser/x"), "localhost");
+ assert_eq!(host("ws://127.0.0.1:9223/devtools/page/x"), "127.0.0.1:9223");
+ assert_eq!(host("ws://[::1]:9222/devtools/page/x"), "[::1]:9222");
+ assert_eq!(host("ws://localhost:9222/devtools/page/x"), "localhost:9222");
+ assert_eq!(host("wss://cdp.example.com/devtools/browser/x"), "cdp.example.com");
+ }
+}
diff --git a/src/sandbox/computer.rs b/src/sandbox/computer.rs
index eca6d845..538821d7 100644
--- a/src/sandbox/computer.rs
+++ b/src/sandbox/computer.rs
@@ -5,6 +5,7 @@
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::Duration;
+use crate::doctor::{self, Platform};
/// Settings row holding the person's explicit choice.
pub const SETTING_KEY: &str = "computer_mode";
@@ -127,10 +128,11 @@ pub fn has_display(os: &str, display: Option<&str>, wayland: Option<&str>) -> bo
/// Why local mode cannot run here, or `None` if it can. No display is needed: local Chrome runs
/// without a window and the app shows it.
-pub fn local_unavailable_reason(chrome: Option<&Path>) -> Option<String> {
- chrome.is_none().then(|| format!(
- "No Chrome or Chromium was found. Install Google Chrome, or set {CHROME_PATH_ENV} to its path."
- ))
+pub fn local_unavailable_reason(chrome: Option<&Path>, platform: Platform) -> Option<String> {
+ chrome.is_none().then(|| match platform {
+ Platform::Docker => format!("kwant runs in a Docker container, which has no Chrome. {}", doctor::chrome_fix(platform)),
+ _ => format!("No Chrome or Chromium was found. Install it: {}", doctor::chrome_fix(platform)),
+ })
}
/// Why local Chrome cannot be opened as a window here, or `None` if it can.
@@ -140,10 +142,10 @@ pub fn window_unavailable_reason(display: bool) -> Option<String> {
/// Why vm mode cannot run here, or `None` if it can. A configured browser service URL is enough
/// for the browser even without Docker.
-pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool) -> Option<String> {
- (!docker && !browser_url_configured).then(|| {
- "Docker is not installed or not running. Install and start Docker (Docker Desktop on a Mac) to use the VM."
- .into()
+pub fn vm_unavailable_reason(docker: bool, browser_url_configured: bool, platform: Platform) -> Option<String> {
+ (!docker && !browser_url_configured).then(|| match platform {
+ Platform::Docker => format!("No browser service is set for this container. {}", doctor::vm_fix(platform)),
+ _ => format!("Docker is not installed or not running. {}", doctor::vm_fix(platform)),
})
}
@@ -160,7 +162,7 @@ pub fn local_chrome_path() -> Option<PathBuf> {
/// [`local_unavailable_reason`] for this process's environment.
pub fn local_reason() -> Option<String> {
- local_unavailable_reason(local_chrome_path().as_deref())
+ local_unavailable_reason(local_chrome_path().as_deref(), Platform::detect())
}
/// [`window_unavailable_reason`] for this process's environment.
@@ -703,18 +705,23 @@ mod tests {
// local Chrome runs without a window, so only a window needs a display
let chrome = Path::new("/usr/bin/chromium");
- assert_eq!(local_unavailable_reason(Some(chrome)), None);
- assert!(local_unavailable_reason(None)
+ assert_eq!(local_unavailable_reason(Some(chrome), Platform::Linux), None);
+ assert!(local_unavailable_reason(None, Platform::Linux)
.unwrap()
.contains(CHROME_PATH_ENV));
+ assert!(local_unavailable_reason(None, Platform::Mac).unwrap().contains("brew install --cask google-chrome"));
+ assert!(local_unavailable_reason(None, Platform::Docker).unwrap().contains("compose browser service"));
assert_eq!(window_unavailable_reason(true), None);
assert!(window_unavailable_reason(false).unwrap().contains("display"));
- assert_eq!(vm_unavailable_reason(true, false), None);
- assert_eq!(vm_unavailable_reason(false, true), None);
- assert!(vm_unavailable_reason(false, false)
- .unwrap()
- .contains("Docker"));
+ assert_eq!(vm_unavailable_reason(true, false, Platform::Linux), None);
+ assert_eq!(vm_unavailable_reason(false, true, Platform::Docker), None);
+ // each platform gets its own advice: no "Docker Desktop on a Mac" on a Linux server
+ let linux = vm_unavailable_reason(false, false, Platform::Linux).unwrap();
+ assert!(linux.contains("get.docker.com") && !linux.contains("Docker Desktop"), "{linux}");
+ assert!(vm_unavailable_reason(false, false, Platform::Mac).unwrap().contains("Docker Desktop"));
+ let docker = vm_unavailable_reason(false, false, Platform::Docker).unwrap();
+ assert!(docker.contains("KWNT_BROWSER_CDP_URL") && docker.contains("docker compose up -d browser"), "{docker}");
}
#[test]
diff --git a/src/server/browser_stream.rs b/src/server/browser_stream.rs
index b2951866..7eedfc69 100644
--- a/src/server/browser_stream.rs
+++ b/src/server/browser_stream.rs
@@ -6,7 +6,7 @@ use serde::Deserialize;
use serde_json::{json, Value};
use std::time::Duration;
use tokio::{sync::OwnedRwLockWriteGuard, time::{timeout, Instant}};
-use tokio_tungstenite::{connect_async, tungstenite::Message as CdpMessage};
+use tokio_tungstenite::tungstenite::Message as CdpMessage;
#[derive(Debug, Deserialize)]
#[serde(tag = "action", rename_all = "snake_case")]
@@ -81,7 +81,7 @@ async fn serve(mut socket: WebSocket, state: AppState, id: String) -> Result<(),
return Ok(());
}
};
- let (mut cdp, _) = connect_async(ctrl.get_ws_url().await?).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
+ let mut cdp = crate::sandbox::browser::connect_cdp(&ctrl.get_ws_url().await?).await?;
let mut command_id = 1u64;
for method in ["Page.enable", "Page.startScreencast"] {
cdp.send(CdpMessage::Text(json!({"id":command_id,"method":method,"params": if method == "Page.startScreencast" {json!({"format":"jpeg","quality":65,"maxWidth":1280,"maxHeight":800,"everyNthFrame":1})} else {json!({})}}).to_string())).await.map_err(|e| BrowserError::Ws(e.to_string()))?;
diff --git a/src/server/computer.rs b/src/server/computer.rs
index b5eed26d..ed263bcd 100644
--- a/src/server/computer.rs
+++ b/src/server/computer.rs
@@ -46,6 +46,7 @@ async fn view(state: &AppState) -> Value {
let vm = computer::vm_unavailable_reason(
state.sandbox_manager.is_docker_available().await,
state.browser_service.has_endpoint(),
+ crate::doctor::Platform::detect(),
);
let window = computer::window_reason();
json!({