ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: drive the agtx via a phone (#152)
Fynn Fluegged307c4c182df
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b4e8ec0..50d7a4b 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -46,8 +46,18 @@ jobs:# - name: Clippy# run: cargo clippy --all-targets --all-features -- -D warnings- - name: Build+ # Both builds, because the two differ: `serve` is optional and the+ # default build must keep compiling without it.+ - name: Build (default)run: cargo build --verbose+ - name: Build (serve)+ run: cargo build --verbose --features serve++ # With `serve`, or the web suite is skipped entirely β its tests are+ # behind the same feature as the code they cover.- name: Run tests- run: cargo test --verbose --features test-mocks+ run: cargo test --verbose --features "serve test-mocks"++ - name: Run web client tests+ run: node --test tests/web_client_tests.mjsdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 858c8cf..fcf5bd2 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -61,7 +61,8 @@ jobs:if [[ "${{ matrix.target }}" == "aarch64-unknown-linux-gnu" ]]; thenexport CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gccfi- cargo build --release --target ${{ matrix.target }}+ # `--features serve` is what puts the mobile board in the shipped binary.+ cargo build --release --features serve --target ${{ matrix.target }}- name: Packagerun: |diff --git a/CLAUDE.md b/CLAUDE.mdindex 0d209ef..46d2dd2 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -26,6 +26,11 @@ cargo build --release# Run the MCP server (global mode, or project-scoped with a path)./target/release/agtx mcp-serve [path]+# Serve the board to a phone (feature = "serve"; loopback needs no pairing)+./target/release/agtx serve [path] [--host 0.0.0.0] [--port 8787] [--tunnel private|public]+./target/release/agtx serve --devices # paired devices+./target/release/agtx serve --revoke <id> # or --revoke-all+# Record an agent lifecycle event (invoked by agent hooks, not by hand)./target/release/agtx hook --env <agent> [--event <Name>] < payload.json@@ -54,6 +59,7 @@ src/β βββ help.rs # The `?` overlay's binding table (declared, not open-coded)β βββ help_tests.rs # Unit tests for help.rs (included via #[path])β βββ input.rs # InputMode enum for UI states+β βββ serve_control.rs # The `W` overlay: run `agtx serve` as a child, manage devicesβ βββ shell_popup.rs # Shell popup state, rendering, content trimmingβ βββ text_input.rs # Shared line editor: buffer + byte caret, motion, deletionβ βββ text_input_tests.rs # Unit tests for text_input.rs (included via #[path])@@ -85,9 +91,22 @@ src/β βββ trust.rs # Reads each agent's own workspace-trust store; seeds antigravity'sβ βββ trust_tests.rs # Unit tests for trust.rs (included via #[path])β βββ operations.rs # AgentOperations/CodingAgent traits (mockable)+βββ core/ # Domain logic with no terminal, HTTP or agent transport attached+β βββ actions.rs # allowed_actions + CallerKind β what a task permits, and to whom+β βββ input.rs # Getting text and keys into a pane: submit_message, composer parkingβββ mcp/β βββ mod.rs # Re-exportsβ βββ server.rs # MCP server (JSON-RPC over stdio) β global and project-scoped modes+βββ web/ # `agtx serve` β the board over HTTP (feature = "serve")+β βββ mod.rs # ServeOptions, startup, the banner and its QR+β βββ routes.rs # Router, read endpoints, the auth layer, the embedded-asset fallback+β βββ writes.rs # Actions (queued, never executed), task CRUD, /input, /api/pair+β βββ ws.rs # Live pane frames β snapshot frames, not a PTY+β βββ state.rs # ServeMode, ApiError, rate limit, conflict cache+β βββ auth.rs # Pairing codes and per-device tokens+β βββ assets.rs # The PWA, embedded with include_bytes! (no bundler)+β βββ qr.rs # Pairing QR: half-blocks for a terminal, grid for ratatui+β βββ tunnel.rs # tailscale serve / funnel / cloudflared β plan is pure, spawn is notβββ update/β βββ mod.rs # check_for_update() β the whole background checkβ βββ version.rs # Semver-lite parse/compare + the prerelease policy (pure)@@ -99,6 +118,15 @@ src/βββ mod.rs # GlobalConfig, ProjectConfig, MergedConfig, PhaseAgentsConfig,# WorktreeConfig, ThemeConfig, WorkflowPlugin, TrustStore+web/ # The mobile PWA β plain ES modules, no build step+βββ index.html # Shell; app.js is the only entry point+βββ app.js # Router, screens, action sheet, swipe, live terminal+βββ api.js # API client, credential capture, key-chip vocabulary+βββ ansi.js # SGR-to-HTML β capture-pane emits only `ESC[β¦m`, so no emulator+βββ app.css # Theme tokens tracking the TUI's palette+βββ sw.js # Offline shell, network-first (never caches /api)+βββ manifest.webmanifest, icon-{192,512}.png+skills/ # Plugin skill files β auto-discovered as /agtx:* (Claude) or @agtx:* (Codex)βββ sweep/SKILL.md # Sweep skill β push any conversation to the board (/agtx:sweep)βββ brainstorm/SKILL.md # Brainstorm skill β free-form exploration (/agtx:brainstorm)@@ -586,6 +614,60 @@ agtx tells the user when a newer release exists and replaces its own binary on rverified them since it was written, but none were ever published, so its verification had neveronce run+### Serving the Board to a Phone+`agtx serve` (feature = `serve`) is **the MCP server re-exposed over HTTP with a PWA on top** β it talks+to SQLite, tmux and git, never to `App`. `W` in the TUI runs it as a child and shows the pairing QR.++**Actions queue; they do not execute.** A tap writes to `transition_requests`, and only a running TUI+drains it β the same contract the orchestrator lives under. So every action response says `queued`,+carries `tui_connected` from the `tui_heartbeat` table, and the phone shows a banner when nothing is+draining. `docs/planning/headless-engine.md` is the plan that removes this.++**Loopback needs no credential; anything wider does.** Reaching `127.0.0.1` already means being on this+machine, where the tmux socket and the databases are readable anyway. Off-loopback β including a tunnel,+whose provider proxies into a loopback listener β requires a paired device. Reading only the bind address+is how a tunnelled server ends up open, so `ServeOptions::is_loopback` reads the tunnel too.++**Per-device tokens, hashed at rest** in `mobile_devices`, so one lost phone is revoked without cutting+off the rest. Validation is a hash lookup per request, which makes `--revoke` immediate and+cross-process.++**Serving is per-session; the pairing is not.** `W` runs `agtx serve` as a *child* of the TUI, so it+stops when agtx does and nothing ever opens a port on its own β while the paired device survives. The+two lifetimes differing is the thing users trip on: the phone reconnects silently when the board is+served again, and times out identically whether it was unpaired or simply nobody is serving. The+README says so under **Mobile**; keep it said.++**A pairing outlives the server that issued it**, by design: the device row is in the global+`index.db` and the token is in the phone's `localStorage`, so a home-screen app reconnects without a+new scan. Revocation is manual (`--revoke`, `--revoke-all`). Each device records the `session_id` of+the serve session that paired it β provenance only, and the hook for a future expiry or+forget-on-exit policy (`Database::revoke_session_devices` scopes a delete to one session, which is+what makes such a policy safe: `mobile_devices` is **global**, so a second agtx serving another+project must keep its own devices). Secrets reach the phone in the **URL fragment**, which browsers never transmit, so they+stay out of every access log; `/ws` uses `Sec-WebSocket-Protocol` instead, the one field a browser can+set on an upgrade. Auth lives in the router's middleware and not the socket handler: `WebSocketUpgrade`+is an extractor, so a handler-side check runs only *after* the upgrade is accepted.++**Two things about the PWA that look like shortcuts and are not.** There is **no bundler** β the app is+plain ES modules embedded with `include_bytes!`, so a missing file is a compile error rather than a+runtime 404, and nothing can be stale. And there is **no xterm.js**: measured against tmux 3.5a,+`capture-pane -p -e` emits only `ESC[β¦m`, no cursor motion, because it is a snapshot of an+already-rendered grid β a terminal emulator would have nothing to emulate. `web/ansi.js` builds a DOM+fragment rather than an HTML string, so agent output containing `<script>` is text.++Two traps worth knowing before touching either half:++- **`include_bytes!` guarantees a *listed* file exists, not that every file is listed.** A module left+ out of `assets.rs` 404s to the SPA shell, the ES import receives HTML, and the whole app renders+ blank. `the_asset_table_covers_the_web_directory` closes that direction.+- **ratatui does not interpret ANSI.** `qr::render` is for the CLI banner; the `W` overlay must use+ `qr::grid` and build styled spans, or it draws literal escape bytes as an unscannable QR.++**The board does not poll.** It is fetched when something happened β opened, pulled down, returned to,+or changed by an action. The live pane is the exception and keeps its socket, which runs only while a+subscriber is attached and sends only changed frames.+### Database StorageAll databases stored centrally (not in project directories), in the platform data dir (`GlobalConfig::data_dir`, via the `directories` crate):- macOS: `~/Library/Application Support/agtx/`@@ -814,6 +896,7 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)| `,` | Open the config editor || `?` | Show every binding (help overlay) || `u` | Update agtx (only bound when a newer release was found) |+| `W` | Serve the board to a phone: QR, pairing, and paired devices || `O` | Toggle orchestrator agent (experimental) || `e` | Toggle project sidebar (`h`/`Left` from the Backlog column focuses it) || `q` | Quit |diff --git a/Cargo.lock b/Cargo.lockindex d1feb21..4080b7e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -7,10 +7,13 @@ name = "agtx"version = "1.0.4"dependencies = ["anyhow",+ "axum","chrono","crossterm","directories",+ "http-body-util","mockall",+ "qrcode","ratatui","rmcp","rusqlite",@@ -22,6 +25,7 @@ dependencies = ["tokio","toml","toml_edit",+ "tower","tracing","tracing-appender","tracing-subscriber",@@ -85,12 +89,73 @@ dependencies = ["bytemuck",]+[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"+[[package]]name = "autocfg"version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"+[[package]]+name = "axum"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"+dependencies = [+ "axum-core",+ "base64",+ "bytes",+ "form_urlencoded",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "serde_core",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sha1",+ "sync_wrapper",+ "tokio",+ "tokio-tungstenite",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-core"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+ "tracing",+]+[[package]]name = "base64"version = "0.22.1"@@ -330,6 +395,12 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "data-encoding"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"+[[package]]name = "deltae"version = "0.3.2"@@ -531,6 +602,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]+[[package]]name = "fragile"version = "2.0.1"@@ -699,6 +779,86 @@ version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"+[[package]]+name = "http"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "httpdate",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "bytes",+ "http",+ "http-body",+ "hyper",+ "pin-project-lite",+ "tokio",+ "tower-service",+]+[[package]]name = "iana-time-zone"version = "0.1.65"@@ -900,6 +1060,12 @@ dependencies = ["regex-automata",]+[[package]]+name = "matchit"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"+[[package]]name = "memchr"version = "2.8.0"@@ -921,6 +1087,12 @@ dependencies = ["autocfg",]+[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]name = "minimal-lexical"version = "0.2.1"@@ -1082,6 +1254,12 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"+[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"+[[package]]name = "pest"version = "2.8.6"@@ -1152,7 +1330,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d"dependencies = ["phf_shared",- "rand",+ "rand 0.8.6",][[package]]@@ -1201,6 +1379,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"+[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]+[[package]]name = "predicates"version = "3.1.4"@@ -1236,6 +1423,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "qrcode"+version = "0.14.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"+[[package]]name = "quote"version = "1.0.44"@@ -1257,7 +1450,27 @@ version = "0.8.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"dependencies = [- "rand_core",+ "rand_core 0.6.4",+]++[[package]]+name = "rand"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"+dependencies = [+ "rand_chacha",+ "rand_core 0.9.5",+]++[[package]]+name = "rand_chacha"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"+dependencies = [+ "ppv-lite86",+ "rand_core 0.9.5",][[package]]@@ -1266,6 +1479,15 @@ version = "0.6.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+[[package]]+name = "rand_core"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"+dependencies = [+ "getrandom 0.3.4",+]+[[package]]name = "ratatui"version = "0.30.0"@@ -1595,6 +1817,17 @@ dependencies = ["zmij",]+[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]+[[package]]name = "serde_spanned"version = "0.6.9"@@ -1604,6 +1837,29 @@ dependencies = ["serde",]+[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "sha1"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]+[[package]]name = "sha2"version = "0.10.9"@@ -1744,6 +2000,12 @@ dependencies = ["unicode-ident",]+[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+[[package]]name = "tempfile"version = "3.24.0"@@ -1936,6 +2198,18 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "tokio-tungstenite"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f72a05e828585856dacd553fba484c242c46e391fb0e58917c942ee9202915c"+dependencies = [+ "futures-util",+ "log",+ "tokio",+ "tungstenite",+]+[[package]]name = "tokio-util"version = "0.7.18"@@ -1990,12 +2264,41 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"+[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"+[[package]]name = "tracing"version = "0.1.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"dependencies = [+ "log","pin-project-lite","tracing-attributes","tracing-core",@@ -2076,6 +2379,22 @@ dependencies = ["tracing-serde",]+[[package]]+name = "tungstenite"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c01152af293afb9c7c2a57e4b559c5620b421f6d133261c60dd2d0cdb38e6b8"+dependencies = [+ "bytes",+ "data-encoding",+ "http",+ "httparse",+ "log",+ "rand 0.9.5",+ "sha1",+ "thiserror 2.0.18",+]+[[package]]name = "typenum"version = "1.19.0"@@ -2491,6 +2810,26 @@ version = "0.51.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"+[[package]]+name = "zerocopy"+version = "0.8.56"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "556764e583adb45a9f8d413c2a147fa7e8d821e48e12b14fd560b607998b75eb"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.56"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2ab42fc20575779bd240faa45f94a74256f755c0fa9e89f0ede20d91d0cdfc1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "zmij"version = "1.0.19"diff --git a/Cargo.toml b/Cargo.tomlindex 0ec2d67..aa58ff6 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -46,9 +46,21 @@ tracing-appender = "0.2"# MCP serverrmcp = { version = "1.7", features = ["server", "macros", "transport-io"] }+# Web server for `agtx serve` (feature = "serve"). Optional not for binary size+# β `tokio` above is unconditional with `features = ["full"]`, so the runtime is+# paid for either way β but for blast radius: this serves a board that can start+# agents running with `--dangerously-skip-permissions`, and an opt-in compile is+# one more step in front of that.+axum = { version = "0.8", features = ["ws"], optional = true }+# The pairing QR. `default-features = false` drops `image` and `svg`, which pull+# in an image codec stack for output this never produces β the only renderer+# here writes half-blocks to a terminal.+qrcode = { version = "0.14", default-features = false, optional = true }+[features]default = []test-mocks = ["dep:mockall"]+serve = ["dep:axum", "dep:qrcode"]# Dev tooling for the smoke tests, not part of the shipped binary. Declared with# an explicit path so it can live next to its only consumer in tests/smoke/@@ -63,6 +75,10 @@ path = "tests/smoke/agent_matrix.rs"[dev-dependencies]tempfile = "3"mockall = "0.13"+# `ServiceExt::oneshot` β drives a `Router` in-process, so the route tests need+# no listener, no port and no network.+tower = { version = "0.5", features = ["util"] }+http-body-util = "0.1"[dependencies.mockall]version = "0.13"diff --git a/README.md b/README.mdindex 5e79e0a..ed6c270 100644--- a/README.md+++ b/README.md@@ -7,10 +7,8 @@<div align="left">->-> **Let different coding agents collaborate** autonomously on the same task with automatic session switching and context awareness.-> **A blackboard for coding agents** - One shared board. A fleet of agents. Add tasks, delegate to multiple coding agents running in parallel.-> **Capture ideas without leaving your session** β `/agtx:brainstorm` to explore freely, `/agtx:sweep` to push the conversation to the board as tasks in one step.+> **A blackboard for coding agents** - One shared board. A fleet of agents. Add tasks, delegate to multiple coding agents running in parallel and let+> **different models collaborate** on the same task with automatic session switching and context awareness, e.g. Codex planning, Claude implementing, Grok review.</div>@@ -25,6 +23,7 @@<a href="#quick-start">Quick Start</a> β’<a href="#features">Features</a> β’<a href="#usage">Usage</a> β’+ <a href="#mobile">Mobile</a> β’<a href="#brainstorm--sweep-skills">Skills</a> β’<a href="#mcp-server">MCP Server</a> β’<a href="#plugins">Plugins</a> β’@@ -58,9 +57,10 @@<a href="https://github.com/google-gemini/gemini-cli"><kbd><img src="docs/logos/gemini.svg" width="18" valign="middle" /> Gemini CLI</kbd></a><a href="https://github.com/github/copilot-cli"><kbd><img src="docs/logos/copilot-dark.svg" width="18" valign="middle" /> Copilot</kbd></a><a href="https://github.com/earendil-works/pi"><kbd><img src="docs/logos/pi-dark.svg" width="18" valign="middle" /> pi</kbd></a>-- **Multi-agent task lifecycle**: Configure different agents per workflow phase β e.g. Gemini for research, Claude for implementation, Codex for review β with automatic agent switching.-- **Multi-project dashboard**: Manage agent sessions across all projects via a single TUI.-- **Parallel execution**: Every task gets its own git worktree and tmux window β run as many agents as needed, simultaneously.+- **Parallel Multi-agent task lifecycle**: Configure different agents per workflow phase β e.g. Grok for research, Claude for implementation, Codex for review β with automatic agent switching and context handover.+- **Multi-project Kanban board**: Manage agent sessions across all projects via a single TUI without leaving your terminal.+- **Vim-native Keybindings**: Control the board and agent sessions with your Vim-powered muscle memory.+- **Mobile support**: Press `W` and scan the QR for an installable web app with the board, task details, diffs and the agent's live terminal β including a keyboard, so you can answer a permission prompt without going back to your desk. Over your wifi, or from anywhere via your tailnet. See <a href="#mobile">Mobile</a>.- **Orchestrator agent (experimental)**: A dedicated agent that autonomously manages your kanban board via MCP β delegates to coding agents, advances phases, checks for merge conflicts.- **Brainstorm & Sweep skills**: Capture ideas and push them to the board from any coding agent session β `/agtx:brainstorm` to explore freely, `/agtx:sweep` to decompose and create tasks with one confirmation step.- **Spec-driven plugins**: Plug in [GSD](https://github.com/fynnfluegge/get-shit-done-cc), [Spec-kit](https://github.com/github/spec-kit), [OpenSpec](https://github.com/Fission-AI/OpenSpec), [BMAD](https://github.com/bmad-code-org/BMAD-METHOD), [Superpowers](https://github.com/obra/superpowers) and more β fully customizable. Ddefine your own workflow via a single TOML file. See <a href="#plugins">Plugins</a> how to create a plugin.@@ -70,76 +70,25 @@>> Choose the **`void` plugin** and enjoy agtx as a batteries included multi-agent session-manager.-> [!TIP]-> Check out the [Contributing](#contributing) section or have a look at [`good first issues`](https://github.com/fynnfluegge/agtx/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) to get involved and become a contributor βοΈ--## Why agtx? - The blackboard model--Most AI coding tools give you one agent, one task, one terminal. agtx is built on a different and much-older idea: the [**blackboard system**](https://en.wikipedia.org/wiki/Blackboard_system).--> A blackboard system is an approach where a common knowledge base β the *blackboard* β is iteratively-> updated by a diverse group of specialist *knowledge sources*, starting from a problem specification-> and ending with a solution. Each specialist writes a partial solution to the blackboard when the-> state on the board matches what it can contribute.->-> β after [*Blackboard system*](https://en.wikipedia.org/wiki/Blackboard_system), Wikipedia (CC BY-SA)--That architecture was designed for problems that are too ill-defined for a single solver and too-interdependent to split cleanly up front. **Shipping software with coding agents is exactly that-problem**, so agtx implements the model directly:--The dependency graph gives the blackboard its structure. Tasks references they build on,-forming a graph of partial solutions - agtx holds downstream tasks until their dependencies reach-Review or Done, then carries the relevant diffs and artifacts into the dependent task's context.--```- βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- β CONTROL orchestrator agent Β· phase gates Β· dep graph β- βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ- β- βββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββ- β THE BLACKBOARD β- β backlog β planning β running β review β done β- β dependency graph Β· specs Β· plans Β· diffs Β· reviews β- ββββββ²ββββββββββ²ββββββββββ²ββββββββββ²ββββββββββ²ββββββββββ²βββββ- β β β β β β- ββββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ- β Claude β β Codex β βGemini β βCursor β β Grok β β ... β- ββββββββββ βββββββββ βββββββββ βββββββββ βββββββββ βββββββββ- KNOWLEDGE SOURCES β one git worktree + tmux window each-```--| Blackboard model | In agtx |-|------------------|---------|-| **The blackboard** β a shared repository of the problem, partial solutions and contributed information | The kanban board, its dependency graph, and everything the phases leave behind: specs, plans, diffs, reviews, and phase artifacts. Every agent reads from and writes to the same board |-| **Knowledge sources** β independent specialists that never talk to each other, only to the board | Eight coding agent CLIs, each running in its **own git worktree and tmux window**. No agent can see another's context β they exchange only what lands on the board |-| **Control shell** β decides opportunistically which specialist runs next | Plugin phase gates determine when a task can advance; the dependency graph determines which tasks are ready to start; and the [orchestrator agent](#orchestrator-agent-experimental) coordinates the board over MCP |-## Quick Start```bash# Installcurl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh | bash--# Run in any git repository-cd your-project && agtx``````bash-# Dashboard mode β manage all projects-agtx -g--# Orchestrator mode β let an AI manage the board for you-agtx --experimental+# Run in any git repository+cd your-project && agtx```> [!NOTE]> Add `.agtx/` to your project's `.gitignore` to avoid committing worktrees and local task data.```bash-# Install from source-cargo build --release+# Install from source β `serve` adds the mobile board (`W`), and the+# published binaries are built with it+cargo build --release --features servecp target/release/agtx ~/.local/bin/```@@ -155,18 +104,6 @@ agtx update --check # report only; exits 1 when an update is availableagtx --version```-The running agtx keeps the old binary until you restart it; open tmux sessions-and their agents are untouched.--To never check, set `update_check = false` in `~/.config/agtx/config.toml`, or-export `AGTX_NO_UPDATE_CHECK=1` for a single run (CI, containers). To pin or roll-back to a specific release, re-run the installer with `AGTX_VERSION`:--```bash-curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh \- | AGTX_VERSION=v0.2.6 bash-```-### Requirements- **tmux** β agent sessions run in a dedicated tmux server@@ -195,6 +132,7 @@ curl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh \| `,` | Open the config editor || `?` | Show every keyboard shortcut || `u` | Update agtx (only shown when a new release is available) |+| `W` | Serve the board to a phone (QR pairing, device list) || `O` | Toggle orchestrator agent (`--experimental`) || `e` | Toggle project sidebar || `q` | Quit |@@ -239,6 +177,164 @@ Each task runs in its own tmux window with a dedicated coding agent. The session</details>+## Why agtx? - The blackboard model++Most AI coding tools give you one agent, one task, one terminal. agtx is built on a different and much+older idea: the [**blackboard system**](https://en.wikipedia.org/wiki/Blackboard_system).++> A blackboard system is an approach where a common knowledge base β the *blackboard* β is iteratively+> updated by a diverse group of specialist *knowledge sources*, starting from a problem specification+> and ending with a solution. Each specialist writes a partial solution to the blackboard when the+> state on the board matches what it can contribute.+>+> β after [*Blackboard system*](https://en.wikipedia.org/wiki/Blackboard_system), Wikipedia (CC BY-SA)++That architecture was designed for problems that are too ill-defined for a single solver and too+interdependent to split cleanly up front. **Shipping software with coding agents is exactly that+problem**, so agtx implements the model directly:++The dependency graph gives the blackboard its structure. Tasks references they build on,+forming a graph of partial solutions - agtx holds downstream tasks until their dependencies reach+Review or Done, then carries the relevant diffs and artifacts into the dependent task's context.++```+ βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ β CONTROL orchestrator agent Β· phase gates Β· dep graph β+ βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββ+ β+ βββββββββββββββββββββββββββββββΌββββββββββββββββββββββββββββββ+ β THE BLACKBOARD β+ β backlog β planning β running β review β done β+ β dependency graph Β· specs Β· plans Β· diffs Β· reviews β+ ββββββ²ββββββββββ²ββββββββββ²ββββββββββ²ββββββββββ²ββββββββββ²βββββ+ β β β β β β+ ββββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ βββββ΄ββββ+ β Claude β β Codex β βGemini β βCursor β β Grok β β ... β+ ββββββββββ βββββββββ βββββββββ βββββββββ βββββββββ βββββββββ+ KNOWLEDGE SOURCES β one git worktree + tmux window each+```++| Blackboard model | In agtx |+|------------------|---------|+| **The blackboard** β a shared repository of the problem, partial solutions and contributed information | The kanban board, its dependency graph, and everything the phases leave behind: specs, plans, diffs, reviews, and phase artifacts. Every agent reads from and writes to the same board |+| **Knowledge sources** β independent specialists that never talk to each other, only to the board | Eight coding agent CLIs, each running in its **own git worktree and tmux window**. No agent can see another's context β they exchange only what lands on the board |+| **Control shell** β decides opportunistically which specialist runs next | Plugin phase gates determine when a task can advance; the dependency graph determines which tasks are ready to start; and the [orchestrator agent](#orchestrator-agent-experimental) coordinates the board over MCP |++## Mobile++[//]: <> (screenshot: the board on a phone β take it on a real device, then drag it into a GitHub comment and paste the attachment URL here, as with the TUI shot above)++Press `W` on the board to serve it to your phone. agtx prints a QR code; scanning+it pairs the device and opens an installable web app with the board, task+details, git diffs, and the agent's live terminal β including a keyboard, so you+can answer a permission prompt from wherever you are.++```bash+# Or start it yourself, without the TUI+agtx serve # this machine only+agtx serve --tunnel # your tailnet β anywhere, your devices only+agtx serve --devices # list paired devices+agtx serve --revoke <id> # revoke one; --revoke-all for the lot+```++Two keys in the overlay, each a whole action: `s` serves to the local network,+`t` serves via your tailnet.++> [!IMPORTANT]+> **agtx never opens a port on its own.** Serving lasts for as long as that agtx+> runs: quit it and the server stops, so the next time you want the board on+> your phone you press `W` then `s`/`t` again. Pairing does not change this β it+> is a credential, not a trigger, and a paired phone whose Mac is not serving+> just times out.++> [!NOTE]+> This needs a binary built with `--features serve`. The released ones are; a+> local `cargo build --release` without it reports "this build has no web+> server" under both options.++<details>+<summary><strong>Setup β on your wifi</strong></summary>++Works in about thirty seconds, and needs nothing installed.++1. Run `agtx` in a project and press `W`+2. Press `s`+3. Point your phone's camera at the QR code β the phone must be on the same wifi+4. In Safari or Chrome: **Share β Add to Home Screen**++That last step is what turns it into an app: its own icon, no address bar, and+the pairing remembered so you never scan again β but you still press `W` then+`s` to start serving each time you run agtx.++The URL here is a private address like `192.168.1.20`, which exists only on your+network. **It will not work on mobile data** β if you leave the house, the app+will sit there timing out. That is what the tailnet option below is for.++</details>++<details>+<summary><strong>Setup β from anywhere, via Tailscale</strong></summary>++A few minutes once, then it is the same two taps forever. Your board becomes+reachable from your phone on any network, while staying invisible to everyone+else.++**One-time, on your Mac and your phone:**++1. Install [Tailscale](https://tailscale.com/download) on both+2. Sign both into the **same** account β they need to be on one tailnet+3. Enable Serve for your tailnet. It is off by default and is a separate switch+ from installing Tailscale β the step most people miss. The simplest way is to+ just press `t` in agtx once: Tailscale refuses with a one-time link that+ enables it for this machine, and agtx prints that link rather than swallowing+ it. Follow it, then press `t` again.++**Once more, to install the app:**++1. Run `agtx`, press `W`, press `t`+2. Scan the QR, and **Share β Add to Home Screen**++**Then, every time you want the board on your phone:** run `agtx`, press `W`,+press `t`. That is all β the pairing is remembered, so there is no QR to scan;+what you are starting is the server.++Now the icon on your home screen works on 5G, on hotel wifi, anywhere β the+address is an HTTPS name on your tailnet, and only devices signed into it can+resolve or reach it.++</details>++<details>+<summary><strong>When it does not work</strong></summary>++| What you see | What it means |+|---|---|+| `Unavailable: install Tailscale and sign this machine in` | `t` needs Tailscale on *this* machine. Install it, or use `s` for wifi. |+| `Unavailable: Tailscale is installed but not signed in` | Run `tailscale up`. |+| `could not start the tunnel: β¦ Serve is not enabled on your tailnet` | The one-time switch above. agtx relays Tailscale's own message, which carries the URL that enables it. |+| Scanned fine, then the app times out | You pressed `s` (wifi) and the phone is on mobile data. Press `s` again to stop, then `t`. |+| The tailnet URL loads on the Mac but not the phone | The phone is not on the tailnet. Open the Tailscale app there and connect. |+| `This device is not authorised` | The pairing code expired β it lasts two minutes and is single-use. Press `s` or `t` again for a fresh QR. |+| The app worked yesterday, today it just times out | Nothing is serving. agtx does not start the server on its own β run it, press `W`, then `s`/`t`. The pairing is still good; the port is not open. |+| `No agtx running` on the board | Expected with no TUI open. Reading works; actions queue until one is. |++</details>++> [!IMPORTANT]+> Anything that can reach this server can read every task, every diff and every+> agent's screen, and can type into a running agent β which is arbitrary code+> execution on your machine. So: loopback needs no credential because reaching it+> already means being on the machine, and **everything wider requires a paired+> device**. Tokens are per-device and stored hashed, so a lost phone is revoked+> without disturbing the rest. `--tunnel public` publishes to the open internet+> and is deliberately not offered behind a keypress.++**Actions queue; they do not execute on their own.** Moving a task writes a+request that only a running `agtx` picks up, so with no TUI open your taps are+accepted and then wait β the board says so rather than pretending. Creating,+editing and deleting Backlog tasks take effect immediately, since they need no+agent. Starting the server with `W` keeps the two together by construction.+## Brainstorm & Sweep SkillsTwo companion skills for capturing ideas in any coding agent session and turning them into tasks in the agtx board.diff --git a/src/core/actions.rs b/src/core/actions.rsnew file mode 100644index 0000000..6330647--- /dev/null+++ b/src/core/actions.rs@@ -0,0 +1,157 @@+//! What a task is allowed to do next, and who is asking.+//!+//! Shared by the MCP server and the web API so the phone and the orchestrator+//! cannot drift apart on what a task permits.++use crate::db::{Task, TaskStatus};++/// Who is asking what a task may do.+///+/// The answer genuinely differs, and collapsing the two is a bug in both+/// directions. The orchestrator does not manage Backlog β a human triages it β+/// so offering it `research` would have it starting work the user has not+/// looked at. A person opening the board has the opposite need: Backlog triage+/// is most of what they came to do, and a Backlog card with no actions is a+/// dead end.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CallerKind {+ /// The orchestrator agent, driving the board unattended.+ Orchestrator,+ /// A person, through a UI.+ Human,+}++/// Every `move_task` verb, in one place so the MCP tool and the web API cannot+/// disagree about what a valid action is even called.+pub const ACTIONS: &[&str] = &[+ "research",+ "move_forward",+ "move_to_planning",+ "move_to_running",+ "move_to_review",+ "move_to_done",+ "resume",+ "escalate_to_user",+];++/// The longest a task title may be. Mirrors the wizard's own cap, so a task+/// created from a phone cannot be one the desktop refuses to edit.+pub const MAX_TASK_TITLE_CHARS: usize = 120;++/// The actions `task` currently permits, named as the MCP `move_task` verbs.+///+/// `deps_satisfied` comes from [`crate::db::Database::deps_satisfied`]: a task+/// whose referenced tasks are not yet in Review or Done cannot leave Backlog.+pub fn allowed_actions(task: &Task, deps_satisfied: bool, caller: CallerKind) -> Vec<String> {+ let mut actions: Vec<String> = Vec::new();++ match task.status {+ TaskStatus::Backlog => {+ // The orchestrator is a coordinator, not a triager: it moves work+ // that a person has already decided to start. Everything a human+ // can do from Backlog is what the board's `R`, `m` and `M` keys do.+ if caller == CallerKind::Human {+ actions.push("research".to_string());+ actions.push("move_to_planning".to_string());+ actions.push("move_to_running".to_string());+ }+ }+ TaskStatus::Planning | TaskStatus::Running => {+ actions.push("move_forward".to_string());+ // `escalate_to_user` means "stop and ask the person". Offering it to+ // the person is incoherent β they are already looking at the task β+ // so it belongs to the orchestrator alone.+ if caller == CallerKind::Orchestrator {+ actions.push("escalate_to_user".to_string());+ }+ }+ TaskStatus::Review => {+ actions.push("move_to_done".to_string());+ actions.push("resume".to_string());+ }+ TaskStatus::Done => {}+ }++ // Block forward transitions out of Backlog when dependencies are not+ // satisfied. Reachable only for `Human`, since the orchestrator is offered+ // nothing from Backlog to retain β but it belongs here rather than inside+ // the arm above, because the rule is about the transition, not the caller.+ if !deps_satisfied && task.status == TaskStatus::Backlog {+ actions.retain(|a| {+ !matches!(+ a.as_str(),+ "move_forward" | "move_to_planning" | "move_to_running"+ )+ });+ }++ actions+}++/// Why an action was refused.+///+/// The two cases are different kinds of wrong and a caller should treat them+/// differently: an unknown verb is a malformed request that will never work,+/// while a verb the task does not currently permit may succeed once the board+/// moves. Collapsing them tells a client to give up on something it should+/// retry, or to retry something it should fix.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ActionRefusal {+ /// Not a verb agtx knows.+ UnknownAction(String),+ /// A real verb, not available in this task's current state.+ NotPermitted(String),+}++impl ActionRefusal {+ pub fn message(&self) -> &str {+ match self {+ ActionRefusal::UnknownAction(m) | ActionRefusal::NotPermitted(m) => m,+ }+ }+}++/// Whether `caller` may ask for `action` on `task` right now.+pub fn validate_action(+ task: &Task,+ deps_satisfied: bool,+ caller: CallerKind,+ action: &str,+) -> Result<(), ActionRefusal> {+ if !ACTIONS.contains(&action) {+ return Err(ActionRefusal::UnknownAction(format!(+ "unknown action {action:?}; valid actions are {}",+ ACTIONS.join(", ")+ )));+ }++ let allowed = allowed_actions(task, deps_satisfied, caller);+ if allowed.iter().any(|a| a == action) {+ return Ok(());+ }++ // Separate "not yet" from "not ever": a dependency clears on its own, and+ // telling someone their tap was invalid when it was merely early sends them+ // looking for a bug in the wrong place.+ if !deps_satisfied+ && task.status == TaskStatus::Backlog+ && matches!(+ action,+ "move_forward" | "move_to_planning" | "move_to_running"+ )+ {+ return Err(ActionRefusal::NotPermitted(format!(+ "{action} is blocked: this task's dependencies are not all in Review or Done yet"+ )));+ }++ Err(ActionRefusal::NotPermitted(format!(+ "{action} is not available for a task in {}{}",+ task.status.as_str(),+ if allowed.is_empty() {+ String::new()+ } else {+ format!("; try one of {}", allowed.join(", "))+ }+ )))+}diff --git a/src/core/input.rs b/src/core/input.rsnew file mode 100644index 0000000..96d586e--- /dev/null+++ b/src/core/input.rs@@ -0,0 +1,238 @@+//! Getting text and keystrokes into a running agent's pane.+//!+//! Shared by the TUI's phase delivery and the web API's `/input`, because the+//! hard-won part is not the sending β it is knowing that an agent's composer+//! may swallow the first Enter, and that a bare `send-keys` resolves anything+//! matching a tmux key name *as that key*. A second implementation of this+//! would rediscover both the slow way.+//!+//! Nothing here decides *what* to send; that belongs to the caller.++use std::sync::Arc;++use crate::tmux::TmuxOperations;++/// Attempts and per-attempt budget for [`submit_message`].+///+/// Smaller than the delivery budget on purpose: by the time this runs the text is+/// known to be in the composer, so this is only absorbing a composer that is still+/// mid-render, not a session that never attached its stdin.+pub const SUBMIT_ATTEMPTS: u32 = 3;++pub const SUBMIT_CONFIRM_POLLS: u32 = 5; // x 200ms = 1s++/// Longest prefix of a message used to confirm it landed on a pane that never+/// went quiet. Short on purpose: a composer wraps and re-indents what it echoes,+/// so a long needle straddles a line break and reads as absent.+pub const DELIVERY_NEEDLE_CHARS: usize = 16;++/// Whitespace-collapsed prefix of `text`, or `None` when there is nothing+/// distinctive enough to look for.+pub fn delivery_needle(text: &str) -> Option<String> {+ let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");+ let needle: String = flat.chars().take(DELIVERY_NEEDLE_CHARS).collect();+ (needle.chars().count() >= 4).then_some(needle)+}++/// Whether `needle` is visible in `pane`, comparing both whitespace-collapsed so+/// a wrap or re-indent in the composer does not hide it.+pub fn pane_shows(pane: &str, needle: &str) -> bool {+ let flat: String = pane.split_whitespace().collect::<Vec<_>>().join(" ");+ flat.contains(needle)+}++/// Lines at the bottom of a pane treated as the composer.+///+/// Sized from the worst real layout, not from the composer alone: while the+/// command picker is open the agent draws its suggestions *below* the composer,+/// and cursor's footer wraps the worktree path over three more lines. That puts+/// the text being submitted eight or more lines off the bottom β a snugger+/// window reads it as already gone and stops pressing Enter after one.+///+/// The cost of erring wide is one extra Enter into a composer that already+/// submitted, which is inert; the cost of erring narrow is a command parked+/// forever.+pub const COMPOSER_TAIL_LINES: usize = 14;++/// Whether the message is still sitting in the composer rather than submitted.+///+/// Only the bottom of the pane is examined: after a submit the text moves up into+/// the scrollback, and finding it *there* is proof it went, not that it stayed.+pub fn composer_holds(pane: &str, needle: &str) -> bool {+ // Trailing blanks first. `capture-pane -p` emits one line per pane *row*, not+ // per rendered line β verified against tmux 3.5a: a 20-row pane holding one+ // word comes back as 20 lines, 19 of them empty. Anchoring the window to the+ // raw end would put it entirely inside that padding whenever the agent's+ // output has not yet filled the pane, find nothing, and stop pressing Enter+ // after one β the very park this exists to catch.+ let mut lines: Vec<&str> = pane.lines().collect();+ while lines.last().is_some_and(|l| l.trim().is_empty()) {+ lines.pop();+ }+ let start = lines.len().saturating_sub(COMPOSER_TAIL_LINES);+ pane_shows(&lines[start..].join("\n"), needle)+}++/// Press Enter until the message actually leaves the composer.+///+/// The check is "the text is gone from the composer", not "the pane changed".+/// A repaint is not a submit: a **bare skill command** β one with no prompt after+/// it, which is what a phase whose command carries no `{task}`/`{task_id}` sends β+/// exactly matches a skill name, so the composer's command picker opens *on the+/// paste*. Enter is then consumed by the picker ("Press enter to insert"), which+/// inserts the command and repaints. The old change-detector read that repaint as+/// success and returned, leaving the command parked in the composer forever.+///+/// Measured against codex-cli 0.144.5 and cursor-agent 2026.08.25: both open the+/// picker on a pasted bare command, both need the second Enter, and both run the+/// skill once it arrives.+///+/// Falls back to the change-detector when the text is too short to track, and is+/// bounded either way β an agent that never submits costs `SUBMIT_ATTEMPTS`+/// keypresses, not an unbounded stream.+///+/// Known cost: agents echo the submitted message into the transcript just above+/// the composer, so a *successful* submit can leave the needle inside the window+/// and spend the remaining attempts. Those Enters land in an empty composer,+/// which is inert β except against a dialog that renders mid-submit, where a bare+/// Enter picks the highlighted option. `answer_session_dialogs` is what answers+/// those, and it runs on the refresh loop rather than here.+pub fn submit_message(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, text: &str) {+ let needle = delivery_needle(text);+ for _ in 0..SUBMIT_ATTEMPTS {+ let before = tmux_ops.capture_pane(target).unwrap_or_default();+ let _ = tmux_ops.send_key(target, "Enter");+ for _ in 0..SUBMIT_CONFIRM_POLLS {+ std::thread::sleep(std::time::Duration::from_millis(200));+ let Ok(now) = tmux_ops.capture_pane(target) else {+ continue;+ };+ match needle.as_deref() {+ Some(n) if !composer_holds(&now, n) => return,+ Some(_) => {}+ // Nothing distinctive enough to look for; the pane moving is all+ // there is to go on.+ None if now != before => return,+ None => {}+ }+ }+ }+}++// ββ user input ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// A keystroke a person asked for, as opposed to text they typed.+///+/// The distinction is not cosmetic. `send-keys` without `-l` resolves an+/// argument matching a key name *as that key*: a message of `"Space"` arrives+/// as `0x20` and a leading `;` separates tmux commands. So text must go out+/// literally and keys must not β which is why the wire format is+/// `{text?, key?}` and never one field a server has to guess about.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum PaneKey {+ Enter,+ Escape,+ CtrlC,+ Up,+ Down,+ Tab,+ /// A single character sent as a key rather than as text β the digits and+ /// letters an agent's dialogs ask for (`1`, `2`, `y`, `n`).+ Char(char),+}++impl PaneKey {+ /// Parse the name a client may send. Deliberately a closed set: forwarding+ /// arbitrary key names would let a request send `C-d` (an EOF that ends the+ /// session) or `C-u` (which kills the composer line).+ pub fn parse(name: &str) -> Option<Self> {+ Some(match name {+ "Enter" => PaneKey::Enter,+ "Escape" | "Esc" => PaneKey::Escape,+ "C-c" | "CtrlC" => PaneKey::CtrlC,+ "Up" => PaneKey::Up,+ "Down" => PaneKey::Down,+ "Tab" => PaneKey::Tab,+ other => {+ let mut chars = other.chars();+ match (chars.next(), chars.next()) {+ (Some(c), None) if c.is_ascii_alphanumeric() => PaneKey::Char(c),+ _ => return None,+ }+ }+ })+ }++ /// The tmux key name to send.+ pub fn tmux_name(&self) -> String {+ match self {+ PaneKey::Enter => "Enter".to_string(),+ PaneKey::Escape => "Escape".to_string(),+ PaneKey::CtrlC => "C-c".to_string(),+ PaneKey::Up => "Up".to_string(),+ PaneKey::Down => "Down".to_string(),+ PaneKey::Tab => "Tab".to_string(),+ PaneKey::Char(c) => c.to_string(),+ }+ }++ /// Whether this is a bare character, which must go out with `-l` so tmux+ /// does not resolve it as a key name.+ pub fn is_literal_char(&self) -> bool {+ matches!(self, PaneKey::Char(_))+ }+}++/// Send one keystroke.+///+/// A `Char` goes out literally; everything else is a real key name. Sending a+/// digit without `-l` mostly works and then does not: tmux resolves `0`..`9` as+/// themselves, but the same code path with a letter like `n` is one rename away+/// from colliding with a key name, and the literal form is correct for both.+pub fn send_user_key(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, key: PaneKey) -> bool {+ let name = key.tmux_name();+ let sent = if key.is_literal_char() {+ tmux_ops.send_text(target, &name)+ } else {+ tmux_ops.send_key(target, &name)+ };+ sent.is_ok()+}++/// Put a person's message into the agent's composer and submit it.+///+/// `paste` selects the delivery lane. An Ink-class composer (gemini, codex,+/// cursor, antigravity, pi) takes a bracketed paste as literal text but leaves+/// a combined text+Enter `send_keys` sitting unsent, so those agents must paste+/// and then submit separately. The rest take the generic path.+///+/// Submission is [`submit_message`] rather than one Enter, for the reason that+/// function documents: a composer's picker can eat the first one.+pub fn send_user_text(+ tmux_ops: &Arc<dyn TmuxOperations>,+ target: &str,+ text: &str,+ paste: bool,+) -> bool {+ if text.is_empty() {+ return false;+ }+ let delivered = if paste {+ tmux_ops.paste_text(target, text).is_ok()+ } else {+ tmux_ops.send_text(target, text).is_ok()+ };+ if !delivered {+ return false;+ }+ submit_message(tmux_ops, target, text);+ true+}++/// Whether `agent` needs the paste-then-submit lane rather than a plain send.+///+/// The same list `send_skill_and_prompt` uses for its combined-send branch;+/// see the agent table in CLAUDE.md for what was measured on each.+pub fn agent_needs_paste(agent: &str) -> bool {+ matches!(agent, "gemini" | "codex" | "cursor" | "antigravity" | "pi")+}diff --git a/src/core/mod.rs b/src/core/mod.rsnew file mode 100644index 0000000..4394ff2--- /dev/null+++ b/src/core/mod.rs@@ -0,0 +1,8 @@+//! Domain logic with no terminal, no HTTP and no agent transport attached.+//!+//! Everything here is shared by callers that drive the board from outside the+//! TUI β the MCP server today, the web API alongside it. Step 8 of the mobile+//! plan moves the transition machinery in beside it.++pub mod actions;+pub mod input;diff --git a/src/db/models.rs b/src/db/models.rsindex 5bab668..2421404 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -218,6 +218,46 @@ pub struct Notification {pub id: String,pub message: String,pub created_at: DateTime<Utc>,+ /// The task this is about. `None` only for rows written before the column+ /// existed β every producer sets it.+ pub task_id: Option<String>,+ /// What kind of event this is. Separate from `message` because a consumer+ /// outside the TUI filters on the event, not on prose: a chat bridge that+ /// wakes someone for [`TaskStuck`](NotificationKind::TaskStuck) but not for+ /// [`PhaseCompleted`](NotificationKind::PhaseCompleted) cannot express that+ /// against a formatted string.+ pub kind: Option<NotificationKind>,+}++/// Why a [`Notification`] was raised.+///+/// The serde spellings match [`as_str`](Self::as_str) so the stored value and+/// the wire value cannot drift β a consumer reading the DB directly and one+/// reading serialised output must agree on the name.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum NotificationKind {+ /// A task's phase artifact appeared β it can move forward.+ PhaseCompleted,+ /// A task has stopped making progress and may need a human.+ TaskStuck,+}++impl NotificationKind {+ pub fn as_str(&self) -> &'static str {+ match self {+ NotificationKind::PhaseCompleted => "phase_completed",+ NotificationKind::TaskStuck => "task_stuck",+ }+ }++ pub fn from_str(s: &str) -> Option<Self> {+ match s {+ "phase_completed" => Some(NotificationKind::PhaseCompleted),+ "task_stuck" => Some(NotificationKind::TaskStuck),+ _ => None,+ }+ }}impl Notification {@@ -226,11 +266,34 @@ impl Notification {id: uuid::Uuid::new_v4().to_string(),message: message.into(),created_at: Utc::now(),+ task_id: None,+ kind: None,+ }+ }++ /// The form every producer should use: a notification is always *about* a+ /// task, and a consumer outside this process needs both halves to route it.+ pub fn for_task(+ kind: NotificationKind,+ task_id: impl Into<String>,+ message: impl Into<String>,+ ) -> Self {+ Self {+ task_id: Some(task_id.into()),+ kind: Some(kind),+ ..Self::new(message)}}}-/// Phase completion status (runtime-only, not persisted to DB)+/// Phase completion status.+///+/// The TUI computes this on its own thread and reads its in-memory copy; the+/// `task_runtime` table is a *published* mirror for readers in other processes,+/// which cannot recompute it without duplicating the artifact-check and+/// pane-hash pipeline. A reader must treat a row as a snapshot and check+/// `updated_at`: with no TUI running nothing refreshes it, and a frozen+/// [`Working`](Self::Working) must not be presented as live.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PhaseStatus {/// Agent is still working, no artifact yet@@ -250,3 +313,87 @@ pub enum PhaseStatus {/// Tmux window gone (process exited)Exited,}++impl PhaseStatus {+ pub fn as_str(&self) -> &'static str {+ match self {+ PhaseStatus::Working => "working",+ PhaseStatus::Blocked => "blocked",+ PhaseStatus::Idle => "idle",+ PhaseStatus::Ready => "ready",+ PhaseStatus::Exited => "exited",+ }+ }++ pub fn from_str(s: &str) -> Option<Self> {+ match s {+ "working" => Some(PhaseStatus::Working),+ "blocked" => Some(PhaseStatus::Blocked),+ "idle" => Some(PhaseStatus::Idle),+ "ready" => Some(PhaseStatus::Ready),+ "exited" => Some(PhaseStatus::Exited),+ _ => None,+ }+ }+}++/// A published snapshot of one task's runtime state, for readers outside the+/// TUI process. Written by the session refresh; never read back by the TUI,+/// which has the live values.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TaskRuntime {+ pub task_id: String,+ pub phase_status: PhaseStatus,+ /// Hash of the last pane capture, and when it last changed. Carried so a+ /// reader can distinguish "idle because the agent is quiet" from "idle+ /// because nothing has refreshed this row".+ pub pane_hash: Option<String>,+ pub pane_changed_at: Option<DateTime<Utc>>,+ pub updated_at: DateTime<Utc>,+}++/// A phone (or anything else) paired with `agtx serve`.+///+/// One row per device rather than one shared secret, so a lost phone can be+/// revoked without re-pairing everything else β which is the whole reason this+/// exists rather than the single token it replaced.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct MobileDevice {+ pub id: String,+ /// What the user calls it. Free text from the pairing request, so it is+ /// shown but never trusted or matched on.+ pub label: String,+ /// SHA-256 of the token, hex. The token itself is shown once, at pairing,+ /// and never stored.+ pub token_hash: String,+ pub created_at: DateTime<Utc>,+ pub last_seen: Option<DateTime<Utc>>,+ /// The serve session that paired it.+ ///+ /// Provenance, not a lifetime β a pairing persists until revoked. It is+ /// what a future expiry or forget-on-exit policy would delete by, and the+ /// reason such a policy can be safe: `mobile_devices` is global, so a+ /// second agtx serving another project must keep its own devices.+ ///+ /// `None` for a row written before this column existed, and in tests.+ pub session_id: Option<String>,+}++impl MobileDevice {+ pub fn new(label: impl Into<String>, token_hash: impl Into<String>) -> Self {+ Self {+ id: uuid::Uuid::new_v4().to_string(),+ label: label.into(),+ token_hash: token_hash.into(),+ created_at: Utc::now(),+ last_seen: None,+ session_id: None,+ }+ }++ /// Bind this device to the serve session that paired it.+ pub fn in_session(mut self, session_id: impl Into<String>) -> Self {+ self.session_id = Some(session_id.into());+ self+ }+}diff --git a/src/db/schema.rs b/src/db/schema.rsindex 086e6b5..b32769d 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -2,7 +2,10 @@ use anyhow::{Context, Result};use rusqlite::{params, Connection};use std::path::Path;-use super::models::{Notification, Project, Task, TaskStatus, TransitionRequest};+use super::models::{+ MobileDevice, Notification, NotificationKind, PhaseStatus, Project, Task, TaskRuntime,+ TaskStatus, TransitionRequest,+};/// Database wrapper for SQLite operationspub struct Database {@@ -221,6 +224,18 @@ impl Database {message TEXT NOT NULL,created_at TEXT NOT NULL);++ -- Published mirror of the TUI's in-memory PhaseStatus, for readers+ -- in other processes. One row per task, rewritten by each session+ -- refresh; `updated_at` is what tells a reader whether anything is+ -- still refreshing it.+ CREATE TABLE IF NOT EXISTS task_runtime (+ task_id TEXT PRIMARY KEY,+ phase_status TEXT NOT NULL,+ pane_hash TEXT,+ pane_changed_at TEXT,+ updated_at TEXT NOT NULL+ );"#,)?;@@ -234,6 +249,15 @@ impl Database {[],);+ // Migration: notifications gain the two fields an out-of-process reader+ // needs to route them. Nullable, so rows written before this survive.+ let _ = self+ .conn+ .execute("ALTER TABLE notifications ADD COLUMN task_id TEXT", []);+ let _ = self+ .conn+ .execute("ALTER TABLE notifications ADD COLUMN kind TEXT", []);+Ok(())}@@ -265,8 +289,54 @@ impl Database {);CREATE INDEX IF NOT EXISTS idx_running_project ON running_agents(project_id);++ -- One row per project a TUI is currently open on. Its only job is+ -- to answer "is anything draining the transition queue?" β a phone+ -- can enqueue a request whenever, but nothing executes it without a+ -- running TUI, and a board that accepts taps and silently does+ -- nothing is worse than one that says so.+ CREATE TABLE IF NOT EXISTS tui_heartbeat (+ project_path TEXT PRIMARY KEY,+ beat_at TEXT NOT NULL+ );++ -- When a phone last asked for a project's board.+ --+ -- The TUI publishes `task_runtime` only while this is fresh, so a+ -- board nobody is looking at costs no writes at all. Without it the+ -- refresh wrote a transaction every couple of seconds forever, to+ -- keep a mirror current for a reader that might never exist.+ CREATE TABLE IF NOT EXISTS board_watch (+ project_path TEXT PRIMARY KEY,+ beat_at TEXT NOT NULL+ );++ -- Devices paired with `agtx serve`. One row per phone, so a lost+ -- one can be revoked without re-pairing the rest.+ --+ -- The token is stored **hashed**. This file is 0600, but a+ -- credential that grants shell-equivalent access to the machine+ -- should not be readable from a backup, a stray copy, or anything+ -- that later gets a wider mode by accident.+ CREATE TABLE IF NOT EXISTS mobile_devices (+ id TEXT PRIMARY KEY,+ label TEXT NOT NULL,+ token_hash TEXT NOT NULL UNIQUE,+ created_at TEXT NOT NULL,+ last_seen TEXT,+ session_id TEXT+ );++ CREATE INDEX IF NOT EXISTS idx_devices_hash ON mobile_devices(token_hash);"#,)?;++ // Migration: a device records the serve session that paired it.+ // Nullable, so a row written before this column existed survives.+ let _ = self+ .conn+ .execute("ALTER TABLE mobile_devices ADD COLUMN session_id TEXT", []);+Ok(())}@@ -657,8 +727,15 @@ impl Database {pub fn create_notification(&self, notif: &Notification) -> Result<()> {self.conn.execute(- "INSERT INTO notifications (id, message, created_at) VALUES (?1, ?2, ?3)",- params![notif.id, notif.message, notif.created_at.to_rfc3339()],+ "INSERT INTO notifications (id, message, created_at, task_id, kind)+ VALUES (?1, ?2, ?3, ?4, ?5)",+ params![+ notif.id,+ notif.message,+ notif.created_at.to_rfc3339(),+ notif.task_id,+ notif.kind.map(|k| k.as_str()),+ ],)?;Ok(())}@@ -679,6 +756,11 @@ impl Database {).map(|dt| dt.with_timezone(&chrono::Utc)).unwrap_or_else(|_| chrono::Utc::now()),+ task_id: row.get("task_id")?,+ kind: row+ .get::<_, Option<String>>("kind")?+ .as_deref()+ .and_then(NotificationKind::from_str),})})?.filter_map(|r| r.ok())@@ -689,9 +771,10 @@ impl Database {/// Atomic fetch-and-delete via `DELETE ... RETURNING`.pub fn consume_notifications(&self) -> Result<Vec<Notification>> {- let mut stmt = self- .conn- .prepare("DELETE FROM notifications RETURNING id, message, created_at")?;+ let mut stmt = self.conn.prepare(+ "DELETE FROM notifications+ RETURNING id, message, created_at, task_id, kind",+ )?;let mut notifs: Vec<Notification> = stmt.query_map([], |row| {@@ -703,6 +786,11 @@ impl Database {).map(|dt| dt.with_timezone(&chrono::Utc)).unwrap_or_else(|_| chrono::Utc::now()),+ task_id: row.get("task_id")?,+ kind: row+ .get::<_, Option<String>>("kind")?+ .as_deref()+ .and_then(NotificationKind::from_str),})})?.filter_map(|r| r.ok())@@ -712,4 +800,269 @@ impl Database {notifs.sort_by(|a, b| a.created_at.cmp(&b.created_at));Ok(notifs)}++ // ββ Paired devices ββββββββββββββββββββββββββββββββββββββββββββββββββ++ pub fn add_mobile_device(&self, device: &MobileDevice) -> Result<()> {+ self.conn.execute(+ "INSERT INTO mobile_devices (id, label, token_hash, created_at, last_seen, session_id)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)",+ params![+ device.id,+ device.label,+ device.token_hash,+ device.created_at.to_rfc3339(),+ device.last_seen.map(|t| t.to_rfc3339()),+ device.session_id,+ ],+ )?;+ Ok(())+ }++ /// The device holding this token hash, if any.+ ///+ /// Looked up by hash rather than compared in Rust so the secret itself+ /// never has to be read out of the database to check a request.+ pub fn mobile_device_by_hash(&self, token_hash: &str) -> Result<Option<MobileDevice>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM mobile_devices WHERE token_hash = ?1")?;+ let mut rows = stmt.query_map(params![token_hash], Self::mobile_device_from_row)?;+ Ok(rows.next().transpose()?)+ }++ pub fn list_mobile_devices(&self) -> Result<Vec<MobileDevice>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM mobile_devices ORDER BY created_at ASC")?;+ let rows = stmt+ .query_map([], Self::mobile_device_from_row)?+ .filter_map(|r| r.ok())+ .collect();+ Ok(rows)+ }++ /// Record that a device was used. Callers should throttle: this is a write,+ /// and a phone polling the board would otherwise cause one every two+ /// seconds to store a timestamp nobody reads that often.+ pub fn touch_mobile_device(&self, id: &str) -> Result<()> {+ self.conn.execute(+ "UPDATE mobile_devices SET last_seen = ?1 WHERE id = ?2",+ params![chrono::Utc::now().to_rfc3339(), id],+ )?;+ Ok(())+ }++ /// Returns whether a row was removed, so a caller can tell "revoked" from+ /// "no such device" rather than reporting success either way.+ pub fn revoke_mobile_device(&self, id: &str) -> Result<bool> {+ let rows = self+ .conn+ .execute("DELETE FROM mobile_devices WHERE id = ?1", params![id])?;+ Ok(rows > 0)+ }++ /// Drop every device paired by one serve session.+ ///+ /// Nothing calls this on shutdown β pairings persist until revoked. It is+ /// the scoped primitive an expiry or forget-on-exit policy needs, and the+ /// scoping is the point: `mobile_devices` is global, so a blanket delete+ /// would cut off a second agtx serving another project.+ ///+ /// A `NULL` session_id is never matched, so a row written before the+ /// column existed is left for the user to revoke by hand.+ pub fn revoke_session_devices(&self, session_id: &str) -> Result<usize> {+ Ok(self.conn.execute(+ "DELETE FROM mobile_devices WHERE session_id = ?1",+ params![session_id],+ )?)+ }++ /// Returns how many were removed.+ pub fn revoke_all_mobile_devices(&self) -> Result<usize> {+ Ok(self.conn.execute("DELETE FROM mobile_devices", [])?)+ }++ fn mobile_device_from_row(row: &rusqlite::Row) -> rusqlite::Result<MobileDevice> {+ let parse = |s: String| {+ chrono::DateTime::parse_from_rfc3339(&s)+ .map(|dt| dt.with_timezone(&chrono::Utc))+ .ok()+ };+ Ok(MobileDevice {+ id: row.get("id")?,+ label: row.get("label")?,+ token_hash: row.get("token_hash")?,+ created_at: row+ .get::<_, Option<String>>("created_at")?+ .and_then(parse)+ .unwrap_or_else(chrono::Utc::now),+ last_seen: row.get::<_, Option<String>>("last_seen")?.and_then(parse),+ session_id: row.get("session_id")?,+ })+ }++ // ββ TUI heartbeat βββββββββββββββββββββββββββββββββββββββββββββββββββ++ /// Record that a TUI is live on `project_path`, as of now.+ ///+ /// Called on the transition-poll cadence rather than per event-loop+ /// iteration: the loop wakes on `HOUSEKEEPING_TICK` (100 ms) and on every+ /// keystroke, so beating per iteration would be a write ten-plus times a+ /// second to answer a question whose useful resolution is seconds.+ pub fn beat_tui_heartbeat(&self, project_path: &str) -> Result<()> {+ self.conn.execute(+ "INSERT INTO tui_heartbeat (project_path, beat_at) VALUES (?1, ?2)+ ON CONFLICT(project_path) DO UPDATE SET beat_at = excluded.beat_at",+ params![project_path, chrono::Utc::now().to_rfc3339()],+ )?;+ Ok(())+ }++ /// Record that something asked for this project's board.+ ///+ /// Written by the web server on a board request. Callers should throttle:+ /// this is a write, and it answers a question whose useful resolution is+ /// minutes.+ pub fn note_board_watched(&self, project_path: &str) -> Result<()> {+ self.conn.execute(+ "INSERT INTO board_watch (project_path, beat_at) VALUES (?1, ?2)+ ON CONFLICT(project_path) DO UPDATE SET beat_at = excluded.beat_at",+ params![project_path, chrono::Utc::now().to_rfc3339()],+ )?;+ Ok(())+ }++ /// Whether a board was asked for within `stale_after`.+ ///+ /// The gate on publishing `task_runtime`. Absent and stale are the same+ /// answer β nobody is reading β so a missing row is not an error.+ pub fn board_watched_recently(+ &self,+ project_path: &str,+ stale_after: chrono::Duration,+ ) -> Result<bool> {+ let beat: Option<String> = self+ .conn+ .query_row(+ "SELECT beat_at FROM board_watch WHERE project_path = ?1",+ params![project_path],+ |row| row.get(0),+ )+ .ok();+ Ok(beat+ .and_then(|b| chrono::DateTime::parse_from_rfc3339(&b).ok())+ .is_some_and(|t| chrono::Utc::now() - t.with_timezone(&chrono::Utc) < stale_after))+ }++ /// Whether a TUI has beaten for `project_path` within `stale_after`.+ ///+ /// Absent and stale are the same answer β nothing is draining the queue β+ /// so a missing row is not an error.+ pub fn tui_is_live(&self, project_path: &str, stale_after: chrono::Duration) -> Result<bool> {+ let beat: Option<String> = self+ .conn+ .query_row(+ "SELECT beat_at FROM tui_heartbeat WHERE project_path = ?1",+ params![project_path],+ |row| row.get(0),+ )+ .ok();+ Ok(beat+ .and_then(|b| chrono::DateTime::parse_from_rfc3339(&b).ok())+ .is_some_and(|t| chrono::Utc::now() - t.with_timezone(&chrono::Utc) < stale_after))+ }++ // ββ Task runtime (published phase status) βββββββββββββββββββββββββββ++ /// Publish one refresh pass as a whole: upsert every live task's row and+ /// drop rows for tasks that no longer exist, in one transaction.+ ///+ /// The refresh writes every live task on every pass β that is what makes+ /// `updated_at` mean "last observed" rather than "last changed", which is+ /// the distinction a reader needs to tell a steadily-working task from a+ /// board nothing has refreshed since the TUI died. Batching is what keeps+ /// that affordable: one commit per pass instead of one per task.+ ///+ /// Pruning removes rows for tasks that no longer *exist*, not rows absent+ /// from this pass: the refresh tracks only active phases, so a task that+ /// reaches Done stops being published and keeps its last row. That row is+ /// stale rather than wrong, and `updated_at` is what a reader checks β the+ /// same contract that covers a board nothing is refreshing at all. Pruning+ /// to the published set instead would empty the table on any pass that+ /// transiently reported nothing.+ ///+ /// Uses an unchecked transaction because the caller holds `&Database`.+ pub fn publish_task_runtime(&self, rows: &[TaskRuntime]) -> Result<()> {+ let tx = self.conn.unchecked_transaction()?;+ for rt in rows {+ tx.execute(+ "INSERT INTO task_runtime+ (task_id, phase_status, pane_hash, pane_changed_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5)+ ON CONFLICT(task_id) DO UPDATE SET+ phase_status = excluded.phase_status,+ pane_hash = excluded.pane_hash,+ pane_changed_at = excluded.pane_changed_at,+ updated_at = excluded.updated_at",+ params![+ rt.task_id,+ rt.phase_status.as_str(),+ rt.pane_hash,+ rt.pane_changed_at.map(|t| t.to_rfc3339()),+ rt.updated_at.to_rfc3339(),+ ],+ )?;+ }+ // A deleted task's last status would otherwise be served to readers+ // forever as current. In the same transaction so a reader never sees a+ // pass applied without its prune.+ tx.execute(+ "DELETE FROM task_runtime WHERE task_id NOT IN (SELECT id FROM tasks)",+ [],+ )?;+ tx.commit()?;+ Ok(())+ }++ pub fn get_task_runtime(&self, task_id: &str) -> Result<Option<TaskRuntime>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM task_runtime WHERE task_id = ?1")?;+ let mut rows = stmt.query_map(params![task_id], Self::task_runtime_from_row)?;+ Ok(rows.next().transpose()?)+ }++ pub fn list_task_runtime(&self) -> Result<Vec<TaskRuntime>> {+ let mut stmt = self.conn.prepare("SELECT * FROM task_runtime")?;+ let rows = stmt+ .query_map([], Self::task_runtime_from_row)?+ .filter_map(|r| r.ok())+ .collect();+ Ok(rows)+ }++ fn task_runtime_from_row(row: &rusqlite::Row) -> rusqlite::Result<TaskRuntime> {+ let parse = |s: String| {+ chrono::DateTime::parse_from_rfc3339(&s)+ .map(|dt| dt.with_timezone(&chrono::Utc))+ .ok()+ };+ Ok(TaskRuntime {+ task_id: row.get("task_id")?,+ // An unparseable status means a writer from a newer version wrote a+ // variant this build has no arm for. Treating that as `Working` is+ // the honest fallback: it is the state that claims the least.+ phase_status: PhaseStatus::from_str(&row.get::<_, String>("phase_status")?)+ .unwrap_or(PhaseStatus::Working),+ pane_hash: row.get("pane_hash")?,+ pane_changed_at: row+ .get::<_, Option<String>>("pane_changed_at")?+ .and_then(parse),+ updated_at: row+ .get::<_, Option<String>>("updated_at")?+ .and_then(parse)+ .unwrap_or_else(chrono::Utc::now),+ })+ }}diff --git a/src/git/mod.rs b/src/git/mod.rsindex 7004457..ceaaaae 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -49,6 +49,27 @@ pub fn current_branch(path: &Path) -> Result<String> {Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())}+/// Whether `rev` resolves to a commit in the repository at `path`.+///+/// Needed because [`diff_stat`] and [`diff_full`] only fail when git cannot be+/// *spawned*: a nonzero exit β `fatal: ambiguous argument 'main'` for a base+/// branch that does not exist β leaves stdout empty and returns `Ok("")`. A+/// caller that renders that as "no changes" is asserting something it was never+/// told, which on a review screen is a claim someone may merge on.+pub fn ref_exists(path: &Path, rev: &str) -> bool {+ Command::new("git")+ .current_dir(path)+ .args([+ "rev-parse",+ "--verify",+ "--quiet",+ &format!("{rev}^{{commit}}"),+ ])+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false)+}+/// Get the diff between two branches (stat format)pub fn diff_stat(path: &Path, base: &str, target: &str) -> Result<String> {let output = Command::new("git")diff --git a/src/lib.rs b/src/lib.rsindex f71dd63..53d0aae 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -1,5 +1,6 @@pub mod agent;pub mod config;+pub mod core;pub mod db;pub mod git;pub mod mcp;@@ -8,6 +9,10 @@ pub mod tmux;pub mod tui;pub mod update;+/// The HTTP + WebSocket server behind `agtx serve`.+#[cfg(feature = "serve")]+pub mod web;+use std::path::PathBuf;#[derive(Debug, Clone)]diff --git a/src/main.rs b/src/main.rsindex aa144ba..d035741 100644--- a/src/main.rs+++ b/src/main.rs@@ -78,6 +78,7 @@ async fn main() -> Result<()> {};return agtx::mcp::serve(project_path).await;}+ Some("serve") => return run_serve(&args[2..]).await,Some("trust") => {let project_path = std::env::current_dir()?.canonicalize()?;let mut store = config::TrustStore::load().unwrap_or_default();@@ -170,6 +171,234 @@ fn migrate_old_config(new_path: &std::path::Path) -> bool {////// The dedicated command the header notice points at. `--check` only reports,/// and exits 1 when an update is available so it can drive a script.+/// `agtx serve [path] [--port N] [--host ADDR]`.+///+/// Lives in the `mode` match rather than the early fast path beside `hook` and+/// `--version`: it is long-running and wants the log appender those two skip.+/// The `cfg(not(...))` arm is not decoration β the match below ends with+/// `Some(path) => AppMode::Project(...)`, and `serve` is not `--`-prefixed, so+/// without it a default build would open a directory named `serve` as a project.+/// What `agtx serve --help` prints.+///+/// Hand-written because agtx parses its own arguments; the cost of that is+/// that `--help` has to be remembered, and forgetting it means the first thing+/// anyone types at a new subcommand is an error.+#[cfg(feature = "serve")]+const SERVE_HELP: &str = "\+agtx serve β open the board to a phone++USAGE+ agtx serve [path] [options]++ With no path, every project in the global index is served and the phone picks+ one. With a path, only that project.++OPTIONS+ --host <addr> Bind address. Defaults to 127.0.0.1, which nothing else+ can reach; anything wider requires a paired device.+ --port <n> Default 8787.+ --tunnel [private|public]+ Reach the board from outside this network. `private`+ (the default, and what a bare --tunnel means) is+ `tailscale serve`: anywhere, but only devices signed into+ your tailnet. `public` is cloudflared or `tailscale+ funnel` β the open internet, to anyone with the URL.+ --devices List paired devices.+ --revoke <id> Revoke one device.+ --revoke-all Revoke every device.++PAIRING+ Off loopback, agtx prints a QR encoding a single-use pairing code. Scanning it+ exchanges the code for that device's own token, so a lost phone can be revoked+ without disturbing the rest. Already-paired devices need nothing.++WHAT WORKS WITHOUT A TUI+ Reading does: the board, task details, diffs and the live agent pane are all+ served from the databases and tmux directly.++ Acting does not, yet. Moving a task writes a request to a queue that only a+ running `agtx` drains, so with no TUI open your taps are accepted and then+ wait. The board says so rather than pretending. Anything that does not need+ an agent β creating, editing or deleting a Backlog task β takes effect+ immediately.++ From the TUI, `W` starts this server and shows the QR, so the two are running+ together by construction.+";++#[cfg(feature = "serve")]+async fn run_serve(args: &[String]) -> Result<()> {+ if args.iter().any(|a| a == "--help" || a == "-h") {+ print!("{SERVE_HELP}");+ return Ok(());+ }++ let parsed = parse_serve_args(args)?;++ // Device management runs and exits β it is about the paired devices, not+ // about serving, and doing it without starting a listener means it works+ // while a server is already running.+ if parsed.devices {+ return list_devices();+ }+ if parsed.revoke_all {+ return revoke_all_devices();+ }+ if let Some(id) = parsed.revoke {+ return revoke_device(&id);+ }++ agtx::web::serve(parsed.opts).await+}++#[cfg(not(feature = "serve"))]+async fn run_serve(_args: &[String]) -> Result<()> {+ anyhow::bail!(+ "this agtx was built without the web server. Rebuild with `--features serve` \+ (the published binaries have it) to use `agtx serve`."+ )+}++#[cfg(feature = "serve")]+struct ParsedServeArgs {+ opts: agtx::web::ServeOptions,+ devices: bool,+ revoke_all: bool,+ revoke: Option<String>,+}++/// `agtx serve --devices`+#[cfg(feature = "serve")]+fn list_devices() -> Result<()> {+ let devices = agtx::db::Database::open_global()?.list_mobile_devices()?;+ if devices.is_empty() {+ println!("No paired devices. Run `agtx serve --host 0.0.0.0` and scan the QR code.");+ return Ok(());+ }+ println!("{:<38} {:<24} {}", "ID", "LABEL", "LAST SEEN");+ for d in devices {+ let seen = d+ .last_seen+ .map(|t| t.format("%Y-%m-%d %H:%M").to_string())+ .unwrap_or_else(|| "never".to_string());+ println!("{:<38} {:<24} {}", d.id, d.label, seen);+ }+ println!("\nRevoke one with `agtx serve --revoke <ID>`, or all with `--revoke-all`.");+ Ok(())+}++/// `agtx serve --revoke <id>`+#[cfg(feature = "serve")]+fn revoke_device(id: &str) -> Result<()> {+ let db = agtx::db::Database::open_global()?;+ if db.revoke_mobile_device(id)? {+ println!("Revoked {id}. That device must scan a new QR code to return.");+ } else {+ // Distinguished from success so a typo does not read as a revocation+ // that never happened.+ anyhow::bail!("no paired device with id {id}; `agtx serve --devices` lists them");+ }+ Ok(())+}++/// `agtx serve --revoke-all`+#[cfg(feature = "serve")]+fn revoke_all_devices() -> Result<()> {+ let removed = agtx::db::Database::open_global()?.revoke_all_mobile_devices()?;+ match removed {+ 0 => println!("No paired devices to revoke."),+ 1 => println!("Revoked 1 device."),+ n => println!("Revoked {n} devices."),+ }+ Ok(())+}++/// Parse `serve`'s own arguments.+///+/// Deliberately *not* built on the `positional_args` filter above. That filter+/// drops `--`-prefixed tokens, which leaves a flag's **value** looking exactly+/// like a positional: `serve --port 8791` would take `8791` as the project+/// path and fail with "resolving 8791: no such file or directory". A flag that+/// takes a value has to consume it.+#[cfg(feature = "serve")]+fn parse_serve_args(args: &[String]) -> Result<ParsedServeArgs> {+ let mut opts = agtx::web::ServeOptions::default();+ let mut devices = false;+ let mut revoke_all = false;+ let mut revoke = None;+ let mut iter = args.iter().peekable();++ while let Some(arg) = iter.next() {+ match arg.as_str() {+ "--port" => {+ let v = iter+ .next()+ .context("--port needs a value, e.g. `--port 8787`")?;+ opts.port = v+ .parse()+ .with_context(|| format!("--port expects a number, got {v:?}"))?;+ }+ "--host" => {+ let v = iter+ .next()+ .context("--host needs a value, e.g. `--host 127.0.0.1`")?;+ opts.host = v+ .parse()+ .with_context(|| format!("--host expects an IP address, got {v:?}"))?;+ }+ "--tunnel" => {+ // A bare `--tunnel` means private. `public` is never inferred:+ // the difference is a tailnet versus the open internet, and it+ // has to be a thing someone typed.+ let scope = match iter.peek() {+ Some(next) if !next.starts_with("--") => {+ let v = iter.next().unwrap();+ agtx::web::tunnel::TunnelScope::parse(v).with_context(|| {+ format!("--tunnel takes `private` or `public`, got {v:?}")+ })?+ }+ _ => agtx::web::tunnel::TunnelScope::Private,+ };+ opts.tunnel = Some(scope);+ }+ "--pair-code" => {+ opts.pair_code = Some(iter.next().context("--pair-code needs a value")?.clone())+ }+ // Set by the `W` overlay so the TUI can drop this session's+ // pairings if the child is killed before it cleans up after+ // itself. Not for humans; a standalone serve mints its own.+ "--session-id" => {+ opts.session_id = Some(iter.next().context("--session-id needs a value")?.clone())+ }+ "--devices" => devices = true,+ "--revoke-all" => revoke_all = true,+ "--revoke" => {+ revoke = Some(+ iter.next()+ .context("--revoke needs a device id; see `agtx serve --devices`")?+ .clone(),+ )+ }+ other if other.starts_with("--") => {+ anyhow::bail!("unknown option for `agtx serve`: {other}. Try `agtx serve --help`.")+ }+ path => {+ if opts.project_path.is_some() {+ anyhow::bail!("`agtx serve` takes at most one project path, got {path:?}");+ }+ opts.project_path = Some(PathBuf::from(path));+ }+ }+ }++ Ok(ParsedServeArgs {+ opts,+ devices,+ revoke_all,+ revoke,+ })+}+fn run_update(args: &[String]) -> Result<()> {use agtx::update;diff --git a/src/mcp/server.rs b/src/mcp/server.rsindex 3d78d89..8ecb809 100644--- a/src/mcp/server.rs+++ b/src/mcp/server.rs@@ -9,6 +9,7 @@ use rmcp::{use serde::{Deserialize, Serialize};use crate::config::{GlobalConfig, ProjectConfig};+use crate::core::actions::CallerKind;use crate::db::{Database, Task, TaskStatus, TransitionRequest};/// Whether the MCP server is bound to a specific project or serves all projects globally.@@ -480,48 +481,12 @@ impl AgtxMcpServer {}}- /// Compute which move_task actions are valid for a task given its status and plugin rules.+ /// Which `move_task` actions a task permits, as the orchestrator.+ ///+ /// The web API asks the same question as [`CallerKind::Human`] and gets a+ /// different answer for Backlog β see [`crate::core::actions`].fn allowed_actions(&self, task: &Task, deps_satisfied: bool) -> Vec<String> {- let project_path = self.resolve_project_path(None).ok();- let mut actions = Vec::new();-- let _plugin = match &task.plugin {- Some(name) => crate::config::WorkflowPlugin::load(name, project_path.as_deref())- .ok()- .or_else(|| crate::skills::load_bundled_plugin(name)),- None => crate::skills::load_bundled_plugin("agtx"),- };-- match task.status {- TaskStatus::Backlog => {- // Orchestrator does not manage Backlog β user triages manually- }- TaskStatus::Planning => {- actions.push("move_forward".to_string());- actions.push("escalate_to_user".to_string());- }- TaskStatus::Running => {- actions.push("move_forward".to_string());- actions.push("escalate_to_user".to_string());- }- TaskStatus::Review => {- actions.push("move_to_done".to_string());- actions.push("resume".to_string());- }- TaskStatus::Done => {}- }-- // Block forward transitions out of Backlog when dependencies are not satisfied- if !deps_satisfied && task.status == TaskStatus::Backlog {- actions.retain(|a| {- !matches!(- a.as_str(),- "move_forward" | "move_to_planning" | "move_to_running"- )- });- }-- actions+ crate::core::actions::allowed_actions(task, deps_satisfied, CallerKind::Orchestrator)}}@@ -687,16 +652,7 @@ impl AgtxMcpServer {)]fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {tracing::info!(tool = "move_task", task_id = %params.task_id, action = %params.action, "MCP tool called");- let valid_actions = [- "research",- "move_forward",- "move_to_planning",- "move_to_running",- "move_to_review",- "move_to_done",- "resume",- "escalate_to_user",- ];+ let valid_actions = crate::core::actions::ACTIONS;if !valid_actions.contains(¶ms.action.as_str()) {return format!("Invalid action: '{}'. Valid actions: {}",diff --git a/src/tui/app.rs b/src/tui/app.rsindex 0d11141..5c87684 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -18,6 +18,10 @@ use std::time::Instant;use crate::agent::hook_status::{self, HookState};use crate::agent::{self, AgentOperations};use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig, WorkflowPlugin};+use crate::core::input::{+ composer_holds, delivery_needle, pane_shows, submit_message, COMPOSER_TAIL_LINES,+ SUBMIT_ATTEMPTS, SUBMIT_CONFIRM_POLLS,+};use crate::db::{Database, PhaseStatus, Task, TaskStatus, TransitionRequest};use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps,@@ -432,6 +436,15 @@ struct AppState {deps_satisfied_cache: HashMap<String, bool>,// Full-screen dependency-graph overlay (Shift+D)dep_graph_popup: Option<DepGraphPopup>,+ /// The `W` overlay: serve the board to a phone, and manage paired devices.+ mobile_popup: Option<crate::tui::serve_control::MobilePopup>,+ /// The child `agtx serve`, if one is running.+ ///+ /// Held here and **not on the popup**, because the popup is a view that is+ /// dropped whenever the overlay closes β and dropping a `ServeSession`+ /// kills the child. Someone opens `W`, scans, closes it, and carries on+ /// using the board; the server has to survive that.+ serve_session: Option<crate::tui::serve_control::ServeSession>,// Queue of task IDs awaiting serialized worktree setup (batch-move from the// dependency view). Worktree setup runs one-at-a-time via `setup_rx`; this// queue is drained as each setup completes.@@ -928,6 +941,8 @@ impl App {update_install_rx: None,deps_satisfied_cache: HashMap::new(),dep_graph_popup: None,+ mobile_popup: None,+ serve_session: None,setup_queue: VecDeque::new(),instance_id: uuid::Uuid::new_v4().to_string(),},@@ -1177,6 +1192,8 @@ impl App {update_install_rx: None,deps_satisfied_cache: HashMap::new(),dep_graph_popup: None,+ mobile_popup: None,+ serve_session: None,setup_queue: VecDeque::new(),instance_id: uuid::Uuid::new_v4().to_string(),},@@ -1484,6 +1501,38 @@ impl App {if let Err(e) = self.process_transition_requests() {tracing::warn!(error = %e, "failed to process transition requests");}+ // Notice a served board whose child has died β a taken port, or a+ // tunnel the provider refused. Without this the overlay keeps+ // showing a QR for a server that is gone, which is the worst of+ // both: it looks fine and nothing works.+ if self.state.serve_session.is_some() {+ if let Some(popup) = self.state.mobile_popup.as_mut() {+ if popup.poll_session(&mut self.state.serve_session) {+ changed = true;+ }+ } else if self+ .state+ .serve_session+ .as_mut()+ .and_then(|s| s.check())+ .is_some()+ {+ // Overlay closed, so there is nowhere to show a message β+ // but the dead session must still be dropped, or `s` would+ // report "stopped serving" for something already gone.+ self.state.serve_session = None;+ }+ }++ // Beat on the same tick, because it answers a question about+ // exactly this loop: something out of process can enqueue a+ // transition whenever, but only a running TUI drains the queue.+ if let Some(path) = &self.state.project_path {+ let _ = self+ .state+ .global_db+ .beat_tui_heartbeat(&path.to_string_lossy());+ }}// tmux said a window closed. The refresh is what turns that into an@@ -2727,6 +2776,17 @@ impl App {if let Some(ref popup) = state.dep_graph_popup {Self::draw_dependency_graph(popup, frame, area, &state.config.theme);}++ // Mobile overlay+ if let Some(ref popup) = state.mobile_popup {+ Self::draw_mobile_popup(+ popup,+ state.serve_session.as_ref(),+ frame,+ area,+ &state.config.theme,+ );+ }}/// Render the dependency-graph overlay: topological columns of task cards,@@ -3436,6 +3496,11 @@ impl App {return self.handle_dep_graph_key(key);}+ // Handle the mobile overlay if open+ if self.state.mobile_popup.is_some() {+ return self.handle_mobile_key(key);+ }+// Handle PR confirmation popup if openif self.state.pr_confirm_popup.is_some() {return self.handle_pr_confirm_key(key);@@ -4640,6 +4705,10 @@ impl App {KeyCode::Char('x') => self.delete_selected_task()?,KeyCode::Char('d') => self.show_task_diff()?,KeyCode::Char('D') => self.show_dependency_graph()?,+ KeyCode::Char('W') => {+ // `W` and not `R`/`r`: those are start-research and resume.+ self.state.mobile_popup = Some(crate::tui::serve_control::MobilePopup::new());+ }KeyCode::Char('m') => self.move_task_right()?,KeyCode::Char('M') => self.move_backlog_to_running()?,KeyCode::Char('R') => {@@ -6522,6 +6591,239 @@ impl App {}/// Key handling for the dependency-graph overlay.+ /// Keys for the `W` overlay.+ ///+ /// Closing it does **not** stop the server: someone opens this, scans, and+ /// closes it while carrying on with the board. Only `s` and quitting stop+ /// serving.+ fn handle_mobile_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let Some(popup) = self.state.mobile_popup.as_mut() else {+ return Ok(());+ };+ match key.code {+ KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('W') => {+ self.state.mobile_popup = None;+ }+ // Each key is a whole action, not a mode plus a trigger.+ KeyCode::Char('s') => popup.serve(+ &mut self.state.serve_session,+ crate::tui::serve_control::DEFAULT_PORT,+ crate::tui::serve_control::Reach::Lan,+ ),+ KeyCode::Char('t') => popup.serve(+ &mut self.state.serve_session,+ crate::tui::serve_control::DEFAULT_PORT,+ crate::tui::serve_control::Reach::Tailnet,+ ),+ KeyCode::Char('x') => popup.revoke_selected(),+ KeyCode::Char('j') | KeyCode::Down => popup.move_selection(1),+ KeyCode::Char('k') | KeyCode::Up => popup.move_selection(-1),+ KeyCode::Char('r') => {+ popup.reload_devices();+ popup.message = Some("Reloaded.".to_string());+ }+ // Swallow everything else rather than letting it reach the board+ // behind the overlay.+ _ => {}+ }+ Ok(())+ }++ /// The `W` overlay: a QR to scan, and the devices already paired.+ fn draw_mobile_popup(+ popup: &crate::tui::serve_control::MobilePopup,+ session: Option<&crate::tui::serve_control::ServeSession>,+ frame: &mut Frame,+ area: Rect,+ theme: &crate::config::ThemeConfig,+ ) {+ use ratatui::widgets::Clear;++ let accent = hex_to_color(&theme.color_accent);+ let dim = hex_to_color(&theme.color_dimmed);+ let text = hex_to_color(&theme.color_text);+ let selected = hex_to_color(&theme.color_selected);++ let qr = session.and_then(|s| crate::tui::serve_control::qr_grid(&s.url));+ // The QR is the widest thing here and it must not wrap β a wrapped QR+ // is unscannable and reads as corruption rather than as a layout bug.+ // Two module rows per text row, so the height is half the width.+ let qr_width = qr.as_ref().map_or(0, |(w, _)| *w);+ let qr_height = qr_width.div_ceil(2);++ let serving = session.is_some();++ let mut lines: Vec<Line> = Vec::new();++ match (session, &qr) {+ (Some(session), Some((total, dark))) => {+ lines.extend(qr_lines(*total, dark));+ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ session.url.clone(),+ Style::default().fg(accent),+ )));+ lines.push(Line::from(Span::styled(+ "Scan it. The code is single-use; paired devices need nothing.",+ Style::default().fg(dim),+ )));+ // Say the reach out loud. A QR invites the assumption that it+ // works from anywhere, and a private address does not β the+ // failure is a phone on mobile data timing out against an+ // unroutable host, which looks like a broken pairing rather+ // than a network that was never going to carry it.+ lines.push(Line::from(Span::styled(+ if session.is_lan_only() {+ "Works on this wifi only β a private address is unroutable from mobile data."+ } else {+ "Reachable from outside this network."+ },+ Style::default().fg(selected),+ )));+ }+ (Some(session), None) => {+ lines.push(Line::from(Span::styled(+ session.url.clone(),+ Style::default().fg(accent),+ )));+ }+ (None, _) => {+ // Both options, each stating what it gives. The alternative β+ // one key setting a mode another key acts on β means neither+ // label can say what pressing it will do.+ lines.push(Line::from(Span::styled(+ "Not serving.",+ Style::default().fg(dim),+ )));+ lines.push(Line::from(""));+ for (key, reach) in [+ ("s", crate::tui::serve_control::Reach::Lan),+ ("t", crate::tui::serve_control::Reach::Tailnet),+ ] {+ let blocked = reach.unavailable();+ lines.push(Line::from(vec![+ Span::styled(+ format!(" {key} "),+ Style::default()+ .fg(if blocked.is_some() { dim } else { selected })+ .add_modifier(Modifier::BOLD),+ ),+ Span::styled(+ format!("{:<15}", reach.label()),+ Style::default().fg(if blocked.is_some() { dim } else { text }),+ ),+ Span::styled(reach.describe(), Style::default().fg(dim)),+ ]));+ if let Some(why) = blocked {+ lines.push(Line::from(Span::styled(+ format!(" unavailable: {why}"),+ Style::default().fg(hex_to_color(&theme.color_description)),+ )));+ }+ }+ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ "A paired device can type into your agents.",+ Style::default().fg(dim),+ )));+ }+ }++ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ format!("Paired devices ({})", popup.devices.len()),+ Style::default().fg(text).add_modifier(Modifier::BOLD),+ )));++ if popup.devices.is_empty() {+ lines.push(Line::from(Span::styled(+ " none yet",+ Style::default().fg(dim),+ )));+ } else {+ for (i, device) in popup.devices.iter().enumerate() {+ let marker = if i == popup.selected { "βΈ " } else { " " };+ let seen = device+ .last_seen+ .map(|t| t.format("%Y-%m-%d %H:%M").to_string())+ .unwrap_or_else(|| "never".to_string());+ lines.push(Line::from(vec![+ Span::styled(+ format!("{marker}{}", device.label),+ Style::default().fg(if i == popup.selected { selected } else { text }),+ ),+ Span::styled(format!(" last seen {seen}"), Style::default().fg(dim)),+ ]));+ }+ }++ if let Some(ref message) = popup.message {+ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ message.clone(),+ Style::default().fg(selected),+ )));+ }++ lines.push(Line::from(""));+ lines.push(Line::from(Span::styled(+ // Trimmed to fit the box, like the board's own footer: `r` still+ // reloads, it just lives in HELP rather than here. A footer that+ // runs off the edge advertises a key by half its name.+ if serving {+ "[s] stop [x] revoke [j/k] move [Esc] close, keeps serving"+ } else {+ "[s] wifi [t] tailnet [x] revoke [j/k] move [Esc] close"+ },+ Style::default().fg(dim),+ )));++ // Sized from the longest line it will actually draw. `Paragraph` is+ // left unwrapped on purpose β wrapping would break the QR's rows into+ // nonsense β so anything wider than the box is silently truncated.+ //+ // Measuring the QR alone is not enough, and the shortfall is not+ // cosmetic: the pairing URL is longer than the QR is wide, and a code+ // missing its last characters is not a shorter code but an invalid+ // one. Clicking that link fails to pair and then reports "This device+ // is not authorised", which reads as a pairing bug rather than a+ // layout one.+ let content_width = lines.iter().map(|l| l.width()).max().unwrap_or(0) as u16;+ let width = (qr_width as u16 + 6)+ .max(content_width + 4)+ .max(MOBILE_POPUP_MIN_WIDTH)+ .min(area.width.saturating_sub(2));+ let body_height = qr_height as u16 + popup.devices.len().max(1) as u16 + 10;+ let height = body_height.min(area.height.saturating_sub(2));+ let rect = centered_rect_fixed_width(width, 100, area);+ let rect = Rect {+ x: rect.x,+ y: area.y + (area.height.saturating_sub(height)) / 2,+ width: rect.width.min(width),+ height,+ };++ frame.render_widget(Clear, rect);++ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(Style::default().fg(hex_to_color(&theme.color_popup_border)))+ .title(Span::styled(+ if serving {+ " Mobile β serving "+ } else {+ " Mobile "+ },+ Style::default()+ .fg(hex_to_color(&theme.color_popup_header))+ .add_modifier(Modifier::BOLD),+ ));+ let inner = block.inner(rect);+ frame.render_widget(block, rect);++ frame.render_widget(Paragraph::new(lines), inner);+ }+fn handle_dep_graph_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {let Some(popup) = self.state.dep_graph_popup.as_mut() else {return Ok(());@@ -7265,6 +7567,19 @@ impl App {.get_task(&req.task_id)?.ok_or_else(|| anyhow::anyhow!("Task not found: {}", req.task_id))?;+ // Recheck when the queue is drained: an agent may have written more+ // work since the phone rendered the card or submitted the request.+ // Include move_forward so stale/legacy requests cannot bypass this.+ if task.status == TaskStatus::Review+ && matches!(req.action.as_str(), "move_to_done" | "move_forward")+ && task+ .worktree_path+ .as_ref()+ .is_some_and(|wt| self.state.git_ops.has_changes(Path::new(wt)))+ {+ anyhow::bail!("Uncommitted changes prevent moving this task to Done. Commit or resolve them first.");+ }+// Block forward transitions when dependencies are not satisfiedlet is_forward = matches!(req.action.as_str(),@@ -8150,9 +8465,52 @@ impl App {});}+ /// Whether `task_runtime` is worth writing right now.+ ///+ /// The table exists so a *reader outside this process* can see phase status+ /// it cannot recompute. With no such reader the write is pure cost β and it+ /// is not a small one in aggregate: a transaction every couple of seconds,+ /// for the life of every agtx session, forever, on the chance a phone might+ /// one day connect.+ ///+ /// So it is gated twice. Without the `serve` feature there is no server in+ /// this binary and nothing could ever read the table, so the call is+ /// compiled out entirely. With it, publishing starts when someone actually+ /// asks for a board and stops when they stop β the web server marks+ /// `board_watch` on a board request, and the overlay's own child counts too,+ /// since starting it is an explicit request for mobile.+ ///+ /// The window is generous because the board no longer polls: someone can+ /// read it for minutes without issuing a request, and going quiet mid-read+ /// would freeze their phase icons rather than save anything worth having.+ #[cfg(feature = "serve")]+ fn should_publish_runtime(&self) -> bool {+ const WATCH_WINDOW: i64 = 10 * 60;++ if self.state.serve_session.is_some() {+ return true;+ }+ let Some(path) = &self.state.project_path else {+ return false;+ };+ self.state+ .global_db+ .board_watched_recently(+ &path.to_string_lossy(),+ chrono::Duration::seconds(WATCH_WINDOW),+ )+ .unwrap_or(false)+ }++ #[cfg(not(feature = "serve"))]+ fn should_publish_runtime(&self) -> bool {+ false+ }+/// Apply results from the background session refresh thread.fn apply_session_refresh(&mut self, result: SessionRefreshResult) {let now = Instant::now();+ let mut runtime_rows: Vec<crate::db::TaskRuntime> = Vec::new();for task_status in result.statuses {// The refresh ran on a thread, so the task may have moved on since@@ -8263,6 +8621,26 @@ impl App {.phase_status_cache.insert(task_status.task_id.clone(), (phase, now));+ // Collect the resolved status for readers in other processes, to be+ // published as one transaction below. This is the only writer:+ // `phase` is final here, after every override above, and recomputing+ // it elsewhere would mean duplicating the artifact-check and+ // pane-hash pipeline against the same panes.+ let pane = self.state.pane_content_hashes.get(&task_status.task_id);+ runtime_rows.push(crate::db::TaskRuntime {+ task_id: task_status.task_id.clone(),+ phase_status: phase,+ pane_hash: pane.map(|(h, _)| h.to_string()),+ // `Instant` has no epoch, so the stored wall-clock time is+ // derived from how long ago the change was.+ pane_changed_at: pane.map(|(_, at)| {+ chrono::Utc::now()+ - chrono::Duration::from_std(now.duration_since(*at))+ .unwrap_or_else(|_| chrono::Duration::zero())+ }),+ updated_at: chrono::Utc::now(),+ });+// Notify orchestrator when a phase completes (newly Ready)if newly_ready {if self.state.orchestrator_session.is_some() {@@ -8285,10 +8663,14 @@ impl App {} else {&task_status.task_id};- let notif = crate::db::Notification::new(format!(- "Task \"{}\" ({}) completed phase: {}",- task_title, short_id, phase_name- ));+ let notif = crate::db::Notification::for_task(+ crate::db::NotificationKind::PhaseCompleted,+ &task_status.task_id,+ format!(+ "Task \"{}\" ({}) completed phase: {}",+ task_title, short_id, phase_name+ ),+ );let _ = db.create_notification(¬if);}}@@ -8411,7 +8793,7 @@ impl App {&task_status.task_id};let reason = self.state.blocked_reasons.get(&task_status.task_id);- let notif = crate::db::Notification::new(match (blocked, reason) {+ let message = match (blocked, reason) {(true, Some(r)) => format!("Task \"{}\" ({}) is blocked in phase {} waiting for: {}",task_title,@@ -8431,7 +8813,12 @@ impl App {short_id,task_status.status.as_str()),- });+ };+ let notif = crate::db::Notification::for_task(+ crate::db::NotificationKind::TaskStuck,+ &task_status.task_id,+ message,+ );let _ = db.create_notification(¬if);}}@@ -8443,6 +8830,18 @@ impl App {.remove(&task_status.task_id);}}++ // One commit for the whole pass, and only when something is reading.+ // Pruning rides along inside it β see `publish_task_runtime`; it is done+ // there rather than at the delete sites because MCP deletes tasks from+ // another process entirely.+ if self.should_publish_runtime() {+ if let Some(db) = &self.state.db {+ if let Err(e) = db.publish_task_runtime(&runtime_rows) {+ tracing::warn!(error = %e, "failed to publish task runtime");+ }+ }+ }}fn switch_to_project(&mut self, project: &ProjectInfo) -> Result<()> {@@ -8515,6 +8914,12 @@ impl App {impl Drop for App {fn drop(&mut self) {+ // Stop a server started from the overlay. tmux windows deliberately+ // outlive agtx; a child server must not, or it holds its port with+ // nothing on screen owning it. Quitting is the only thing that stops+ // it β closing the overlay does not.+ self.state.serve_session = None;+// Deliver what is still queued and stop the broker before the process// goes away β the last characters typed into a pane were typed on// purpose. Bounded by the queue depth, so quitting stays instant.@@ -10953,37 +11358,10 @@ fn spawn_send_to_agent(const DELIVERY_ATTEMPTS: u32 = 3;const DELIVERY_CONFIRM_POLLS: u32 = 10; // x 200ms = 2s-/// Attempts and per-attempt budget for [`submit_message`].-///-/// Smaller than the delivery budget on purpose: by the time this runs the text is-/// known to be in the composer, so this is only absorbing a composer that is still-/// mid-render, not a session that never attached its stdin.-const SUBMIT_ATTEMPTS: u32 = 3;-const SUBMIT_CONFIRM_POLLS: u32 = 5; // x 200ms = 1s/// Pane-settle budget before each attempt: 1s of quiet, given up on after 10s.const SETTLE_STABLE_POLLS: u32 = 5;const SETTLE_MAX_POLLS: u32 = 50;-/// Longest prefix of a message used to confirm it landed on a pane that never-/// went quiet. Short on purpose: a composer wraps and re-indents what it echoes,-/// so a long needle straddles a line break and reads as absent.-const DELIVERY_NEEDLE_CHARS: usize = 16;--/// Whitespace-collapsed prefix of `text`, or `None` when there is nothing-/// distinctive enough to look for.-fn delivery_needle(text: &str) -> Option<String> {- let flat: String = text.split_whitespace().collect::<Vec<_>>().join(" ");- let needle: String = flat.chars().take(DELIVERY_NEEDLE_CHARS).collect();- (needle.chars().count() >= 4).then_some(needle)-}--/// Whether `needle` is visible in `pane`, comparing both whitespace-collapsed so-/// a wrap or re-indent in the composer does not hide it.-fn pane_shows(pane: &str, needle: &str) -> bool {- let flat: String = pane.split_whitespace().collect::<Vec<_>>().join(" ");- flat.contains(needle)-}-/// Wait for the pane to stop changing, up to [`SETTLE_MAX_POLLS`].////// Returns whether it settled; callers proceed either way, since a pane that@@ -11026,84 +11404,6 @@ fn wait_for_pane_settled(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> bo/// Returns whether the message was seen to land. Callers submit either way,/// because a false negative (a pane that happened not to redraw) must not/// swallow the task.-/// Lines at the bottom of a pane treated as the composer.-///-/// Sized from the worst real layout, not from the composer alone: while the-/// command picker is open the agent draws its suggestions *below* the composer,-/// and cursor's footer wraps the worktree path over three more lines. That puts-/// the text being submitted eight or more lines off the bottom β a snugger-/// window reads it as already gone and stops pressing Enter after one.-///-/// The cost of erring wide is one extra Enter into a composer that already-/// submitted, which is inert; the cost of erring narrow is a command parked-/// forever.-const COMPOSER_TAIL_LINES: usize = 14;--/// Whether the message is still sitting in the composer rather than submitted.-///-/// Only the bottom of the pane is examined: after a submit the text moves up into-/// the scrollback, and finding it *there* is proof it went, not that it stayed.-fn composer_holds(pane: &str, needle: &str) -> bool {- // Trailing blanks first. `capture-pane -p` emits one line per pane *row*, not- // per rendered line β verified against tmux 3.5a: a 20-row pane holding one- // word comes back as 20 lines, 19 of them empty. Anchoring the window to the- // raw end would put it entirely inside that padding whenever the agent's- // output has not yet filled the pane, find nothing, and stop pressing Enter- // after one β the very park this exists to catch.- let mut lines: Vec<&str> = pane.lines().collect();- while lines.last().is_some_and(|l| l.trim().is_empty()) {- lines.pop();- }- let start = lines.len().saturating_sub(COMPOSER_TAIL_LINES);- pane_shows(&lines[start..].join("\n"), needle)-}--/// Press Enter until the message actually leaves the composer.-///-/// The check is "the text is gone from the composer", not "the pane changed".-/// A repaint is not a submit: a **bare skill command** β one with no prompt after-/// it, which is what a phase whose command carries no `{task}`/`{task_id}` sends β-/// exactly matches a skill name, so the composer's command picker opens *on the-/// paste*. Enter is then consumed by the picker ("Press enter to insert"), which-/// inserts the command and repaints. The old change-detector read that repaint as-/// success and returned, leaving the command parked in the composer forever.-///-/// Measured against codex-cli 0.144.5 and cursor-agent 2026.08.25: both open the-/// picker on a pasted bare command, both need the second Enter, and both run the-/// skill once it arrives.-///-/// Falls back to the change-detector when the text is too short to track, and is-/// bounded either way β an agent that never submits costs `SUBMIT_ATTEMPTS`-/// keypresses, not an unbounded stream.-///-/// Known cost: agents echo the submitted message into the transcript just above-/// the composer, so a *successful* submit can leave the needle inside the window-/// and spend the remaining attempts. Those Enters land in an empty composer,-/// which is inert β except against a dialog that renders mid-submit, where a bare-/// Enter picks the highlighted option. `answer_session_dialogs` is what answers-/// those, and it runs on the refresh loop rather than here.-fn submit_message(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, text: &str) {- let needle = delivery_needle(text);- for _ in 0..SUBMIT_ATTEMPTS {- let before = tmux_ops.capture_pane(target).unwrap_or_default();- let _ = tmux_ops.send_key(target, "Enter");- for _ in 0..SUBMIT_CONFIRM_POLLS {- std::thread::sleep(std::time::Duration::from_millis(200));- let Ok(now) = tmux_ops.capture_pane(target) else {- continue;- };- match needle.as_deref() {- Some(n) if !composer_holds(&now, n) => return,- Some(_) => {}- // Nothing distinctive enough to look for; the pane moving is all- // there is to go on.- None if now != before => return,- None => {}- }- }- }-}-fn deliver_message(tmux_ops: &Arc<dyn TmuxOperations>,target: &str,@@ -11810,7 +12110,11 @@ fn run_orchestrator_catchup(db: &Database, tasks: &[Task], project_path: Option<if existing.contains(&message) {continue;}- let _ = db.create_notification(&crate::db::Notification::new(message));+ let _ = db.create_notification(&crate::db::Notification::for_task(+ crate::db::NotificationKind::PhaseCompleted,+ &task.id,+ message,+ ));}}@@ -14131,3 +14435,41 @@ fn draw_wizard_list();}}++/// A QR module grid as ratatui lines.+///+/// `β` splits each cell into an upper and a lower module, coloured+/// independently, so the code is square in a terminal whose cells are about+/// twice as tall as they are wide β and half as tall as one module per cell.+///+/// The colours are set explicitly, not left to the theme: a QR must be+/// dark-on-light to scan, and most terminals running agtx are the other way+/// round.+fn qr_lines(total: usize, dark: &[bool]) -> Vec<Line<'static>> {+ let at = |x: usize, y: usize| -> bool { y < total && dark[y * total + x] };+ (0..total)+ .step_by(2)+ .map(|row| {+ let spans: Vec<Span> = (0..total)+ .map(|x| {+ let upper = at(x, row);+ let lower = at(x, row + 1);+ Span::styled(+ "β",+ Style::default()+ .fg(if upper { Color::Black } else { Color::White })+ .bg(if lower { Color::Black } else { Color::White }),+ )+ })+ .collect();+ Line::from(spans)+ })+ .collect()+}++/// Narrowest the `W` overlay may be.+///+/// Wide enough for its longest sentence: the body is drawn unwrapped, because+/// wrapping would break the QR's rows, so a narrower box truncates text rather+/// than reflowing it.+const MOBILE_POPUP_MIN_WIDTH: u16 = 64;diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex ffa5741..17abfbc 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -15505,3 +15505,567 @@ fn an_unmapped_key_is_dropped_rather_than_guessed() {None);}++// =============================================================================+// The `W` overlay β serving the board to a phone+// =============================================================================++#[test]+#[cfg(feature = "test-mocks")]+fn test_w_opens_the_mobile_overlay_and_esc_closes_it() {+ let mut app = make_test_app();+ assert!(app.state.mobile_popup.is_none());++ press_key(&mut app, KeyCode::Char('W'));+ assert!(+ app.state.mobile_popup.is_some(),+ "W did not open the overlay"+ );+ assert!(app.draw().is_ok());++ press_key(&mut app, KeyCode::Esc);+ assert!(app.state.mobile_popup.is_none());+}++/// The overlay swallows keys rather than letting them reach the board behind+/// it β otherwise `x` would delete the selected *task* while someone is aiming+/// at a device row.+#[test]+#[cfg(feature = "test-mocks")]+fn test_the_mobile_overlay_swallows_board_keys() {+ let mut app = make_test_app();+ let before = app.state.board.tasks.len();++ press_key(&mut app, KeyCode::Char('W'));+ for key in ['x', 'o', 'd', 'm', 'p'] {+ press_key(&mut app, KeyCode::Char(key));+ }++ assert!(app.state.mobile_popup.is_some(), "a key closed the overlay");+ assert_eq!(+ app.state.board.tasks.len(),+ before,+ "a key reached the board behind the overlay"+ );+ assert!(+ app.state.wizard.is_none(),+ "`o` opened the wizard underneath"+ );+}++/// Everything currently on the test terminal, as one string.+///+/// Reads the cells rather than any of the app's own state, so it sees what a+/// person would see β which is the point when the bug under test is bytes+/// reaching the screen that should never have been drawn.+#[cfg(feature = "test-mocks")]+fn rendered_text(app: &App) -> String {+ match app.terminal.backend() {+ AppBackend::Test(backend) => {+ let buffer = backend.buffer();+ let area = buffer.area();+ (0..area.height)+ .map(|y| {+ (0..area.width)+ .map(|x| buffer[(x, y)].symbol())+ .collect::<String>()+ })+ .collect::<Vec<_>>()+ .join("\n")+ }+ _ => String::new(),+ }+}++/// A QR drawn through ratatui must be **styled spans**, never the ANSI string+/// the CLI banner prints: ratatui does not interpret escape sequences, so those+/// bytes would be drawn as literal garbage β a QR that cannot scan and looks+/// like corruption.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_overlay_never_draws_raw_ansi() {+ let mut app = make_test_app();+ press_key(&mut app, KeyCode::Char('W'));+ assert!(app.draw().is_ok());++ let rendered = rendered_text(&app);+ assert!(+ !rendered.contains('\u{1b}') && !rendered.contains("[97m") && !rendered.contains("[107m"),+ "an escape sequence reached the screen: {rendered:?}"+ );+}++/// Closing the overlay must not stop the server: the point is to scan, close,+/// and carry on using the board.+///+/// This needs a live session to mean anything. An earlier version of this test+/// had none and asserted only that the overlay opened and closed β so it passed+/// while `Esc` was killing the child, because `MobilePopup` owned the+/// `ServeSession` and dropping the view dropped the server. The session now+/// lives on `AppState`; this is what holds that.+#[test]+#[cfg(feature = "test-mocks")]+fn test_closing_the_overlay_does_not_stop_serving() {+ use crate::tui::serve_control::{MobilePopup, ServeSession};++ let mut app = make_test_app();+ // A stand-in child that stays alive long enough to observe.+ let child = std::process::Command::new("sleep")+ .arg("30")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .expect("spawn a stand-in child");+ app.state.serve_session = Some(ServeSession::for_test(+ child,+ "http://10.0.0.2:8787/#pair=x",+ ));+ app.state.mobile_popup = Some(MobilePopup::new());++ press_key(&mut app, KeyCode::Esc);+ assert!(+ app.state.mobile_popup.is_none(),+ "Esc should close the overlay"+ );+ assert!(+ app.state.serve_session.is_some(),+ "closing the overlay stopped the server"+ );+ // And the child is genuinely still running, not merely still referenced.+ assert!(+ app.state.serve_session.as_mut().unwrap().check().is_none(),+ "the child exited when the overlay closed"+ );++ // Reopening finds it still serving.+ press_key(&mut app, KeyCode::Char('W'));+ assert!(app.state.mobile_popup.is_some());+ assert!(app.state.serve_session.is_some());++ // Quitting is what stops it.+ app.state.serve_session = None;+}++/// `move_selection` is the only thing standing between an empty device list and+/// an index panic on the next draw.+#[test]+#[cfg(feature = "test-mocks")]+fn test_device_selection_is_clamped() {+ use crate::tui::serve_control::MobilePopup;++ let mut popup = MobilePopup {+ devices: Vec::new(),+ selected: 0,+ message: None,+ };+ popup.move_selection(1);+ popup.move_selection(-1);+ assert_eq!(popup.selected, 0, "an empty list must not move the cursor");++ popup.devices = vec![+ crate::db::MobileDevice::new("a", "h1"),+ crate::db::MobileDevice::new("b", "h2"),+ ];+ popup.move_selection(5);+ assert_eq!(popup.selected, 1, "selection ran past the end");+ popup.move_selection(-5);+ assert_eq!(popup.selected, 0, "selection ran before the start");+}++/// A QR invites the assumption that it works from anywhere. A private address+/// does not, and the failure β a phone on mobile data timing out against an+/// unroutable host β looks like broken pairing rather than a network that was+/// never going to carry it. So the overlay says which it is.+#[test]+#[cfg(feature = "test-mocks")]+fn test_a_lan_only_url_is_named_as_such() {+ use crate::tui::serve_control::ServeSession;++ for private in [+ "http://192.168.178.26:8787/#pair=abc",+ "http://10.0.0.4:8787/#pair=abc",+ "http://172.16.5.9:8787/#pair=abc",+ "http://127.0.0.1:8787/#pair=abc",+ "http://169.254.1.1:8787/#pair=abc",+ ] {+ assert!(+ ServeSession::lan_only_url(private),+ "{private} should be flagged as LAN-only"+ );+ }++ for reachable in [+ "https://mac.tailnet.ts.net/#pair=abc",+ "https://brave-fox-1234.trycloudflare.com/#pair=abc",+ "http://203.0.113.7:8787/#pair=abc",+ ] {+ assert!(+ !ServeSession::lan_only_url(reachable),+ "{reachable} should not be flagged as LAN-only"+ );+ }+}++/// Tailscale reports a fully-qualified name with the root dot. Leaving it on+/// produces a URL some clients accept and others reject β the worst of both.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_tailnet_hostname_is_parsed_and_trimmed() {+ use crate::web::tunnel::parse_tailnet_hostname;++ let json = r#"{"Self":{"DNSName":"macbook.tail1a2b.ts.net.","HostName":"macbook"}}"#;+ assert_eq!(+ parse_tailnet_hostname(json).as_deref(),+ Some("macbook.tail1a2b.ts.net")+ );++ // Not signed in, or a shape we do not recognise: no hostname rather than a+ // guess, so the overlay says it cannot serve instead of building a URL+ // that resolves nowhere.+ assert_eq!(parse_tailnet_hostname(r#"{"Self":{}}"#), None);+ assert_eq!(parse_tailnet_hostname(r#"{"Self":{"DNSName":"."}}"#), None);+ assert_eq!(parse_tailnet_hostname("not json"), None);+ assert_eq!(parse_tailnet_hostname("{}"), None);+}++/// The overlay's body is drawn unwrapped β wrapping would break the QR's rows+/// into nonsense β so a line longer than the box is silently truncated. A+/// sentence losing its last word reads as a typo rather than a layout bug, so+/// the box has to be wide enough for everything it says.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_mobile_overlay_never_truncates_its_own_text() {+ let mut app = make_test_app();+ press_key(&mut app, KeyCode::Char('W'));++ app.draw().unwrap();+ let screen = rendered_text(&app);+ for line in screen.lines().filter(|l| l.contains('β')) {+ let inner = line.trim_matches(|c| c != 'β').trim_matches('β');+ // A body line that ends flush against the border, with no space before+ // it, is one that ran out of room.+ assert!(+ inner.is_empty() || inner.ends_with(' ') || inner.trim().is_empty(),+ "a line reaches the border and is probably cut: {inner:?}"+ );+ }+}++/// Draw the `W` overlay on its own, at a size a real terminal has.+///+/// The shared `TestBackend` is 80x24 and a QR is 21 rows, so through `App::draw`+/// everything below the QR β the URL, the hint, the footer β is clipped+/// vertically and no assertion about it can mean anything.+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn render_mobile_overlay(url: &str, w: u16, h: u16) -> String {+ use crate::tui::serve_control::{MobilePopup, ServeSession};++ let child = std::process::Command::new("sleep")+ .arg("30")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .expect("spawn a stand-in child");+ let session = ServeSession::for_test(child, url);+ let popup = MobilePopup::new();+ let theme = crate::config::ThemeConfig::default();++ let mut terminal =+ ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).expect("terminal");+ terminal+ .draw(|frame| {+ let area = frame.area();+ App::draw_mobile_popup(&popup, Some(&session), frame, area, &theme);+ })+ .expect("draw");++ terminal+ .backend()+ .buffer()+ .content()+ .chunks(w as usize)+ .map(|row| row.iter().map(|c| c.symbol()).collect::<String>())+ .collect::<Vec<_>>()+ .join("\n")+}++/// A realistic pairing URL: a LAN address and a full 32-character code. The+/// length is the whole point, so a short stand-in would pass against a box that+/// truncates.+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn sample_pairing_url() -> String {+ format!("http://192.168.178.26:8787/#pair={}", "be29ea5a".repeat(4))+}++/// The URL under the QR must appear **in full**.+///+/// It is a link people click β for a demo on the machine itself, or to paste+/// somewhere β and a pairing code missing its last characters is not a shorter+/// code, it is an invalid one. The failure is silent and misdirects: pairing+/// fails, the app falls back to an unauthenticated request, and the browser+/// reports "This device is not authorised", which reads as a pairing problem+/// rather than a layout one.+///+/// The box was sized from the QR alone, and the URL is longer than the QR is+/// wide.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_overlay_shows_the_whole_pairing_url() {+ let url = sample_pairing_url();+ let screen = render_mobile_overlay(&url, 120, 44);+ assert!(+ screen.contains(&url),+ "the pairing URL is cut off, so clicking it pairs with an invalid code.\n\+ wanted: {url}\nscreen:\n{screen}"+ );+}++/// Every line drawn while serving has to fit, for the same reason: the body is+/// unwrapped, so anything too wide is silently cut.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_serving_overlay_never_truncates_its_own_text() {+ let screen = render_mobile_overlay(&sample_pairing_url(), 120, 44);+ for line in screen.lines().filter(|l| l.contains('β')) {+ let inner = line.trim_matches(|c| c != 'β').trim_matches('β');+ assert!(+ inner.is_empty() || inner.ends_with(' ') || inner.trim().is_empty(),+ "a line reaches the border and is probably cut: {inner:?}"+ );+ }+}++/// `s` and `t` are each a whole action β serve to this wifi, serve via the+/// tailnet β rather than one key setting a mode another key acts on. A hidden+/// mode means neither label can say what pressing it will do, which is the+/// confusion this design replaced.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_overlay_offers_both_reaches_directly() {+ let mut app = make_test_app();+ press_key(&mut app, KeyCode::Char('W'));+ app.draw().unwrap();+ let screen = rendered_text(&app);++ assert!(screen.contains("local network"), "{screen}");+ assert!(screen.contains("tailnet"), "{screen}");+ assert!(+ screen.contains("this wifi only"),+ "the wifi option must say it is unroutable off the network: {screen}"+ );+ assert!(+ !screen.contains("t to switch"),+ "nothing should still advertise the removed mode toggle"+ );+}++/// Only those two behind a key. `--tunnel public` publishes an endpoint that+/// can type into a running agent; that should cost more than one keystroke.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_the_overlay_never_offers_the_public_internet() {+ let mut app = make_test_app();+ press_key(&mut app, KeyCode::Char('W'));+ app.draw().unwrap();+ let screen = rendered_text(&app).to_lowercase();+ assert!(+ !screen.contains("public") && !screen.contains("funnel"),+ "the overlay offers public exposure: {screen}"+ );+}++/// A served board whose child has died must say *why*.+///+/// The child knows things the TUI does not β that the port is taken, or that+/// Tailscale Serve is disabled for this tailnet and the one-time link that+/// enables it. Discarding its stderr leaves the overlay able to say only "it+/// stopped", which helps nobody; and until this was wired up, `poll_session`+/// was dead code, so a dead child was never noticed at all and the overlay+/// went on showing a QR for a server that was gone.+#[test]+#[cfg(feature = "test-mocks")]+fn test_a_dead_server_reports_what_the_child_said() {+ use crate::tui::serve_control::{MobilePopup, ServeSession};++ let child = std::process::Command::new("sh")+ .args([+ "-c",+ "echo 'Error: binding 127.0.0.1:8787' >&2; \+ echo '' >&2; \+ echo 'Address already in use (os error 48)' >&2; \+ exit 1",+ ])+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::piped())+ .spawn()+ .expect("spawn");++ let mut session = Some(ServeSession::for_test(+ child,+ "http://10.0.0.2:8787/#pair=x",+ ));+ let mut popup = MobilePopup::new();++ // Give it a moment to exit, then poll as housekeeping does.+ for _ in 0..30 {+ if popup.poll_session(&mut session) {+ break;+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }++ assert!(session.is_none(), "a dead session must be dropped");+ let message = popup.message.expect("a dead server must explain itself");+ assert!(+ message.contains("Address already in use"),+ "the child's own words were dropped: {message}"+ );+ // The *last* line, because anyhow prints the context first and the cause β+ // the part that says what to do β last.+ assert!(+ !message.contains("binding 127.0.0.1"),+ "reported the context rather than the cause: {message}"+ );+}++/// An idle TUI must not write `task_runtime` at all.+///+/// The table mirrors phase status for a reader in another process. With no+/// reader the write is pure cost β one transaction every couple of seconds for+/// the life of every session β so publishing is gated on someone actually+/// asking for a board, and compiled out entirely in a build with no server.+#[test]+#[cfg(feature = "test-mocks")]+fn test_an_unwatched_board_publishes_no_runtime() {+ let app = make_test_app();+ assert!(+ !app.should_publish_runtime(),+ "a board nobody has asked for should not be mirrored to the database"+ );+}++/// Starting the server from the overlay is an explicit request for mobile, so+/// it counts without waiting for the phone's first request.+#[test]+#[cfg(all(feature = "test-mocks", feature = "serve"))]+fn test_serving_from_the_overlay_turns_publishing_on() {+ use crate::tui::serve_control::ServeSession;++ let mut app = make_test_app();+ assert!(!app.should_publish_runtime());++ let child = std::process::Command::new("sleep")+ .arg("30")+ .stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null())+ .spawn()+ .expect("spawn a stand-in child");+ app.state.serve_session = Some(ServeSession::for_test(+ child,+ "http://10.0.0.2:8787/#pair=x",+ ));++ assert!(+ app.should_publish_runtime(),+ "serving should start the mirror without waiting for a request"+ );+ app.state.serve_session = None;+}++/// A build without the `serve` feature still has the `W` binding, so both+/// options are permanently unavailable β and must say what to do about it. The+/// published binaries carry the feature; a plain `cargo build --release` does+/// not, and "this build has no web server" left the reader guessing whether+/// that was a bug, a missing dependency, or something they could fix.+#[test]+#[cfg(all(feature = "test-mocks", not(feature = "serve")))]+fn test_a_build_without_the_server_says_how_to_get_one() {+ use crate::tui::serve_control::Reach;++ for reach in [Reach::Lan, Reach::Tailnet] {+ let why = reach.unavailable().expect("must be unavailable");+ assert!(+ why.contains("--features serve"),+ "the reason must name the fix: {why}"+ );+ }+}++#[test]+#[cfg(feature = "test-mocks")]+fn queued_completion_refuses_dirty_worktree() {+ for action in ["move_to_done", "move_forward"] {+ let mut git = MockGitOperations::new();+ git.expect_has_changes().times(1).returning(|_| true);+ // No kill/remove expectations: either side effect would fail the test.+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(MockTmuxOperations::new()),+ Arc::new(git),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap();+ let mut task = Task::new("Dirty review", "claude", "test-project");+ task.status = TaskStatus::Review;+ task.worktree_path = Some("/tmp/test-project/worktree".into());+ task.session_name = Some("session:task".into());+ let db = app.state.db.as_ref().unwrap();+ db.create_task(&task).unwrap();+ let req = crate::db::TransitionRequest::new(&task.id, action);+ db.create_transition_request(&req).unwrap();+ app.process_transition_requests().unwrap();+ let db = app.state.db.as_ref().unwrap();+ let saved = db.get_task(&task.id).unwrap().unwrap();+ assert_eq!(saved.status, TaskStatus::Review);+ assert_eq!(saved.worktree_path, task.worktree_path);+ assert_eq!(saved.session_name, task.session_name);+ let result = db.get_transition_request(&req.id).unwrap().unwrap();+ assert!(result.error.unwrap().contains("Uncommitted changes"));+ }+}++#[test]+#[cfg(feature = "test-mocks")]+fn queued_completion_allows_clean_worktree() {+ let (tx, rx) = std::sync::mpsc::channel();+ let mut git = MockGitOperations::new();+ git.expect_has_changes().times(1).returning(|_| false);+ git.expect_remove_worktree()+ .times(1)+ .returning(move |_, _| {+ tx.send(()).unwrap();+ Ok(())+ });+ let mut app = App::new_for_test(+ Some(PathBuf::from("/tmp/test-project")),+ Arc::new(MockTmuxOperations::new()),+ Arc::new(git),+ Arc::new(MockGitProviderOperations::new()),+ Arc::new(MockAgentRegistry::new()),+ )+ .unwrap();+ let mut task = Task::new("Clean completion", "claude", "test-project");+ task.status = TaskStatus::Review;+ task.worktree_path = Some("/tmp/test-project/worktree".into());+ let db = app.state.db.as_ref().unwrap();+ db.create_task(&task).unwrap();+ let req = crate::db::TransitionRequest::new(&task.id, "move_to_done");+ db.create_transition_request(&req).unwrap();+ app.process_transition_requests().unwrap();+ rx.recv_timeout(std::time::Duration::from_secs(3)).unwrap();+ let db = app.state.db.as_ref().unwrap();+ let saved = db.get_task(&task.id).unwrap().unwrap();+ assert_eq!(saved.status, TaskStatus::Done);+ assert!(saved.worktree_path.is_none());+ assert!(db+ .get_transition_request(&req.id)+ .unwrap()+ .unwrap()+ .error+ .is_none());+}diff --git a/src/tui/help.rs b/src/tui/help.rsindex 3b81eb5..22823ea 100644--- a/src/tui/help.rs+++ b/src/tui/help.rs@@ -28,6 +28,7 @@ pub const HELP: &[HelpSection] = &[e("C-f", "Open the task's pane fullscreen"),e("d", "Show the task's git diff"),e("D", "Dependency graph overlay"),+ e("W", "Serve the board to a phone, and manage paired devices"),e("/", "Search tasks"),e("x", "Delete task"),e("q", "Quit"),@@ -98,6 +99,18 @@ pub const HELP: &[HelpSection] = &[e("? / Esc / q", "Close"),],},+ HelpSection {+ title: "Mobile (W)",+ entries: &[+ e("s", "Serve to this wifi β not reachable on mobile data"),+ e("t", "Serve via your tailnet β anywhere, your devices only"),+ e("s / t", "While serving, either one stops it"),+ e("j k ββ", "Select a paired device"),+ e("x", "Revoke the selected device"),+ e("r", "Reload the device list"),+ e("Esc q W", "Close β serving continues"),+ ],+ },HelpSection {title: "Dependency graph",entries: &[diff --git a/src/tui/mod.rs b/src/tui/mod.rsindex 1e78d86..0a0328e 100644--- a/src/tui/mod.rs+++ b/src/tui/mod.rs@@ -3,6 +3,7 @@ pub mod board;pub mod config_editor;pub mod dep_graph;pub mod help;+pub mod serve_control;pub mod shell_popup;pub mod text_input;mod theme;diff --git a/src/tui/serve_control.rs b/src/tui/serve_control.rsnew file mode 100644index 0000000..a713395--- /dev/null+++ b/src/tui/serve_control.rs@@ -0,0 +1,423 @@+//! Running `agtx serve` as a child of the TUI, and the overlay that drives it.+//!+//! **Why the TUI mints the pairing code.** The obvious alternative is to let+//! the server mint one and parse it back out of the child's stdout, which makes+//! the banner's wording load-bearing and breaks silently when it changes.+//! Passing `--pair-code` in the other direction means the TUI already knows the+//! URL before the child has started, so it can draw the QR immediately and+//! never has to read the child at all.+//!+//! **Why the child is killed on drop.** agtx has never held a long-running+//! child of its own β tmux windows outlive it deliberately, and agents live in+//! those windows. A server that outlived the TUI would hold its port with+//! nothing on screen owning it, which surfaces a week later as "why does serve+//! say address in use".++use std::net::IpAddr;+use std::process::{Child, Command, Stdio};++use anyhow::{Context, Result};++/// Default port for the TUI-launched server.+///+/// The same one `agtx serve` uses on its own, so a device paired through the+/// overlay keeps working against a hand-started server and the other way round.+pub const DEFAULT_PORT: u16 = 8787;++/// How far the served board should reach.+///+/// Only these two. `--tunnel public` exists on the CLI and is deliberately not+/// offered behind a keypress: it publishes an endpoint that can type into a+/// running agent, and that should cost more than tapping `t` twice.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Reach {+ /// Bound to every interface. Works on this wifi; a private address is+ /// unroutable from mobile data.+ Lan,+ /// `tailscale serve` into a loopback listener. Anywhere, but only devices+ /// signed into the same tailnet.+ Tailnet,+}++impl Reach {+ pub fn label(&self) -> &'static str {+ match self {+ Reach::Lan => "local network",+ Reach::Tailnet => "tailnet",+ }+ }++ /// What a person gets, in the words the overlay offers it in.+ ///+ /// Kept short enough to fit beside the key and the label without the box+ /// having to grow: the overlay draws unwrapped, so a long phrase here is+ /// silently cut rather than reflowed.+ pub fn describe(&self) -> &'static str {+ match self {+ Reach::Lan => "this wifi only, not mobile data",+ Reach::Tailnet => "anywhere, your devices only",+ }+ }++ /// Why this option cannot be used right now, if it cannot.+ ///+ /// Checked before starting rather than after: a child that exits because+ /// Tailscale is missing surfaces as "the server stopped on its own", which+ /// says nothing about what to install.+ #[cfg(feature = "serve")]+ pub fn unavailable(&self) -> Option<&'static str> {+ match self {+ Reach::Lan => None,+ Reach::Tailnet if !crate::web::tunnel::installed("tailscale") => {+ Some("install Tailscale and sign this machine in")+ }+ Reach::Tailnet if crate::web::tunnel::tailnet_hostname().is_none() => {+ Some("Tailscale is installed but not signed in")+ }+ Reach::Tailnet => None,+ }+ }++ /// A build without the feature can never serve, so both options say so β+ /// and say what to do about it. "This build has no web server" is true and+ /// useless: the reader is left to guess whether that is a bug, a missing+ /// dependency, or something they can fix.+ #[cfg(not(feature = "serve"))]+ pub fn unavailable(&self) -> Option<&'static str> {+ Some("rebuild with `cargo build --release --features serve`")+ }+}++/// A running child server, plus what a person needs to reach it.+pub struct ServeSession {+ child: Child,+ pub url: String,+ pub port: u16,+ pub reach: Reach,+}++impl ServeSession {+ /// Start `agtx serve` for `reach`, seeded with a fresh pairing code.+ ///+ /// The two modes differ in more than a flag. LAN binds every interface and+ /// the URL is this machine's private address. A tunnel leaves the listener+ /// on loopback β Tailscale proxies into it β and the URL is the **tailnet+ /// hostname**, which agtx does not choose and therefore has to ask for.+ /// Both require pairing: `ServeOptions::is_loopback` counts a tunnel as+ /// exposure even though the bind address says otherwise.+ pub fn start(port: u16, reach: Reach) -> Result<Self> {+ let exe = std::env::current_exe().context("locating the agtx binary")?;+ let code = uuid::Uuid::new_v4().simple().to_string();+ // Recorded against every device the child pairs, so a device can be+ // traced back to the session that issued it. Not a lifetime: pairings+ // persist until revoked.+ let session_id = uuid::Uuid::new_v4().to_string();++ let mut args: Vec<String> = vec!["serve".into(), "--port".into(), port.to_string()];+ let url = match reach {+ Reach::Lan => {+ args.push("--host".into());+ args.push("0.0.0.0".into());+ let host = local_ipv4().unwrap_or_else(|| "127.0.0.1".to_string());+ format!("http://{host}:{port}/#pair={code}")+ }+ Reach::Tailnet => {+ args.push("--tunnel".into());+ args.push("private".into());+ let host = tailnet_host().context(+ "could not read this machine's tailnet name from `tailscale status`",+ )?;+ // https, because that is what `tailscale serve --https=443`+ // publishes β and the port is the tunnel's, not the listener's.+ format!("https://{host}/#pair={code}")+ }+ };+ args.push("--pair-code".into());+ args.push(code);+ args.push("--session-id".into());+ args.push(session_id);++ let child = Command::new(exe)+ .args(&args)+ // The TUI owns the screen, so the child's own output must not land+ // on top of the board β but its *errors* are the only place some+ // things are explained. A failed tunnel prints the one-time link+ // that enables Tailscale Serve, and discarding that leaves the+ // overlay able to say only "it stopped", which helps nobody.+ //+ // The overlay only starts LAN or private Tailscale serving, whose+ // stderr is limited to startup errors; the banner and QR use stdout.+ // Before adding public tunnels here, drain stderr continuously:+ // cloudflared forwards ongoing logs through agtx serve's stderr,+ // and waiting until exit would fill this pipe and block the tunnel.+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::piped())+ .spawn()+ .context("starting agtx serve")?;++ Ok(Self {+ child,+ url,+ port,+ reach,+ })+ }++ /// Whether the child is still running.+ ///+ /// `Some(status)` means it exited β most often because the port was already+ /// taken, or this build has no `serve` feature. Either way the overlay has+ /// to stop claiming to be serving.+ /// Whether this URL only resolves inside the local network.+ ///+ /// True for the private ranges β 10/8, 172.16/12, 192.168/16 and the+ /// link-local 169.254/16 β plus loopback. A phone on mobile data has no+ /// route to any of them, so a QR carrying one is a code that scans+ /// perfectly and then times out.+ pub fn is_lan_only(&self) -> bool {+ Self::lan_only_url(&self.url)+ }++ /// Split out so it can be tested against the addresses that matter without+ /// starting a server for each one.+ pub fn lan_only_url(url: &str) -> bool {+ let host = url+ .trim_start_matches("http://")+ .trim_start_matches("https://")+ .split(['/', ':'])+ .next()+ .unwrap_or_default();+ match host.parse::<std::net::Ipv4Addr>() {+ Ok(ip) => ip.is_private() || ip.is_loopback() || ip.is_link_local(),+ // A hostname rather than an address means a tunnel put it there.+ Err(_) => false,+ }+ }++ /// A session wrapping an arbitrary long-lived child, for tests.+ ///+ /// The ownership rule this exists to pin β that closing the overlay must+ /// not stop the server β is only observable with a session present, and the+ /// test that claimed to check it had none. It could never have failed.+ #[cfg(feature = "test-mocks")]+ pub fn for_test(child: Child, url: &str) -> Self {+ Self {+ child,+ url: url.to_string(),+ port: DEFAULT_PORT,+ reach: Reach::Lan,+ }+ }++ pub fn check(&mut self) -> Option<std::process::ExitStatus> {+ self.child.try_wait().ok().flatten()+ }++ /// Whatever the child wrote to stderr before dying.+ ///+ /// Only meaningful once it has exited β reading earlier would block on a+ /// pipe nobody is finished writing to.+ pub fn take_stderr(&mut self) -> String {+ use std::io::Read;+ let Some(mut err) = self.child.stderr.take() else {+ return String::new();+ };+ let mut buf = String::new();+ let _ = err.read_to_string(&mut buf);+ buf.trim().to_string()+ }++ pub fn stop(&mut self) {+ // `Child::kill` sends SIGKILL, which cannot be caught β and the child+ // has cleanup that matters: a tunnel configures the Tailscale daemon,+ // so the exposure outlives the process unless it is torn down. Ask+ // politely first, and only insist if it does not go.+ //+ // Shelling out to `kill` rather than adding a libc dependency for one+ // signal, which is the same trade agtx already makes for tmux and git.+ let _ = Command::new("kill")+ .args(["-TERM", &self.child.id().to_string()])+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();++ // Up to two seconds, polled: a tunnel teardown is a round trip to the+ // local daemon, not an instant thing.+ for _ in 0..20 {+ if matches!(self.child.try_wait(), Ok(Some(_))) {+ return;+ }+ std::thread::sleep(std::time::Duration::from_millis(100));+ }++ let _ = self.child.kill();+ let _ = self.child.wait();+ }+}++impl Drop for ServeSession {+ fn drop(&mut self) {+ self.stop();+ }+}++/// This machine's first non-loopback IPv4.+///+/// Read from the OS rather than parsed out of `ifconfig`: a UDP socket+/// "connected" to an off-machine address makes the kernel pick the outbound+/// interface without sending anything.+pub fn local_ipv4() -> Option<String> {+ let sock = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;+ sock.connect("192.0.2.1:80").ok()?; // TEST-NET-1: routed nowhere+ let ip = sock.local_addr().ok()?.ip();+ match ip {+ IpAddr::V4(v4) if !v4.is_loopback() => Some(v4.to_string()),+ _ => None,+ }+}++#[cfg(feature = "serve")]+fn tailnet_host() -> Option<String> {+ crate::web::tunnel::tailnet_hostname()+}++#[cfg(not(feature = "serve"))]+fn tailnet_host() -> Option<String> {+ None+}++/// The `W` overlay's state.+pub struct MobilePopup {+ /// Devices as of the last refresh, so the list does not hit the database+ /// on every frame.+ pub devices: Vec<crate::db::MobileDevice>,+ pub selected: usize,+ /// A one-line result of the last action, shown under the list.+ pub message: Option<String>,+}++impl MobilePopup {+ pub fn new() -> Self {+ let mut popup = Self {+ devices: Vec::new(),+ selected: 0,+ message: None,+ };+ popup.reload_devices();+ popup+ }++ pub fn reload_devices(&mut self) {+ self.devices = crate::db::Database::open_global()+ .and_then(|db| db.list_mobile_devices())+ .unwrap_or_default();+ self.selected = self.selected.min(self.devices.len().saturating_sub(1));+ }++ /// Stop serving if running; otherwise start with the given reach.+ ///+ /// Each key does a whole thing β `s` serves to this wifi, `t` serves via+ /// the tailnet β rather than one key setting a mode another key acts on.+ /// A hidden mode means neither label can say what pressing it will+ /// actually do, and the answer to "why can my phone not see this" was one+ /// keypress of invisible state away.+ pub fn serve(&mut self, session: &mut Option<ServeSession>, port: u16, reach: Reach) {+ if session.is_some() {+ *session = None; // dropping stops the child+ self.message = Some("Stopped serving.".to_string());+ return;+ }+ if let Some(why) = reach.unavailable() {+ self.message = Some(format!("Cannot serve to the {}: {why}.", reach.label()));+ return;+ }+ match ServeSession::start(port, reach) {+ Ok(started) => {+ *session = Some(started);+ self.message = None;+ }+ Err(e) => self.message = Some(format!("Could not start: {e}")),+ }+ }++ /// Notice a child that exited on its own β a taken port, or a build without+ /// the `serve` feature. Returns whether anything changed.+ pub fn poll_session(&mut self, session: &mut Option<ServeSession>) -> bool {+ let exited = session.as_mut().and_then(|s| s.check()).is_some();+ if !exited {+ return false;+ }++ // Relay what the child said. It knows things the TUI does not β that+ // the port is taken, or that Tailscale Serve is disabled for this+ // tailnet and the one-time link that enables it.+ let detail = session+ .as_mut()+ .map(|s| s.take_stderr())+ .unwrap_or_default();+ *session = None;++ self.message = Some(if detail.is_empty() {+ "The server stopped. The port may be in use, or this build lacks the `serve` feature."+ .to_string()+ } else {+ // Last line first: anyhow prints `Error: <context>` then the cause,+ // and the cause is the part that says what to do.+ let line = detail.lines().rfind(|l| !l.trim().is_empty());+ format!("Server stopped: {}", line.unwrap_or(&detail))+ });+ true+ }++ pub fn revoke_selected(&mut self) {+ let Some(device) = self.devices.get(self.selected).cloned() else {+ return;+ };+ let revoked = crate::db::Database::open_global()+ .and_then(|db| db.revoke_mobile_device(&device.id))+ .unwrap_or(false);+ self.message = Some(if revoked {+ format!(+ "Revoked β{}β. It must scan a new code to return.",+ device.label+ )+ } else {+ format!("Could not revoke β{}β.", device.label)+ });+ self.reload_devices();+ }++ pub fn move_selection(&mut self, delta: isize) {+ if self.devices.is_empty() {+ return;+ }+ let last = self.devices.len() - 1;+ self.selected = match delta {+ d if d < 0 => self.selected.saturating_sub(d.unsigned_abs()),+ d => (self.selected + d as usize).min(last),+ };+ }+}++/// The QR module grid for a pairing URL.+///+/// The **grid**, not the ANSI rendering: ratatui does not interpret escape+/// sequences, so `qr::render`'s output would be drawn as literal garbage. The+/// overlay turns these modules into styled spans instead.+#[cfg(feature = "serve")]+pub fn qr_grid(url: &str) -> Option<(usize, Vec<bool>)> {+ crate::web::qr::grid(url)+}++#[cfg(not(feature = "serve"))]+pub fn qr_grid(_url: &str) -> Option<(usize, Vec<bool>)> {+ None+}++impl Default for MobilePopup {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/src/web/assets.rs b/src/web/assets.rsnew file mode 100644index 0000000..fa883be--- /dev/null+++ b/src/web/assets.rs@@ -0,0 +1,94 @@+//! The PWA, compiled into the binary.+//!+//! Embedded with `include_bytes!` rather than a bundler-plus-`rust-embed`+//! pipeline, for three reasons that all point the same way:+//!+//! - **There is nothing to bundle.** The app is plain ES modules with no npm+//! dependency, which every browser that can install a PWA loads natively.+//! - **A missing file is a compile error.** A path table checked at build time+//! cannot drift from what is on disk; a directory glob resolved at runtime+//! 404s instead, and only for whoever hits that asset. Note the guarantee runs+//! one way β a *listed* file must exist, but nothing here makes every file on+//! disk listed. A new module left out of this table 404s to the SPA shell, and+//! an ES import that receives HTML fails the whole app with a blank page.+//! `the_asset_table_covers_the_web_directory` is what closes that direction.+//! - **No build artifact means nothing can be stale.** The alternative β+//! committing `web/dist/` and adding a CI job to catch a stale copy β exists+//! only to police a build step that this does not have.+//!+//! It also matches how `src/skills.rs` embeds the builtin skills, so there is+//! one answer in this codebase to "where do bundled files live".+//!+//! When Step 4 adds xterm.js, vendor it here as one more file rather than+//! introducing a toolchain to produce it.++/// One embedded file: request path, content type, bytes.+pub struct Asset {+ pub path: &'static str,+ pub mime: &'static str,+ pub body: &'static [u8],+}++/// Serving `index.html` at `/` is what makes a bare tunnel hostname work.+pub const INDEX: &str = "index.html";++pub const ASSETS: &[Asset] = &[+ Asset {+ path: "index.html",+ mime: "text/html; charset=utf-8",+ body: include_bytes!("../../web/index.html"),+ },+ Asset {+ path: "app.css",+ mime: "text/css; charset=utf-8",+ body: include_bytes!("../../web/app.css"),+ },+ // `text/javascript` and not `application/javascript`: a module script+ // served as the latter is fine, but a browser refuses any `type="module"`+ // whose MIME is not a JavaScript type, and this is the spelling the HTML+ // spec names. Getting it wrong fails the whole app with a console error+ // and a blank page.+ Asset {+ path: "app.js",+ mime: "text/javascript; charset=utf-8",+ body: include_bytes!("../../web/app.js"),+ },+ Asset {+ path: "ansi.js",+ mime: "text/javascript; charset=utf-8",+ body: include_bytes!("../../web/ansi.js"),+ },+ Asset {+ path: "api.js",+ mime: "text/javascript; charset=utf-8",+ body: include_bytes!("../../web/api.js"),+ },+ Asset {+ path: "sw.js",+ mime: "text/javascript; charset=utf-8",+ body: include_bytes!("../../web/sw.js"),+ },+ Asset {+ path: "manifest.webmanifest",+ mime: "application/manifest+json",+ body: include_bytes!("../../web/manifest.webmanifest"),+ },+ Asset {+ path: "icon-192.png",+ mime: "image/png",+ body: include_bytes!("../../web/icon-192.png"),+ },+ Asset {+ path: "icon-512.png",+ mime: "image/png",+ body: include_bytes!("../../web/icon-512.png"),+ },+];++/// Look up an asset by request path, with `""` and `index.html` both meaning+/// the shell.+pub fn find(path: &str) -> Option<&'static Asset> {+ let path = path.trim_start_matches('/');+ let path = if path.is_empty() { INDEX } else { path };+ ASSETS.iter().find(|a| a.path == path)+}diff --git a/src/web/auth.rs b/src/web/auth.rsnew file mode 100644index 0000000..4b105fa--- /dev/null+++ b/src/web/auth.rs@@ -0,0 +1,290 @@+//! Pairing, and the per-device tokens it issues.+//!+//! Without a credential the honest answer to "bind me to the network" is no:+//! anything that reaches this server can read every task diff, watch every+//! agent pane, and type into a running agent.+//!+//! Shape, and why each part is the way it is:+//!+//! - **One token per device**, hashed at rest in `mobile_devices`. A single+//! shared secret cannot be taken back from one lost phone without cutting off+//! every other device at the same time.+//! - **Pairing codes are short-lived, single-use and in memory only.** They+//! never touch disk because they are only alive for the seconds between the+//! QR appearing and a phone scanning it.+//! - **Static assets are open; `/api/*` and `/ws` are not.** A browser cannot+//! put a header on the initial page load, so gating the shell would mean+//! putting a credential in the URL of every navigation. The assets are the+//! application's own JS and CSS and carry no board data.+//! - **Secrets travel in the URL fragment**, which browsers do not transmit, so+//! they stay out of proxy and server logs. The page moves them to local+//! storage and replaces the hash.++use std::path::PathBuf;++use anyhow::{Context, Result};++/// Where the token lives. Beside `config.toml` rather than in the platform data+/// dir β see the config-path split in CLAUDE.md β and honouring+/// `AGTX_CONFIG_DIR` so tests never touch the real one.+pub fn token_path() -> Result<PathBuf> {+ let cfg = crate::config::GlobalConfig::config_path()?;+ Ok(cfg+ .parent()+ .context("config path has no parent")?+ .join("serve-token"))+}++/// Load the legacy single token, creating one on first use.+///+/// Superseded by per-device pairing; kept only so an already-paired phone+/// survives the upgrade β see [`migrate_legacy_token`].+pub fn load_or_create() -> Result<String> {+ let path = token_path()?;+ if let Ok(existing) = std::fs::read_to_string(&path) {+ let trimmed = existing.trim().to_string();+ if !trimmed.is_empty() {+ return Ok(trimmed);+ }+ }++ let token = generate();+ if let Some(dir) = path.parent() {+ std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;+ }+ std::fs::write(&path, &token).with_context(|| format!("writing {}", path.display()))?;+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));+ }+ Ok(token)+}++/// 192 bits, hex, from the OS.+///+/// `getrandom` via `uuid`'s v4 generator rather than a hand-rolled PRNG: agtx+/// already depends on it, and a token seeded from the clock is the classic way+/// to make a credential guessable.+fn generate() -> String {+ let a = uuid::Uuid::new_v4().simple().to_string();+ let b = uuid::Uuid::new_v4().simple().to_string();+ format!("{a}{}", &b[..16])+}++/// Whether `presented` matches `expected`, compared in constant time.+///+/// A byte-by-byte `==` returns early on the first difference, which leaks the+/// length of the matching prefix to anyone who can time the response. That is a+/// thin channel over a network but a real one, and the fix costs nothing.+pub fn token_matches(expected: &str, presented: &str) -> bool {+ let (a, b) = (expected.as_bytes(), presented.as_bytes());+ if a.len() != b.len() {+ return false;+ }+ let mut diff = 0u8;+ for (x, y) in a.iter().zip(b) {+ diff |= x ^ y;+ }+ diff == 0+}++/// The `Sec-WebSocket-Protocol` value carrying a token.+///+/// A browser cannot set `Authorization` on a WebSocket handshake, and a query+/// parameter would put the token in exactly the logs the fragment avoids. The+/// subprotocol header is the one client-settable field on that handshake.+pub const WS_TOKEN_PREFIX: &str = "agtx.token.";++// ββ pairing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++use std::collections::HashMap;+use std::sync::Mutex;+use std::time::{Duration, Instant};++use crate::db::{Database, MobileDevice};++/// How long a pairing code is good for.+///+/// Short because the code's whole life is the seconds between a QR appearing+/// in a terminal and a phone scanning it. A code that outlives the person+/// standing in front of the screen is a credential nobody is watching.+pub const PAIRING_TTL: Duration = Duration::from_secs(120);++/// Failed `/api/pair` attempts before pairing is shut until the next code.+///+/// A code is 128 bits, so guessing is hopeless on arithmetic alone β but+/// `/api/pair` is the one unauthenticated route, and letting it be hammered+/// freely is how a rate-limit oversight becomes the interesting part of an+/// incident report.+pub const PAIRING_MAX_FAILURES: u32 = 10;++/// Codes waiting to be exchanged. In memory only, deliberately.+#[derive(Default)]+pub struct PairingCodes {+ codes: Mutex<HashMap<String, Instant>>,+ failures: Mutex<u32>,+}++/// Why a pairing attempt was refused. Distinct cases because the fix differs:+/// a stale code means scan again, a locked-out server means restart it.+#[derive(Debug, PartialEq, Eq)]+pub enum PairError {+ Unknown,+ Expired,+ LockedOut,+}++impl PairError {+ pub fn message(&self) -> &'static str {+ match self {+ PairError::Unknown => "that pairing code is not valid; scan the current QR code",+ PairError::Expired => "that pairing code has expired; restart agtx serve for a new one",+ PairError::LockedOut => {+ "too many failed pairing attempts; restart agtx serve to pair again"+ }+ }+ }+}++impl PairingCodes {+ /// Adopt a code minted elsewhere.+ ///+ /// The TUI generates the code so it can build the pairing URL β and draw+ /// its QR β before the child server has started. The alternative is parsing+ /// the URL back out of the child's stdout, which makes a human-readable+ /// banner load-bearing and breaks quietly when its wording changes.+ pub fn seed(&self, code: &str) {+ let mut codes = self.codes.lock().unwrap_or_else(|e| e.into_inner());+ codes.insert(code.to_string(), Instant::now());+ }++ /// Mint a code and remember it until it is used or expires.+ pub fn issue(&self) -> String {+ let code = uuid::Uuid::new_v4().simple().to_string();+ let mut codes = self.codes.lock().unwrap_or_else(|e| e.into_inner());+ codes.retain(|_, issued| issued.elapsed() < PAIRING_TTL);+ codes.insert(code.clone(), Instant::now());+ code+ }++ /// Spend a code. Removed whether or not it had expired: a code presented+ /// once is finished either way, and leaving an expired one in the map lets+ /// it be retried until the sweep.+ pub fn redeem(&self, code: &str) -> Result<(), PairError> {+ {+ let failures = self.failures.lock().unwrap_or_else(|e| e.into_inner());+ if *failures >= PAIRING_MAX_FAILURES {+ return Err(PairError::LockedOut);+ }+ }++ let mut codes = self.codes.lock().unwrap_or_else(|e| e.into_inner());+ match codes.remove(code) {+ Some(issued) if issued.elapsed() < PAIRING_TTL => {+ *self.failures.lock().unwrap_or_else(|e| e.into_inner()) = 0;+ Ok(())+ }+ Some(_) => Err(PairError::Expired),+ None => {+ *self.failures.lock().unwrap_or_else(|e| e.into_inner()) += 1;+ Err(PairError::Unknown)+ }+ }+ }+}++/// Mint a device token, store its hash, and hand the token back.+///+/// The token is returned exactly once and never stored β only its hash β so a+/// device that loses it has to pair again rather than ask for it back.+///+/// `session_id` records which serve session paired it. The pairing itself+/// persists until revoked.+pub fn pair_device(label: &str, session_id: Option<&str>) -> Result<String> {+ let token = generate();+ let mut device = MobileDevice::new(sanitise_label(label), sha(&token));+ device.session_id = session_id.map(str::to_string);+ Database::open_global()+ .context("opening the global database")?+ .add_mobile_device(&device)+ .context("storing the paired device")?;+ Ok(token)+}++/// The device this token belongs to, if any.+pub fn device_for_token(token: &str) -> Option<MobileDevice> {+ Database::open_global()+ .ok()?+ .mobile_device_by_hash(&sha(token))+ .ok()+ .flatten()+}++pub fn sha(token: &str) -> String {+ crate::update::install::sha256_hex(token.as_bytes())+}++/// A label is shown in a device list and nowhere else, so the only rules are+/// that it exists and cannot flood the display.+fn sanitise_label(label: &str) -> String {+ let cleaned: String = label+ .chars()+ .filter(|c| !c.is_control())+ .take(60)+ .collect::<String>()+ .trim()+ .to_string();+ if cleaned.is_empty() {+ "phone".to_string()+ } else {+ cleaned+ }+}++/// Adopt an existing `serve-token` as a paired device, once.+///+/// Without this the move to per-device tokens would silently stop an+/// already-paired phone from connecting, with nothing on screen to explain why.+/// The file is removed afterwards so there is exactly one credential path.+///+/// The adopted device records `session_id` like any other.+pub fn migrate_legacy_token(session_id: Option<&str>) -> Result<Option<String>> {+ let path = token_path()?;+ let Ok(existing) = std::fs::read_to_string(&path) else {+ return Ok(None);+ };+ let token = existing.trim().to_string();+ if token.is_empty() {+ let _ = std::fs::remove_file(&path);+ return Ok(None);+ }++ let db = Database::open_global().context("opening the global database")?;+ if db.mobile_device_by_hash(&sha(&token))?.is_none() {+ let mut device = MobileDevice::new("previously paired device", sha(&token));+ device.session_id = session_id.map(str::to_string);+ db.add_mobile_device(&device)?;+ }+ let _ = std::fs::remove_file(&path);+ Ok(Some(token))+}++/// Shared by the HTTP gate and the socket's ongoing authorization checks.+pub fn presented_token(headers: &axum::http::HeaderMap) -> Option<&str> {+ use axum::http::header;+ headers+ .get(header::AUTHORIZATION)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| v.strip_prefix("Bearer "))+ .or_else(|| {+ headers+ .get(header::SEC_WEBSOCKET_PROTOCOL)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| {+ v.split(',')+ .map(str::trim)+ .find_map(|p| p.strip_prefix(WS_TOKEN_PREFIX))+ })+ })+}diff --git a/src/web/mod.rs b/src/web/mod.rsnew file mode 100644index 0000000..0a689d8--- /dev/null+++ b/src/web/mod.rs@@ -0,0 +1,296 @@+//! `agtx serve` β the board over HTTP.+//!+//! The server never links `App`. It reads SQLite, git and tmux, exactly as the+//! MCP server does, so it can run beside a TUI or without one. What it cannot+//! do is *execute* a transition: that machinery lives on `App` (see the mobile+//! plan's "one hard constraint"), which is why the heartbeat exists β a client+//! must be able to tell a queued tap from a completed one.++pub mod assets;+pub mod auth;+pub mod qr;+pub mod routes;+pub mod state;+pub mod tunnel;+pub mod writes;+pub mod ws;++use std::net::{IpAddr, SocketAddr};+use std::path::PathBuf;++use anyhow::{bail, Context, Result};++pub use state::{ServeMode, ServerState};++/// How `agtx serve` was invoked.+pub struct ServeOptions {+ pub project_path: Option<PathBuf>,+ pub host: IpAddr,+ pub port: u16,+ /// How far to expose the board, if at all.+ pub tunnel: Option<tunnel::TunnelScope>,+ /// A pairing code supplied by the caller rather than minted here.+ ///+ /// Set when the TUI launches the server: it needs the URL β and the QR β+ /// before the child exists.+ pub pair_code: Option<String>,+ /// Identifies this serve session in `mobile_devices`.+ ///+ /// Stamped on every device paired here, so a device can be traced back to+ /// the server that issued it. Minted on startup when the caller supplies+ /// none. Pairings themselves persist until revoked.+ ///+ /// Deliberately **not** the pairing code: that is a credential, and a+ /// credential does not belong in a column that outlives its use.+ pub session_id: Option<String>,+}++impl Default for ServeOptions {+ fn default() -> Self {+ Self {+ project_path: None,+ // Loopback, always, until a caller says otherwise. Anyone who+ // reaches this server can read every task, diff and agent pane on+ // the machine.+ host: IpAddr::from([127, 0, 0, 1]),+ port: 8787,+ tunnel: None,+ pair_code: None,+ session_id: None,+ }+ }+}++impl ServeOptions {+ /// Whether anything beyond this machine can reach the board.+ ///+ /// A tunnel counts even though the listener stays on loopback: the provider+ /// proxies into it, so the exposure is real and pairing must be required.+ /// Reading only the bind address here is how a tunnelled server ends up+ /// unauthenticated.+ pub fn is_loopback(&self) -> bool {+ self.host.is_loopback() && self.tunnel.is_none()+ }+}++pub async fn serve(opts: ServeOptions) -> Result<()> {+ // Off-loopback needs a credential, full stop. This exposes task+ // descriptions, whole diffs, live agent panes, and an endpoint that types+ // into a running agent β on a shared network that is arbitrary code+ // execution for anyone who finds the port. The token is what makes `--host`+ // answerable; without one the honest reply is still no.+ // Loopback is its own boundary: reaching it already means being on this+ // machine, where the tmux socket and the databases are readable anyway. So+ // no pairing there β it would mean scanning a code to open a board on the+ // machine already running it, for no gain. Off-loopback, pairing is what+ // makes the bind answerable at all.+ let require_auth = !opts.is_loopback();++ // Recorded on every device this server pairs. Provenance rather than a+ // lifetime: pairings persist until revoked. It is what a forget-on-exit or+ // expiry policy would delete by, and scoping such a delete is not optional+ // β `mobile_devices` is global, so a second agtx serving another project+ // must keep its own devices.+ let session_id = opts+ .session_id+ .clone()+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());++ // An already-paired phone must survive the move from the single shared+ // token to per-device ones. Without this it would simply stop connecting,+ // with nothing on screen to say why.+ if require_auth {+ match auth::migrate_legacy_token(Some(&session_id)) {+ Ok(Some(_)) => println!(" adopted the previous access token as a paired device"),+ Ok(None) => {}+ Err(e) => tracing::warn!(error = %e, "could not migrate the legacy access token"),+ }+ }++ let mode = match &opts.project_path {+ Some(path) => {+ let path = path+ .canonicalize()+ .with_context(|| format!("resolving {}", path.display()))?;+ if !crate::git::is_git_repo(&path) {+ bail!("serve requires a git project directory: {}", path.display());+ }+ ServeMode::Project(path)+ }+ None => ServeMode::Global,+ };++ // Start the tunnel before the listener so a provider that is missing or+ // refuses fails here, rather than after printing a QR for a URL that will+ // never resolve.+ let mut public_base: Option<String> = None;+ let _tunnel = match opts.tunnel {+ Some(scope) => {+ let port = opts.port;+ // Provider discovery and startup run subprocesses; cloudflared may+ // also take up to 30 seconds to report its public hostname.+ let started = tokio::task::spawn_blocking(move || {+ let plan = tunnel::plan(scope, port, &tunnel::installed)?;+ let started = tunnel::Tunnel::start(&plan)?;+ println!("tunnel: {} β reachable from {}", plan.program, plan.reach);+ Ok::<_, anyhow::Error>(started)+ })+ .await+ .context("joining tunnel startup")??;+ public_base = started.public_url.clone();+ Some(started)+ }+ None => None,+ };++ let state = ServerState::with_session(mode, require_auth, Some(session_id.clone()));++ // A code exists only while someone is looking at the terminal it was+ // printed in, so it is minted here rather than on demand.+ let pairing_code = if require_auth {+ Some(match &opts.pair_code {+ Some(supplied) => {+ state.pairing.seed(supplied);+ supplied.clone()+ }+ None => state.pairing.issue(),+ })+ } else {+ None+ };++ let app = routes::router(state.clone());++ let addr = SocketAddr::new(opts.host, opts.port);+ let listener = tokio::net::TcpListener::bind(addr)+ .await+ .with_context(|| format!("binding {addr}"))?;++ // The bound address rather than the requested one: port 0 is how a test or+ // a second instance asks the OS to pick, and the answer is only known here.+ let bound = listener.local_addr().unwrap_or(addr);+ print_banner(+ &bound,+ public_base.as_deref(),+ pairing_code.as_deref(),+ opts.is_loopback(),+ );+ tracing::info!(addr = %bound, loopback = opts.is_loopback(), "web server started");++ // Graceful shutdown is not a nicety here β it is what makes the tunnel+ // teardown run at all. `tailscale serve` configures the *daemon*, so the+ // exposure outlives this process, and `Tunnel`'s `Drop` is the only thing+ // that removes it. Rust does not run destructors on a signal, so without+ // this a Ctrl-C or a `kill` leaves the board published on the tailnet with+ // nothing serving it.+ axum::serve(listener, app)+ .with_graceful_shutdown(shutdown_signal())+ .await+ .context("web server stopped")?;+ Ok(())+}++/// Resolve on Ctrl-C or `SIGTERM`.+///+/// Both, because they arrive from different places and mean the same thing: a+/// person pressing Ctrl-C in the terminal, and the TUI stopping the child it+/// spawned for the `W` overlay.+async fn shutdown_signal() {+ let ctrl_c = async {+ let _ = tokio::signal::ctrl_c().await;+ };++ #[cfg(unix)]+ let terminate = async {+ match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {+ Ok(mut sig) => {+ sig.recv().await;+ }+ // Nothing to do but wait for Ctrl-C instead; a server that refuses+ // to start because it could not install a handler is worse.+ Err(e) => {+ tracing::warn!(error = %e, "could not listen for SIGTERM");+ std::future::pending::<()>().await;+ }+ }+ };++ #[cfg(not(unix))]+ let terminate = std::future::pending::<()>();++ tokio::select! {+ _ = ctrl_c => {}+ _ = terminate => {}+ }+ println!("shutting down");+}++/// What to print so the URL can be typed into a phone.+///+/// The token goes in the **fragment**, which browsers do not transmit: the page+/// reads it, stores it, and strips it from the address bar. Putting it in the+/// path or the query would write the credential into every access log between+/// here and the browser.+fn print_banner(+ bound: &SocketAddr,+ public_base: Option<&str>,+ pairing_code: Option<&str>,+ loopback: bool,+) {+ let host = if bound.ip().is_unspecified() {+ // `0.0.0.0` is not an address anything can open. Name a real one, or+ // the user is left to work out their own LAN address.+ local_ipv4().unwrap_or_else(|| bound.ip().to_string())+ } else {+ bound.ip().to_string()+ };++ // A tunnel's hostname, when there is one. Without this the banner prints+ // the *bound* address β which for a tunnel is loopback, so the QR would+ // carry `http://127.0.0.1:β¦` and be useless to the phone it was drawn for.+ let base = match public_base {+ Some(b) => b.to_string(),+ None => format!("http://{host}:{}", bound.port()),+ };+ let url = match pairing_code {+ Some(code) => format!("{base}/#pair={code}"),+ None => format!("{base}/"),+ };++ println!("agtx serve listening on {base}");++ // The QR is for a *phone*, so it is printed only when one could reach this+ // server. On loopback the URL resolves to the machine already running it,+ // and a code for `127.0.0.1` scans perfectly and goes nowhere.+ if !loopback {+ match qr::render(&url) {+ Some(code) => {+ println!();+ print!("{code}");+ println!();+ }+ None => tracing::warn!("could not encode the pairing URL as a QR code"),+ }+ }++ println!(" scan to pair: {url}");+ if pairing_code.is_some() {+ println!(+ " the code is single-use and lasts {}s; already-paired devices need nothing",+ auth::PAIRING_TTL.as_secs()+ );+ println!(" reachable by anything on this network β that includes typing into your agents");+ }+}++/// This machine's first non-loopback IPv4, for the banner.+///+/// Read from the OS rather than guessed: `hostname -I` is Linux-only and+/// `ifconfig` output differs per platform, while a UDP socket "connected" to an+/// off-machine address makes the kernel pick the outbound interface without+/// sending anything.+fn local_ipv4() -> Option<String> {+ let sock = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;+ sock.connect("192.0.2.1:80").ok()?; // TEST-NET-1: routed nowhere+ Some(sock.local_addr().ok()?.ip().to_string())+}diff --git a/src/web/qr.rs b/src/web/qr.rsnew file mode 100644index 0000000..27a8faf--- /dev/null+++ b/src/web/qr.rs@@ -0,0 +1,97 @@+//! The pairing URL as a QR code, for a terminal.+//!+//! The alternative is typing `http://192.168.178.26:8787/#token=<48 hex chars>`+//! into a phone, which nobody should be asked to do twice.++use qrcode::{EcLevel, QrCode};++/// Two module rows per character cell.+///+/// A terminal cell is about twice as tall as it is wide, so one module per cell+/// gives a QR stretched 2:1 β scannable by a patient phone, but only just.+/// `β` splits a cell into an upper and a lower pixel, coloured independently,+/// which restores square modules and halves the height. A version-5 code then+/// fits in ~23 rows instead of ~45.+const UPPER_HALF: char = 'β';++/// White, then black, as basic ANSI rather than truecolor.+///+/// The colours are set explicitly rather than left to the terminal because a QR+/// has to be dark-on-light to scan reliably, and half of all terminals are+/// dark-on-light the other way round. Basic ANSI (not 24-bit) because this only+/// needs two colours and every terminal has had these since the 1980s.+const FG_LIGHT: &str = "\x1b[97m";+const FG_DARK: &str = "\x1b[30m";+const BG_LIGHT: &str = "\x1b[107m";+const BG_DARK: &str = "\x1b[40m";+const RESET: &str = "\x1b[0m";++/// Modules of light border around the code.+///+/// Four is the specified minimum quiet zone. Dropping it is the classic reason+/// a QR that "looks fine" will not scan: without the border a decoder cannot+/// find the code's edges against whatever is printed around it.+const QUIET: usize = 4;++/// The module grid, including its quiet zone.+///+/// Returns `(width, dark)` where `dark[y * width + x]` is true for a dark+/// module. Separate from [`render`] because the two consumers need different+/// output and neither should re-derive the layout: the CLI banner wants ANSI+/// escapes, while a ratatui overlay needs styled spans and would draw those+/// escapes as literal garbage.+pub fn grid(data: &str) -> Option<(usize, Vec<bool>)> {+ // Low error correction: this is displayed on a screen a few inches from the+ // camera, not printed on a box that might get scuffed. Lower correction+ // means fewer modules, which means a smaller code in a terminal where+ // vertical space is the scarce thing.+ let code = QrCode::with_error_correction_level(data, EcLevel::L).ok()?;+ let width = code.width();+ let modules: Vec<bool> = code+ .into_colors()+ .iter()+ .map(|c| *c == qrcode::Color::Dark)+ .collect();++ let total = width + QUIET * 2;+ let mut padded = vec![false; total * total];+ for y in 0..width {+ for x in 0..width {+ padded[(y + QUIET) * total + (x + QUIET)] = modules[y * width + x];+ }+ }+ Some((total, padded))+}++/// Render `data` as a QR code using half-block characters and ANSI colour.+///+/// For a terminal that interprets escapes β the `agtx serve` banner. A ratatui+/// widget must use [`grid`] instead.+///+/// `None` when the data will not fit any QR version, which for a URL means+/// something has gone very wrong upstream β a caller should fall back to+/// printing the URL rather than treating it as fatal.+pub fn render(data: &str) -> Option<String> {+ // Low error correction: this is displayed on a screen a few inches from the+ // camera, not printed on a box that might get scuffed. Lower correction+ // means fewer modules, which means a smaller code in a terminal where+ // vertical space is the scarce thing.+ let (total, dark) = grid(data)?;+ let dark_at = |x: usize, y: usize| -> bool { dark[y * total + x] };++ let mut out = String::new();+ // Two module rows per line; an odd final row pairs with a light one, which+ // is what the quiet zone would have been anyway.+ for row in (0..total).step_by(2) {+ for x in 0..total {+ let upper = dark_at(x, row);+ let lower = row + 1 < total && dark_at(x, row + 1);+ out.push_str(if upper { FG_DARK } else { FG_LIGHT });+ out.push_str(if lower { BG_DARK } else { BG_LIGHT });+ out.push(UPPER_HALF);+ }+ out.push_str(RESET);+ out.push('\n');+ }+ Some(out)+}diff --git a/src/web/routes.rs b/src/web/routes.rsnew file mode 100644index 0000000..96cf805--- /dev/null+++ b/src/web/routes.rs@@ -0,0 +1,656 @@+//! The read-only half of the HTTP surface.+//!+//! Every handler here reads: SQLite, git and tmux, the same three things the+//! MCP server talks to. Nothing in this module links `App` or mutates the+//! board β writes arrive in Step 3 of the mobile plan.++use std::sync::Arc;++use axum::{+ extract::{Path, Query, Request, State},+ http::{header, StatusCode, Uri},+ middleware::{self, Next},+ response::{IntoResponse, Response},+ routing::{get, patch, post},+ Json, Router,+};+use serde::{Deserialize, Serialize};++use crate::core::actions::{allowed_actions, CallerKind};+use crate::db::{Database, PhaseStatus, Task};++use super::state::{ApiError, ApiResult, ConflictState, ServeMode, ServerState};++/// Reject an unauthenticated `/api/*` or `/ws` request.+///+/// Layered over the API routes only. The static assets stay open because a+/// browser cannot put a header on the initial page load, and gating them would+/// mean carrying the token in the URL of every navigation β see+/// [`super::auth`]. They are this app's own JS and CSS and expose no board.+async fn require_token(+ State(state): State<Arc<ServerState>>,+ req: Request,+ next: Next,+) -> Response {+ // Two places a token can be, because a browser cannot put `Authorization`+ // on a WebSocket handshake β the subprotocol is the one field it *can* set+ // there. Both are checked here rather than one here and one in the socket+ // handler: `WebSocketUpgrade` is an extractor, so a handler-side check runs+ // only after the upgrade has been accepted, and an exemption in this layer+ // to let that happen is an open socket for as long as anyone forgets why.+ let presented = super::auth::presented_token(req.headers());++ if state.token_ok(presented) {+ next.run(req).await+ } else {+ (+ StatusCode::UNAUTHORIZED,+ Json(serde_json::json!({+ "error": "missing or wrong token. Open the URL agtx printed at startup, \+ which carries it in the fragment."+ })),+ )+ .into_response()+ }+}++pub fn router(state: Arc<ServerState>) -> Router {+ Router::new()+ .route("/api/health", get(health))+ .route("/api/projects", get(projects))+ .route("/api/projects/{pid}/tasks", get(tasks))+ .route("/api/projects/{pid}/tasks/{tid}", get(task_detail))+ .route("/api/projects/{pid}/tasks/{tid}/diff", get(task_diff))+ .route("/api/projects/{pid}/tasks/{tid}/pane", get(task_pane))+ // Writes. None of these execute anything: an action becomes a queued+ // transition request, and task CRUD touches only the task table.+ .route(+ "/api/projects/{pid}/tasks/{tid}/action",+ post(super::writes::task_action),+ )+ .route(+ "/api/projects/{pid}/requests/{rid}",+ get(super::writes::request_status),+ )+ .route(+ "/api/projects/{pid}/tasks/{tid}/input",+ post(super::writes::task_input),+ )+ .route(+ "/api/projects/{pid}/tasks",+ post(super::writes::create_task),+ )+ // Live pane frames. Not under `/api` because it is not a JSON endpoint+ // and the fallback's `/api/` guard would have to special-case it.+ // Inside the auth layer, unlike the static assets: the token check has+ // to happen before the upgrade is accepted.+ .route("/ws", get(super::ws::handler))+ .route(+ "/api/projects/{pid}/tasks/{tid}",+ patch(super::writes::update_task).delete(super::writes::delete_task),+ )+ // Pairing is the one unauthenticated route β it is how a device gets a+ // credential in the first place β so it is registered *outside* the+ // auth layer, alongside the static shell.+ .layer(middleware::from_fn_with_state(state.clone(), require_token))+ .route("/api/pair", post(super::writes::pair))+ .with_state(state)+ // The PWA, last: `/api/*` is matched first, so an asset can never+ // shadow a route, and an unknown `/api/...` path still 404s as HTML β+ // and the fallback sits *outside* the auth layer, so the shell loads+ // before the page has a token to present.+ .fallback(asset)+}++// ββ the embedded PWA ββββββββββββββββββββββββββββββββββββββββββββββββββββ++async fn asset(uri: Uri) -> Response {+ let path = uri.path();+ // An unmatched `/api/...` is a client bug, not a deep link. Answering it+ // with `index.html` would hand a `fetch` a 200 full of HTML, which fails+ // as a JSON parse error somewhere unrelated.+ if path.starts_with("/api/") {+ return ApiError::NotFound(format!("no such endpoint: {path}")).into_response();+ }++ match super::assets::find(path) {+ Some(a) => (+ [+ (header::CONTENT_TYPE, a.mime),+ // The shell is embedded in the binary, so its lifetime is the+ // binary's: `agtx update` replaces both together. Revalidating+ // costs one conditional request and removes any chance of a+ // cached UI outliving the API it was built against.+ (header::CACHE_CONTROL, "no-cache"),+ ],+ a.body,+ )+ .into_response(),+ // Hash routing means every real screen is `/#/...`, so any other path+ // is a typo or a probe β but returning the shell keeps a deep link+ // working if routing ever moves into the path.+ None => match super::assets::find(super::assets::INDEX) {+ Some(index) => (+ [+ (header::CONTENT_TYPE, index.mime),+ (header::CACHE_CONTROL, "no-cache"),+ ],+ index.body,+ )+ .into_response(),+ None => ApiError::Internal("web assets missing from this build".into()).into_response(),+ },+ }+}++// ββ /api/health βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+struct Health {+ version: &'static str,+ mode: &'static str,+ project_count: usize,+ /// Whether a TUI is currently draining the transition queue. In global mode+ /// this is true when *any* indexed project has a live heartbeat β a phone+ /// on the projects screen is asking "will anything happen if I tap", and+ /// per-project truth is on the board response.+ tui_connected: bool,+}++async fn health(State(state): State<Arc<ServerState>>) -> ApiResult<Json<Health>> {+ let global =+ Database::open_global().map_err(|e| ApiError::Internal(format!("global database: {e}")))?;+ let projects = visible_projects(&state, &global)?;++ let live = match &state.mode {+ ServeMode::Project(path) => global+ .tui_is_live(&path.to_string_lossy(), state.heartbeat_ttl)+ .unwrap_or(false),+ ServeMode::Global => projects.iter().any(|p| {+ global+ .tui_is_live(&p.path, state.heartbeat_ttl)+ .unwrap_or(false)+ }),+ };++ Ok(Json(Health {+ version: env!("CARGO_PKG_VERSION"),+ mode: match state.mode {+ ServeMode::Project(_) => "project",+ ServeMode::Global => "global",+ },+ project_count: projects.len(),+ tui_connected: live,+ }))+}++// ββ /api/projects βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+struct ProjectSummary {+ id: String,+ name: String,+ path: String,+ last_opened: String,+ tui_connected: bool,+}++async fn projects(State(state): State<Arc<ServerState>>) -> ApiResult<Json<Vec<ProjectSummary>>> {+ let global =+ Database::open_global().map_err(|e| ApiError::Internal(format!("global database: {e}")))?;++ Ok(Json(+ visible_projects(&state, &global)?+ .into_iter()+ .map(|p| ProjectSummary {+ tui_connected: global+ .tui_is_live(&p.path, state.heartbeat_ttl)+ .unwrap_or(false),+ id: p.id,+ name: p.name,+ path: p.path,+ last_opened: p.last_opened.to_rfc3339(),+ })+ .collect(),+ ))+}++/// The projects this server will talk about at all.+///+/// In project mode the picker still exists on the phone, but it has exactly one+/// entry: serving one project must not advertise the whole index. Shared by+/// both handlers so `/api/health`'s count and `/api/projects`'s length cannot+/// disagree β reporting five on one and one on the other is the kind of+/// mismatch a client rebuilds its state machine around.+fn visible_projects(state: &ServerState, global: &Database) -> ApiResult<Vec<crate::db::Project>> {+ let all = global+ .get_all_projects()+ .map_err(|e| ApiError::Internal(format!("listing projects: {e}")))?;+ Ok(match &state.mode {+ ServeMode::Project(path) => all+ .into_iter()+ .filter(|p| std::path::Path::new(&p.path) == path)+ .collect(),+ ServeMode::Global => all,+ })+}++// ββ /api/projects/:pid/tasks ββββββββββββββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+struct TaskCard {+ id: String,+ title: String,+ status: String,+ agent: String,+ plugin: Option<String>,+ cycle: i32,+ branch_name: Option<String>,+ pr_number: Option<i32>,+ escalation_note: Option<String>,+ updated_at: String,+ deps_satisfied: bool,+ allowed_actions: Vec<String>,+ /// The TUI's published phase status, or `None` when nothing has been+ /// observed for this task. A client must weigh it against `phase_age_secs`+ /// rather than treating it as live β with no TUI running, nothing refreshes+ /// it.+ phase_status: Option<String>,+ phase_age_secs: Option<i64>,+ /// Whether this branch still merges cleanly into its base. `None` means+ /// "not checked yet" β a Review task's first appearance, before the+ /// background pass has run β and a client must render that as unknown+ /// rather than as clean, which is the answer someone might merge on.+ conflicted: Option<bool>,+ conflicting_files: Vec<String>,+}++fn card(+ db: &Database,+ t: Task,+ runtime: Option<&crate::db::TaskRuntime>,+ conflict: Option<ConflictState>,+) -> TaskCard {+ let deps_ok = db.deps_satisfied(&t);+ TaskCard {+ conflicted: conflict.as_ref().map(|c| c.conflicted),+ conflicting_files: conflict.map(|c| c.files).unwrap_or_default(),+ allowed_actions: allowed_actions(&t, deps_ok, CallerKind::Human),+ deps_satisfied: deps_ok,+ phase_status: runtime.map(|r| r.phase_status.as_str().to_string()),+ phase_age_secs: runtime.map(|r| (chrono::Utc::now() - r.updated_at).num_seconds()),+ id: t.id,+ title: t.title,+ status: t.status.as_str().to_string(),+ agent: t.agent,+ plugin: t.plugin,+ cycle: t.cycle,+ branch_name: t.branch_name,+ pr_number: t.pr_number,+ escalation_note: t.escalation_note,+ updated_at: t.updated_at.to_rfc3339(),+ }+}++async fn tasks(+ State(state): State<Arc<ServerState>>,+ Path(pid): Path<String>,+) -> ApiResult<Json<Vec<TaskCard>>> {+ let db = state.project_db(&pid)?;+ // Tell the TUI someone is reading, so it starts publishing phase status.+ // Without a reader it publishes nothing, which is the point.+ if let Ok(path) = state.project_path(&pid) {+ state.note_board_watched(&path.to_string_lossy());+ }+ let all = db+ .get_all_tasks()+ .map_err(|e| ApiError::Internal(format!("listing tasks: {e}")))?;++ // One query for the whole board rather than one per card: the board is the+ // request a phone makes most, and it is the one that grows with the project.+ let runtime = db.list_task_runtime().unwrap_or_default();++ // Kick off a conflict pass for anything in Review whose answer is missing+ // or stale. It runs *after* this response: the board never waits on git.+ spawn_conflict_refresh(state.clone(), &pid, &all);++ Ok(Json(+ all.into_iter()+ .map(|t| {+ let rt = runtime.iter().find(|r| r.task_id == t.id);+ let conflict = state.conflicts.get(&t.id);+ card(&db, t, rt, conflict)+ })+ .collect(),+ ))+}++/// Recompute merge-conflict state for Review tasks, off the request path.+///+/// Only Review tasks: a branch that is still being written to will conflict or+/// not many times before anyone cares, and the question is only meaningful once+/// the work is up for merging.+fn spawn_conflict_refresh(state: Arc<ServerState>, pid: &str, tasks: &[Task]) {+ let stale: Vec<Task> = tasks+ .iter()+ .filter(|t| t.status == crate::db::TaskStatus::Review)+ .filter(|t| t.worktree_path.is_some() && state.conflicts.is_stale(&t.id))+ .cloned()+ .collect();+ if stale.is_empty() {+ return;+ }++ let Ok(project) = state.project_path(pid) else {+ return;+ };++ tokio::task::spawn_blocking(move || {+ // One pass at a time. A poll every two seconds would otherwise stack+ // passes over the same tasks faster than git can answer.+ let Some(_guard) = state.conflicts.try_claim() else {+ return;+ };+ for task in stale {+ if let Some(found) = conflict_for(&project, &task) {+ state.conflicts.put(task.id.clone(), found);+ }+ }+ });+}++/// The base branch to compare against, verified to exist.+///+/// The recorded base has to be *checked*, not trusted: `git diff` and+/// `git merge-tree` only fail when git cannot be **spawned**, so a base that no+/// longer resolves comes back as an empty diff and no conflicts β which reads+/// as "nothing to do" for a task whose work is entirely intact. Falling back to+/// detection and reporting which base was used keeps the answer honest.+fn resolve_base(+ project: &std::path::Path,+ worktree: &std::path::Path,+ recorded: Option<&str>,+) -> Option<String> {+ recorded+ .filter(|b| !b.is_empty() && crate::git::ref_exists(worktree, b))+ .map(str::to_string)+ .or_else(|| {+ crate::git::detect_main_branch(project)+ .ok()+ .filter(|b| crate::git::ref_exists(worktree, b))+ })+}++/// `None` when the question cannot be asked β no worktree, no branch, or a base+/// that does not resolve. Distinct from "no conflicts", which is an answer.+fn conflict_for(project: &std::path::Path, task: &Task) -> Option<ConflictState> {+ let worktree = std::path::PathBuf::from(task.worktree_path.as_ref()?);+ if !worktree.exists() {+ return None;+ }+ let branch = task.branch_name.clone()?;+ let base = resolve_base(project, &worktree, task.base_branch.as_deref())?;++ match crate::git::check_merge_conflicts(&worktree, &base, &branch) {+ Ok((conflicted, files)) => Some(ConflictState { conflicted, files }),+ Err(_) => None,+ }+}++// ββ /api/projects/:pid/tasks/:tid βββββββββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+struct TaskDetail {+ #[serde(flatten)]+ card: TaskCard,+ description: Option<String>,+ worktree_path: Option<String>,+ session_name: Option<String>,+ pr_url: Option<String>,+ base_branch: Option<String>,+ referenced_tasks: Option<String>,+ created_at: String,+ /// The agent's own hook-reported state, read from its status file. Distinct+ /// from `phase_status`, which is the TUI's verdict: this one is available+ /// cross-process precisely because it is a file rather than TUI state.+ agent_state: Option<String>,+ blocked_reason: Option<String>,+}++async fn task_detail(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+) -> ApiResult<Json<TaskDetail>> {+ let db = state.project_db(&pid)?;+ let t = load_task(&db, &tid)?;+ let runtime = db.get_task_runtime(&tid).ok().flatten();++ // On the detail screen the answer is worth waiting for: one task, and this+ // is the screen someone is on when deciding whether to merge. The board+ // takes the cached value instead, because it asks about every card at once.+ let conflict = if t.status == crate::db::TaskStatus::Review {+ match state.conflicts.get(&tid) {+ Some(cached) if !state.conflicts.is_stale(&tid) => Some(cached),+ _ => {+ let project = state.project_path(&pid)?;+ let task = t.clone();+ let found = tokio::task::spawn_blocking(move || conflict_for(&project, &task))+ .await+ .ok()+ .flatten();+ if let Some(ref c) = found {+ state.conflicts.put(tid.clone(), c.clone());+ }+ found+ }+ }+ } else {+ None+ };++ let hook = t.worktree_path.as_ref().and_then(|wt| {+ crate::agent::hook_status::read_status(+ std::path::Path::new(wt),+ &t.id,+ chrono::Utc::now().timestamp(),+ )+ });++ let description = t.description.clone();+ let worktree_path = t.worktree_path.clone();+ let session_name = t.session_name.clone();+ let pr_url = t.pr_url.clone();+ let base_branch = t.base_branch.clone();+ let referenced_tasks = t.referenced_tasks.clone();+ let created_at = t.created_at.to_rfc3339();++ Ok(Json(TaskDetail {+ card: card(&db, t, runtime.as_ref(), conflict),+ description,+ worktree_path,+ session_name,+ pr_url,+ base_branch,+ referenced_tasks,+ created_at,+ agent_state: hook.as_ref().map(|h| {+ match h.state {+ crate::agent::hook_status::HookState::Working => "working",+ crate::agent::hook_status::HookState::Blocked => "blocked",+ crate::agent::hook_status::HookState::Waiting => "waiting",+ crate::agent::hook_status::HookState::Ended => "ended",+ }+ .to_string()+ }),+ blocked_reason: hook.and_then(|h| h.message),+ }))+}++// ββ /api/projects/:pid/tasks/:tid/diff ββββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+struct DiffResponse {+ base: String,+ stat: String,+ patch: String,+ /// `None` when the check could not be made. The diff screen is where+ /// someone decides to merge, so "unknown" and "clean" must not look alike.+ conflicted: Option<bool>,+ conflicting_files: Vec<String>,+}++async fn task_diff(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+) -> ApiResult<Json<DiffResponse>> {+ let project = state.project_path(&pid)?;+ let db = state.project_db(&pid)?;+ let t = load_task(&db, &tid)?;++ let worktree = t.worktree_path.clone().ok_or_else(|| {+ ApiError::NotFound(format!("task {tid} has no worktree, so there is no diff"))+ })?;+ let worktree = std::path::PathBuf::from(worktree);+ if !worktree.exists() {+ return Err(ApiError::NotFound(format!(+ "worktree for task {tid} no longer exists"+ )));+ }++ let base = resolve_base(&project, &worktree, t.base_branch.as_deref()).ok_or_else(|| {+ ApiError::NotFound(format!(+ "no base branch to diff against: task {tid} records {:?}, and neither it nor a \+ detected default resolves in {}",+ t.base_branch.as_deref().unwrap_or("none"),+ worktree.display()+ ))+ })?;++ // `HEAD` rather than the branch name: the branch is what the worktree has+ // checked out, and naming it would miss nothing but costs a lookup.+ let stat = crate::git::diff_stat(&worktree, &base, "HEAD")+ .map_err(|e| ApiError::Internal(format!("git diff --stat: {e}")))?;+ let patch = crate::git::diff_full(&worktree, &base, "HEAD")+ .map_err(|e| ApiError::Internal(format!("git diff: {e}")))?;++ // Computed here rather than read from the cache: this is the screen the+ // decision gets made on, and one git call is worth an honest answer.+ let conflict = {+ let project = project.clone();+ let task = t.clone();+ tokio::task::spawn_blocking(move || conflict_for(&project, &task))+ .await+ .ok()+ .flatten()+ };+ if let Some(ref c) = conflict {+ state.conflicts.put(tid.clone(), c.clone());+ }++ Ok(Json(DiffResponse {+ base,+ stat,+ patch,+ conflicted: conflict.as_ref().map(|c| c.conflicted),+ conflicting_files: conflict.map(|c| c.files).unwrap_or_default(),+ }))+}++// ββ /api/projects/:pid/tasks/:tid/pane ββββββββββββββββββββββββββββββββββ++#[derive(Deserialize)]+struct PaneQuery {+ lines: Option<i32>,+}++#[derive(Serialize)]+struct PaneResponse {+ session_name: String,+ lines: i32,+ content: String,+}++async fn task_pane(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+ Query(q): Query<PaneQuery>,+) -> ApiResult<Json<PaneResponse>> {+ let db = state.project_db(&pid)?;+ let t = load_task(&db, &tid)?;++ let session_name = t+ .session_name+ .clone()+ .ok_or_else(|| ApiError::NotFound(format!("task {tid} has no active session")))?;++ let lines = q.lines.unwrap_or(100).clamp(1, 10_000);+ let content = capture_pane(&session_name, lines)+ .ok_or_else(|| ApiError::Internal("tmux capture-pane failed".to_string()))?;++ Ok(Json(PaneResponse {+ session_name,+ lines,+ content,+ }))+}++/// A one-shot capture, for a client with no WebSocket.+///+/// Plain text, unlike the live view: a caller that asked for JSON did not ask+/// for SGR escapes in the middle of it. `/ws` is where the coloured frames go.+///+/// Goes through `TmuxOperations` rather than its own `tmux` invocation so the+/// socket name lives in exactly one place β `RealTmuxOps` hard-codes the `agtx`+/// server, and a second spelling here would be a second thing to update.+fn capture_pane(session_name: &str, lines: i32) -> Option<String> {+ let ops = crate::tmux::RealTmuxOps;+ if !crate::tmux::TmuxOperations::window_exists(&ops, session_name).unwrap_or(false) {+ return None;+ }+ let bytes = crate::tmux::TmuxOperations::capture_pane_with_history(&ops, session_name, lines);+ let text = String::from_utf8_lossy(&bytes);+ Some(strip_sgr(&text))+}++/// Remove SGR sequences, leaving the text a JSON caller expects.+pub fn strip_sgr(text: &str) -> String {+ let mut out = String::with_capacity(text.len());+ let mut chars = text.chars().peekable();+ while let Some(c) = chars.next() {+ if c != '\u{1b}' {+ out.push(c);+ continue;+ }+ if chars.peek() == Some(&'[') {+ chars.next();+ // Consume up to and including the final byte of the sequence.+ for c in chars.by_ref() {+ if c.is_ascii_alphabetic() {+ break;+ }+ }+ }+ }+ out+}++fn load_task(db: &Database, tid: &str) -> ApiResult<Task> {+ match db.get_task(tid) {+ Ok(Some(t)) => Ok(t),+ Ok(None) => Err(ApiError::NotFound(format!("task {tid}"))),+ Err(e) => Err(ApiError::Internal(format!("loading task: {e}"))),+ }+}++/// Re-exported so the phase vocabulary is compiled against, not copied: a+/// client reads these strings and `PhaseStatus` is where they are defined.+#[allow(dead_code)]+fn phase_vocabulary() -> [&'static str; 5] {+ [+ PhaseStatus::Working.as_str(),+ PhaseStatus::Blocked.as_str(),+ PhaseStatus::Idle.as_str(),+ PhaseStatus::Ready.as_str(),+ PhaseStatus::Exited.as_str(),+ ]+}diff --git a/src/web/state.rs b/src/web/state.rsnew file mode 100644index 0000000..d5b37e4--- /dev/null+++ b/src/web/state.rs@@ -0,0 +1,350 @@+//! What a request handler is allowed to reach.++use std::collections::{HashMap, VecDeque};+use std::path::PathBuf;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::Json;+use serde::Serialize;++use crate::db::Database;++/// How the server resolves which project a request is about.+///+/// Mirrors [`crate::mcp::ServerMode`] deliberately: the two servers answer the+/// same questions about the same board, and a phone that has to think about+/// projects differently from the orchestrator is a second model to keep true.+#[derive(Debug, Clone)]+pub enum ServeMode {+ /// One project, fixed at startup. `project_id` in a path is checked against+ /// it rather than used to look anything up.+ Project(PathBuf),+ /// Every project in the global index; `project_id` selects.+ Global,+}++/// A task lost between listing and reading it is a 404, not a 500; a database+/// that will not open is the reverse. Handlers return this so the mapping is+/// made once, in [`super::routes`], rather than guessed per endpoint.+#[derive(Debug)]+pub enum ApiError {+ NotFound(String),+ Internal(String),+ BadRequest(String),+ /// The request was well-formed and the task exists, but the board does not+ /// permit this right now β a Backlog task whose dependencies have not+ /// cleared, say. Distinct from `BadRequest` because retrying later can+ /// succeed, and a client should say "not yet" rather than "you broke it".+ Conflict(String),+ TooManyRequests(String),+}++pub type ApiResult<T> = Result<T, ApiError>;++#[derive(Serialize)]+struct ErrorBody {+ error: String,+}++impl IntoResponse for ApiError {+ fn into_response(self) -> Response {+ let (code, message) = match self {+ ApiError::NotFound(m) => (StatusCode::NOT_FOUND, m),+ ApiError::BadRequest(m) => (StatusCode::BAD_REQUEST, m),+ ApiError::Conflict(m) => (StatusCode::CONFLICT, m),+ ApiError::TooManyRequests(m) => (StatusCode::TOO_MANY_REQUESTS, m),+ ApiError::Internal(m) => (StatusCode::INTERNAL_SERVER_ERROR, m),+ };+ (code, Json(ErrorBody { error: message })).into_response()+ }+}++/// A fixed-size sliding window over recent writes.+///+/// Not an anti-abuse measure β there is nothing to abuse on loopback with one+/// user. It is a ceiling on a *runaway client*: an optimistic UI that retries a+/// failing action in a render loop would otherwise queue thousands of+/// transition requests for the TUI to work through. It has to exist before+/// pairing opens this to a network, and it is cheaper to have it from the+/// start than to remember later.+pub struct RateLimiter {+ hits: Mutex<VecDeque<Instant>>,+ max: usize,+ window: Duration,+}++impl RateLimiter {+ pub fn new(max: usize, window: Duration) -> Self {+ Self {+ hits: Mutex::new(VecDeque::new()),+ max,+ window,+ }+ }++ /// Record an attempt; `false` means the caller is over the limit.+ pub fn allow(&self) -> bool {+ // A poisoned lock holds only timestamps, so recovering loses nothing+ // and refusing every later write would be a worse failure than the+ // panic that poisoned it.+ let mut hits = self.hits.lock().unwrap_or_else(|e| e.into_inner());+ let now = Instant::now();+ while hits+ .front()+ .is_some_and(|t| now.duration_since(*t) > self.window)+ {+ hits.pop_front();+ }+ if hits.len() >= self.max {+ return false;+ }+ hits.push_back(now);+ true+ }+}++/// Whether a task's branch still merges cleanly into its base.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ConflictState {+ pub conflicted: bool,+ pub files: Vec<String>,+}++/// Merge-conflict results, cached because computing one is a `git merge-tree`+/// subprocess.+///+/// The board is polled every two seconds and a project can hold several Review+/// tasks, so checking on the request path would put N git invocations on every+/// poll β the same cost decision 3 refuses for phase status, and for the same+/// reason. Instead the board serves whatever is cached (`None` the first time)+/// and a background pass fills it in, so the chip appears a poll later and the+/// board never waits.+#[derive(Default)]+pub struct ConflictCache {+ entries: Mutex<HashMap<String, (Instant, ConflictState)>>,+ /// One refresh at a time. Without this every poll would spawn another pass+ /// over the same tasks while the first was still running.+ refreshing: Mutex<bool>,+}++/// How long a conflict answer is trusted.+///+/// Generous: it changes only when someone commits to the branch or moves the+/// base, neither of which happens between two board polls.+const CONFLICT_TTL: Duration = Duration::from_secs(30);++impl ConflictCache {+ pub fn get(&self, task_id: &str) -> Option<ConflictState> {+ let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());+ entries.get(task_id).map(|(_, state)| state.clone())+ }++ pub fn is_stale(&self, task_id: &str) -> bool {+ let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());+ match entries.get(task_id) {+ Some((at, _)) => at.elapsed() > CONFLICT_TTL,+ None => true,+ }+ }++ pub fn put(&self, task_id: String, state: ConflictState) {+ let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());+ entries.insert(task_id, (Instant::now(), state));+ }++ /// Claim the right to run a refresh pass; `false` means one is already+ /// going. The guard releases it on drop, including on panic.+ pub fn try_claim(&self) -> Option<RefreshGuard<'_>> {+ let mut flag = self.refreshing.lock().unwrap_or_else(|e| e.into_inner());+ if *flag {+ return None;+ }+ *flag = true;+ Some(RefreshGuard { cache: self })+ }+}++pub struct RefreshGuard<'a> {+ cache: &'a ConflictCache,+}++impl Drop for RefreshGuard<'_> {+ fn drop(&mut self) {+ let mut flag = self+ .cache+ .refreshing+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ *flag = false;+ }+}++pub struct ServerState {+ pub mode: ServeMode,+ /// Whether `/api/*` and `/ws` require a paired device.+ ///+ /// Off for a loopback bind, which is its own boundary: reaching it already+ /// means being on this machine. On for anything wider, where it is the only+ /// thing standing between the network and an agent's composer.+ pub require_auth: bool,+ /// Codes waiting to be exchanged for a device token.+ pub pairing: super::auth::PairingCodes,+ /// Device ids seen recently, so `last_seen` is not written on every poll.+ seen: Mutex<HashMap<String, Instant>>,+ /// Projects whose board was recently asked for, so the watch marker is not+ /// rewritten on every request.+ watched: Mutex<HashMap<String, Instant>>,+ /// How long a TUI heartbeat stays trusted. Three beats of+ /// `TRANSITION_POLL_INTERVAL`, so one missed tick is not a disconnect.+ pub heartbeat_ttl: chrono::Duration,+ /// Ceiling on writes β actions and task CRUD together.+ pub writes: RateLimiter,+ pub conflicts: ConflictCache,+ /// Stamped on every device this server pairs, and the key it deletes them+ /// by on shutdown. `None` in tests and wherever pairings are not owned.+ pub session_id: Option<String>,+}++impl ServerState {+ pub fn new(mode: ServeMode) -> Arc<Self> {+ Self::with_auth(mode, false)+ }++ pub fn with_auth(mode: ServeMode, require_auth: bool) -> Arc<Self> {+ Self::with_session(mode, require_auth, None)+ }++ /// As [`Self::with_auth`], naming the serve session that owns its pairings.+ pub fn with_session(+ mode: ServeMode,+ require_auth: bool,+ session_id: Option<String>,+ ) -> Arc<Self> {+ Arc::new(Self {+ mode,+ require_auth,+ pairing: super::auth::PairingCodes::default(),+ seen: Mutex::new(HashMap::new()),+ watched: Mutex::new(HashMap::new()),+ heartbeat_ttl: chrono::Duration::seconds(6),+ // Generous for a person tapping, ruinous only for a loop.+ writes: RateLimiter::new(120, Duration::from_secs(60)),+ conflicts: ConflictCache::default(),+ session_id,+ })+ }++ /// Whether `presented` belongs to a paired device.+ ///+ /// The lookup is by hash, so the token itself is never read back out of the+ /// database to be compared β and a hash lookup is constant-time in the way+ /// that matters here, since the secret is not part of the comparison.+ pub fn token_ok(&self, presented: Option<&str>) -> bool {+ if !self.require_auth {+ return true;+ }+ let Some(token) = presented else {+ return false;+ };+ match super::auth::device_for_token(token) {+ Some(device) => {+ self.touch(&device.id);+ true+ }+ None => false,+ }+ }++ /// Record a device as active, at most once a minute.+ ///+ /// `last_seen` exists so a person can recognise which row is which phone+ /// when revoking. That does not need second-level accuracy, and writing on+ /// every request would mean a database write every two seconds per polling+ /// phone.+ fn touch(&self, device_id: &str) {+ const TOUCH_INTERVAL: Duration = Duration::from_secs(60);+ let mut seen = self.seen.lock().unwrap_or_else(|e| e.into_inner());+ let fresh = seen+ .get(device_id)+ .is_some_and(|at| at.elapsed() < TOUCH_INTERVAL);+ if fresh {+ return;+ }+ seen.insert(device_id.to_string(), Instant::now());+ if let Ok(db) = Database::open_global() {+ let _ = db.touch_mobile_device(device_id);+ }+ }++ /// Mark this project's board as being looked at.+ ///+ /// This is what lets the TUI publish `task_runtime` only while someone is+ /// actually reading it β a board nobody has opened costs no writes at all.+ /// Throttled, because it answers a question whose useful resolution is+ /// minutes and it is on the path of the request a phone makes most.+ pub fn note_board_watched(&self, project_path: &str) {+ const NOTE_INTERVAL: Duration = Duration::from_secs(30);+ let mut watched = self.watched.lock().unwrap_or_else(|e| e.into_inner());+ let fresh = watched+ .get(project_path)+ .is_some_and(|at| at.elapsed() < NOTE_INTERVAL);+ if fresh {+ return;+ }+ watched.insert(project_path.to_string(), Instant::now());+ if let Ok(db) = Database::open_global() {+ let _ = db.note_board_watched(project_path);+ }+ }++ pub fn check_write_budget(&self) -> ApiResult<()> {+ if self.writes.allow() {+ Ok(())+ } else {+ Err(ApiError::TooManyRequests(+ "too many writes in the last minute; slow down".to_string(),+ ))+ }+ }++ /// Resolve a `project_id` from the path to a project directory.+ ///+ /// In `Project` mode the id is still checked rather than ignored: a phone+ /// holding a stale bookmark for another project must get a 404 instead of+ /// silently being served this one's board.+ pub fn project_path(&self, project_id: &str) -> ApiResult<PathBuf> {+ match &self.mode {+ ServeMode::Project(path) => {+ let global = Database::open_global()+ .map_err(|e| ApiError::Internal(format!("global database: {e}")))?;+ match global.get_project_by_id(project_id) {+ Ok(Some(p)) if std::path::Path::new(&p.path) == path => Ok(path.clone()),+ // Unknown to the index but this server serves exactly one+ // project β accept the id only if it is that project's.+ Ok(_) => Err(ApiError::NotFound(format!(+ "project {project_id} is not the project this server was started on"+ ))),+ Err(e) => Err(ApiError::Internal(format!("project lookup: {e}"))),+ }+ }+ ServeMode::Global => {+ let global = Database::open_global()+ .map_err(|e| ApiError::Internal(format!("global database: {e}")))?;+ match global.get_project_by_id(project_id) {+ Ok(Some(p)) => Ok(PathBuf::from(p.path)),+ Ok(None) => Err(ApiError::NotFound(format!("project {project_id}"))),+ Err(e) => Err(ApiError::Internal(format!("project lookup: {e}"))),+ }+ }+ }+ }++ pub fn project_db(&self, project_id: &str) -> ApiResult<Database> {+ let path = self.project_path(project_id)?;+ Database::open_project(&path)+ .map_err(|e| ApiError::Internal(format!("project database: {e}")))+ }+}diff --git a/src/web/tunnel.rs b/src/web/tunnel.rsnew file mode 100644index 0000000..d26bc86--- /dev/null+++ b/src/web/tunnel.rs@@ -0,0 +1,371 @@+//! Reaching the board from outside the local network.+//!+//! Both providers work the same way and it is why this is safe to do at all:+//! the child makes an **outbound** connection to the provider's edge and the+//! phone reaches the edge. agtx keeps listening on loopback; nothing here binds+//! a wider address, opens a port, or needs a firewall rule.+//!+//! **The two modes are not variations on one thing.** `tailscale serve` is+//! tailnet-only β reachable from anywhere, by your own signed-in devices.+//! `tailscale funnel` and `cloudflared` are the public internet. Tailscale's+//! own naming invites collapsing them, and "Tailscale, so it is private" is+//! exactly the mistake this module refuses to let a caller make: `public` has+//! to be typed in full.+//!+//! **The spawn path here is unverified.** Neither binary is installed on the+//! machine this was written on, so [`TunnelPlan`] β which provider, which+//! command, which teardown β is pure and fully tested, while starting the child+//! is not. That split is deliberate: the part that can be wrong in a quiet way+//! is the part under test.++use std::process::{Child, Command, Stdio};++use anyhow::{bail, Context, Result};++/// How far the tunnel reaches.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TunnelScope {+ /// Your tailnet only. Reachable from anywhere, by your devices alone.+ Private,+ /// The open internet, to anyone with the URL.+ Public,+}++impl TunnelScope {+ pub fn parse(value: &str) -> Option<Self> {+ match value {+ "private" | "tailnet" => Some(TunnelScope::Private),+ "public" => Some(TunnelScope::Public),+ _ => None,+ }+ }+}++/// Which tool will be run, and how.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TunnelPlan {+ pub program: String,+ pub args: Vec<String>,+ /// Run on shutdown to undo the exposure.+ ///+ /// `tailscale serve` configures the *daemon* and outlives the process that+ /// asked for it, so killing the child would leave the board exposed with+ /// nothing on screen to say so. `cloudflared` holds the tunnel itself and+ /// needs no teardown beyond dying.+ pub teardown: Option<Vec<String>>,+ pub scope: TunnelScope,+ /// What to tell the user about where this is reachable from.+ pub reach: &'static str,+ /// Whether the command configures a daemon and exits, rather than *being*+ /// the tunnel.+ ///+ /// This decides how success is judged, and getting it wrong is silent:+ /// `tailscale serve --bg` returns immediately, so a spawned handle proves+ /// nothing β the exit status is the only signal, and a failure there means+ /// no tunnel at all. `cloudflared` is the opposite: it runs for as long as+ /// the tunnel lives, so waiting on it would block forever.+ pub backgrounds: bool,+ /// The URL the board is reached at, once this is running. `None` when only+ /// the provider knows it β `cloudflared` invents a hostname and prints it.+ pub public_url: Option<String>,+}++/// Choose a provider for `scope`, given which binaries exist.+///+/// `available` is passed in rather than probed so the choice is testable+/// without installing anything.+pub fn plan(scope: TunnelScope, port: u16, available: &dyn Fn(&str) -> bool) -> Result<TunnelPlan> {+ let target = format!("http://127.0.0.1:{port}");++ match scope {+ TunnelScope::Private => {+ if !available("tailscale") {+ bail!(+ "--tunnel private needs Tailscale, which is not installed. It is the only way \+ to be reachable from anywhere *without* being reachable by everyone: install \+ it from https://tailscale.com/download and sign this machine and your phone \+ into the same tailnet."+ );+ }+ Ok(TunnelPlan {+ program: "tailscale".to_string(),+ // `serve`, never `funnel`. The difference is the whole point of+ // this arm.+ args: vec![+ "serve".to_string(),+ "--bg".to_string(),+ // Without this it prompts, and the child is spawned with+ // null stdin β so it would block on a question nobody can+ // see, or fail with nothing on screen explaining why.+ "--yes".to_string(),+ "--https=443".to_string(),+ target,+ ],+ teardown: Some(vec![+ "tailscale".to_string(),+ "serve".to_string(),+ "--https=443".to_string(),+ "off".to_string(),+ ]),+ scope,+ reach: "your tailnet β anywhere, but only devices signed into it",+ backgrounds: true,+ // Served on 443, so no port β and https, because that is what+ // `--https=443` publishes.+ public_url: tailnet_hostname().map(|h| format!("https://{h}")),+ })+ }+ TunnelScope::Public => {+ if available("cloudflared") {+ return Ok(TunnelPlan {+ program: "cloudflared".to_string(),+ args: vec![+ "tunnel".to_string(),+ "--url".to_string(),+ target,+ "--no-autoupdate".to_string(),+ ],+ // The child *is* the tunnel; when it dies the exposure ends.+ teardown: None,+ scope,+ reach: "the open internet β anyone with the URL",+ // The child *is* the tunnel and prints its own hostname.+ backgrounds: false,+ public_url: None,+ });+ }+ if available("tailscale") {+ return Ok(TunnelPlan {+ program: "tailscale".to_string(),+ args: vec![+ "funnel".to_string(),+ "--bg".to_string(),+ "--yes".to_string(),+ "--https=443".to_string(),+ target,+ ],+ teardown: Some(vec![+ "tailscale".to_string(),+ "funnel".to_string(),+ "--https=443".to_string(),+ "off".to_string(),+ ]),+ scope,+ reach: "the open internet β anyone with the URL",+ backgrounds: true,+ public_url: tailnet_hostname().map(|h| format!("https://{h}")),+ });+ }+ bail!(+ "--tunnel public needs cloudflared or Tailscale, and neither is installed. \+ Consider `--tunnel private` instead: it reaches just as far without publishing \+ an endpoint that can type into your agents."+ )+ }+ }+}++/// A running tunnel, torn down on drop.+pub struct Tunnel {+ child: Option<Child>,+ teardown: Option<Vec<String>>,+ pub public_url: Option<String>,+}++impl Tunnel {+ pub fn start(plan: &TunnelPlan) -> Result<Self> {+ if plan.backgrounds {+ // Run to completion and judge it by the exit status. Spawning and+ // holding the handle looks like it works and proves nothing: the+ // process is *expected* to exit, so a failed tunnel and a healthy+ // one are indistinguishable that way β which is how a board ends up+ // served at a URL that resolves nowhere.+ let out = Command::new(&plan.program)+ .args(&plan.args)+ .stdin(Stdio::null())+ .output()+ .with_context(|| format!("running {}", plan.program))?;++ if !out.status.success() {+ // Relay the provider's own words. It knows things agtx does not+ // β that Serve is disabled for this tailnet, and the one-time+ // URL that enables it.+ let detail = String::from_utf8_lossy(&out.stderr);+ let detail = detail.trim();+ let detail = if detail.is_empty() {+ String::from_utf8_lossy(&out.stdout).trim().to_string()+ } else {+ detail.to_string()+ };+ bail!("{} could not start the tunnel:\n{detail}", plan.program);+ }++ return Ok(Self {+ child: None,+ teardown: plan.teardown.clone(),+ public_url: plan.public_url.clone(),+ });+ }++ let mut child = Command::new(&plan.program)+ .args(&plan.args)+ .stdin(Stdio::null())+ .stdout(Stdio::inherit())+ .stderr(Stdio::piped())+ .spawn()+ .with_context(|| format!("starting {}", plan.program))?;++ let stderr = child.stderr.take().context("capturing tunnel output")?;+ let (tx, rx) = std::sync::mpsc::channel();+ std::thread::spawn(move || {+ use std::io::BufRead;+ for line in std::io::BufReader::new(stderr).lines() {+ let Ok(line) = line else { break };+ if let Some(url) = quick_tunnel_url(&line) {+ let _ = tx.send(url);+ }+ // Keep draining after discovery so provider logs cannot fill+ // the pipe and stall the tunnel.+ eprintln!("{line}");+ }+ });+ // Own the child before waiting: errors and timeout must kill it too.+ let mut tunnel = Self {+ child: Some(child),+ teardown: plan.teardown.clone(),+ public_url: None,+ };+ let url = rx+ .recv_timeout(std::time::Duration::from_secs(30))+ .context("cloudflared did not report a public URL within 30 seconds")?;+ tunnel.public_url = Some(url);+ Ok(tunnel)+ }+}++impl Drop for Tunnel {+ fn drop(&mut self) {+ if let Some(mut child) = self.child.take() {+ let _ = child.kill();+ let _ = child.wait();+ }+ // Teardown after the kill, because for `tailscale serve` the exposure+ // lives in the daemon and would otherwise survive this process.+ if let Some(cmd) = self.teardown.take() {+ if let Some((program, args)) = cmd.split_first() {+ let _ = Command::new(program)+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status();+ }+ }+ }+}++/// Whether a binary is on `PATH`.+pub fn installed(program: &str) -> bool {+ Command::new("which")+ .arg(program)+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}++// ββ tailnet identity ββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// This machine's tailnet DNS name, for building a URL before the tunnel runs.+///+/// `tailscale serve` proxies `https://<this>/` into a loopback listener, so the+/// hostname is not something agtx chooses β it has to be asked for, or the QR+/// would carry an address that does not exist.+pub fn tailnet_hostname() -> Option<String> {+ let out = Command::new("tailscale")+ .args(["status", "--json"])+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .output()+ .ok()?;+ if !out.status.success() {+ return None;+ }+ parse_tailnet_hostname(&String::from_utf8_lossy(&out.stdout))+}++/// Pull `Self.DNSName` out of `tailscale status --json`.+///+/// Split from the command so the parsing is testable without Tailscale+/// installed β which matters here, because it is not installed on the machine+/// this was written on.+pub fn parse_tailnet_hostname(json: &str) -> Option<String> {+ let value: serde_json::Value = serde_json::from_str(json).ok()?;+ let name = value.get("Self")?.get("DNSName")?.as_str()?;+ // Tailscale reports a fully-qualified name with the root dot. Leaving it on+ // produces a URL that most clients accept and some reject, which is the+ // worst of both.+ let trimmed = name.trim_end_matches('.');+ if trimmed.is_empty() {+ return None;+ }+ Some(trimmed.to_string())+}++/// Read only the assigned quick-tunnel hostname, not documentation links.+fn quick_tunnel_url(line: &str) -> Option<String> {+ line.split_whitespace().find_map(|word| {+ let host = word.strip_prefix("https://")?;+ let label = host.strip_suffix(".trycloudflare.com")?;+ (!label.is_empty()+ && label+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-'))+ .then(|| word.to_string())+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn discovers_only_quick_tunnel_urls() {+ assert_eq!(+ quick_tunnel_url("INF | https://some-host.trycloudflare.com |"),+ Some("https://some-host.trycloudflare.com".into())+ );+ assert_eq!(+ quick_tunnel_url("Visit https://developers.cloudflare.com"),+ None+ );+ assert_eq!(+ quick_tunnel_url("https://fake.trycloudflare.com.evil.test"),+ None+ );+ }++ #[test]+ #[cfg(unix)]+ fn running_tunnel_exposes_the_discovered_url() {+ let plan = TunnelPlan {+ program: "sh".into(),+ args: vec![+ "-c".into(),+ "echo 'INF | https://test-board.trycloudflare.com |' >&2; exec sleep 30".into(),+ ],+ teardown: None,+ scope: TunnelScope::Public,+ reach: "test",+ backgrounds: false,+ public_url: None,+ };+ let tunnel = Tunnel::start(&plan).unwrap();+ assert_eq!(+ tunnel.public_url.as_deref(),+ Some("https://test-board.trycloudflare.com")+ );+ // Drop terminates the fake provider rather than waiting for sleep.+ }+}diff --git a/src/web/writes.rs b/src/web/writes.rsnew file mode 100644index 0000000..8ed43fa--- /dev/null+++ b/src/web/writes.rs@@ -0,0 +1,522 @@+//! The write half of the HTTP surface.+//!+//! **Nothing here executes a transition.** An action becomes a row in+//! `transition_requests`, which only a running TUI drains β the mobile plan's+//! "one hard constraint". So every action response says `queued`, never `done`,+//! and carries the request id the client polls. Reporting otherwise would give+//! a phone a board that looks responsive while the laptop lid is shut.+//!+//! Task CRUD is the exception: create, edit and delete write the task table+//! directly, because they need no worktree, no agent and no tmux. They are+//! restricted to Backlog for the same reason the MCP tools are β editing a task+//! whose agent is mid-phase would change the work under it.++use std::sync::Arc;++use axum::{+ extract::{Path, State},+ Json,+};+use serde::{Deserialize, Serialize};++use crate::core::actions::{validate_action, ActionRefusal, CallerKind, MAX_TASK_TITLE_CHARS};+use crate::core::input::{agent_needs_paste, send_user_key, send_user_text, PaneKey};+use crate::db::{Database, Task, TaskStatus, TransitionRequest};+use crate::web::auth::PairError;++use super::state::{ApiError, ApiResult, ServerState};++// ββ POST /api/projects/:pid/tasks/:tid/action βββββββββββββββββββββββββββ++#[derive(Deserialize)]+pub struct ActionRequest {+ pub action: String,+ pub reason: Option<String>,+}++#[derive(Serialize)]+pub struct ActionResponse {+ request_id: String,+ /// Always `queued`. The board moves when a TUI picks the request up, which+ /// is what `GET .../requests/{id}` reports.+ status: &'static str,+ /// Whether anything is currently draining the queue. A client uses this to+ /// decide between "workingβ¦" and "queued β no agtx running", rather than+ /// leaving a spinner up forever.+ tui_connected: bool,+}++pub async fn task_action(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+ Json(body): Json<ActionRequest>,+) -> ApiResult<Json<ActionResponse>> {+ state.check_write_budget()?;++ let path = state.project_path(&pid)?;+ let db = state.project_db(&pid)?;+ let task = load_task(&db, &tid)?;++ // The same policy the board rendered its buttons from, checked again here.+ // A client is not the authority on what it may do: its copy of the task can+ // be seconds old, and the phase it was showing may already have moved.+ validate_action(+ &task,+ db.deps_satisfied(&task),+ CallerKind::Human,+ &body.action,+ )+ .map_err(|refusal| match refusal {+ ActionRefusal::UnknownAction(m) => ApiError::BadRequest(m),+ ActionRefusal::NotPermitted(m) => ApiError::Conflict(m),+ })?;++ // Refuse before queueing so the phone can show the reason immediately.+ // The TUI checks again at execution time because the agent may keep writing.+ if body.action == "move_to_done" {+ if let Some(worktree) = task.worktree_path.clone() {+ let dirty = tokio::task::spawn_blocking(move || {+ let output = std::process::Command::new("git")+ .current_dir(&worktree)+ .args(["status", "--porcelain"])+ .output()+ .map_err(|e| ApiError::Internal(format!("checking worktree: {e}")))?;+ if !output.status.success() {+ return Err(ApiError::Conflict(+ "Cannot verify that the worktree is clean; completion is blocked.".into(),+ ));+ }+ Ok(!output.stdout.is_empty())+ })+ .await+ .map_err(|e| ApiError::Internal(format!("checking worktree: {e}")))??;+ if dirty {+ return Err(ApiError::Conflict(+ "Uncommitted changes prevent moving this task to Done. Commit or resolve them first.".into(),+ ));+ }+ }+ }++ let mut req = TransitionRequest::new(&tid, &body.action);+ req.reason = body.reason.clone();+ let request_id = req.id.clone();+ db.create_transition_request(&req)+ .map_err(|e| ApiError::Internal(format!("queueing the transition: {e}")))?;++ tracing::info!(task = %tid, action = %body.action, request = %request_id, "queued from web");++ let global =+ Database::open_global().map_err(|e| ApiError::Internal(format!("global database: {e}")))?;+ Ok(Json(ActionResponse {+ request_id,+ status: "queued",+ tui_connected: global+ .tui_is_live(&path.to_string_lossy(), state.heartbeat_ttl)+ .unwrap_or(false),+ }))+}++// ββ GET /api/projects/:pid/requests/:rid ββββββββββββββββββββββββββββββββ++#[derive(Serialize)]+pub struct RequestStatus {+ request_id: String,+ /// `pending`, `completed` or `error` β the same three words+ /// `get_transition_status` reports, so a client reading both agrees.+ status: &'static str,+ error: Option<String>,+}++/// Note the shape: `/api/projects/{pid}/requests/{rid}`, not `/api/requests/{rid}`.+///+/// `transition_requests` lives in the *project* database, so a request id alone+/// does not identify a row β the plan's original route had no way to find one+/// without searching every indexed project.+pub async fn request_status(+ State(state): State<Arc<ServerState>>,+ Path((pid, rid)): Path<(String, String)>,+) -> ApiResult<Json<RequestStatus>> {+ let db = state.project_db(&pid)?;+ match db.get_transition_request(&rid) {+ Ok(Some(req)) => Ok(Json(RequestStatus {+ request_id: req.id,+ status: match (&req.processed_at, &req.error) {+ (Some(_), Some(_)) => "error",+ (Some(_), None) => "completed",+ (None, _) => "pending",+ },+ error: req.error,+ })),+ // Requests are reaped an hour after processing, so a client polling an+ // old id gets a 404 rather than a wrong answer.+ Ok(None) => Err(ApiError::NotFound(format!(+ "no transition request {rid}; it may have completed and been cleaned up"+ ))),+ Err(e) => Err(ApiError::Internal(format!("reading the request: {e}"))),+ }+}++// ββ task CRUD (Backlog only) ββββββββββββββββββββββββββββββββββββββββββββ++#[derive(Deserialize)]+pub struct CreateTask {+ pub title: String,+ pub description: Option<String>,+ pub plugin: Option<String>,+ pub referenced_tasks: Option<String>,+ pub base_branch: Option<String>,+}++#[derive(Serialize)]+pub struct CreatedTask {+ id: String,+ title: String,+ status: String,+}++pub async fn create_task(+ State(state): State<Arc<ServerState>>,+ Path(pid): Path<String>,+ Json(body): Json<CreateTask>,+) -> ApiResult<Json<CreatedTask>> {+ state.check_write_budget()?;++ let db = state.project_db(&pid)?;+ let title = validate_title(&body.title)?;+ validate_refs(&db, body.referenced_tasks.as_deref())?;++ // The project's own defaults, so a task created from a phone is the task+ // the desktop would have created β the agent in particular is what every+ // later phase reads.+ let (agent, plugin) = defaults_for(&state, &pid);+ let project_name = project_name_for(&state, &pid);++ let mut task = Task::new(title, &agent, &project_name);+ task.description = body.description;+ task.plugin = body.plugin.or(plugin);+ task.referenced_tasks = body.referenced_tasks;+ task.base_branch = body.base_branch;++ db.create_task(&task)+ .map_err(|e| ApiError::Internal(format!("creating the task: {e}")))?;+ tracing::info!(task = %task.id, "created from web");++ Ok(Json(CreatedTask {+ id: task.id,+ title: task.title,+ status: task.status.as_str().to_string(),+ }))+}++#[derive(Deserialize)]+pub struct UpdateTask {+ pub title: Option<String>,+ pub description: Option<String>,+ pub plugin: Option<String>,+ pub referenced_tasks: Option<String>,+ pub base_branch: Option<String>,+}++pub async fn update_task(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+ Json(body): Json<UpdateTask>,+) -> ApiResult<Json<CreatedTask>> {+ state.check_write_budget()?;++ let db = state.project_db(&pid)?;+ let mut task = load_task(&db, &tid)?;+ backlog_only(&task, "edit")?;++ if let Some(title) = body.title {+ task.title = validate_title(&title)?.to_string();+ }+ if let Some(description) = body.description {+ task.description = Some(description);+ }+ if let Some(plugin) = body.plugin {+ task.plugin = Some(plugin);+ }+ if let Some(refs) = body.referenced_tasks {+ validate_refs(&db, Some(&refs))?;+ task.referenced_tasks = Some(refs);+ }+ if let Some(base) = body.base_branch {+ task.base_branch = Some(base);+ }++ db.update_task(&task)+ .map_err(|e| ApiError::Internal(format!("updating the task: {e}")))?;++ Ok(Json(CreatedTask {+ id: task.id,+ title: task.title,+ status: task.status.as_str().to_string(),+ }))+}++#[derive(Serialize)]+pub struct DeletedTask {+ id: String,+ title: String,+}++pub async fn delete_task(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+) -> ApiResult<Json<DeletedTask>> {+ state.check_write_budget()?;++ let db = state.project_db(&pid)?;+ let task = load_task(&db, &tid)?;+ backlog_only(&task, "delete")?;++ db.delete_task(&tid)+ .map_err(|e| ApiError::Internal(format!("deleting the task: {e}")))?;+ tracing::info!(task = %tid, "deleted from web");++ Ok(Json(DeletedTask {+ id: task.id,+ title: task.title,+ }))+}++// ββ shared checks βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++fn load_task(db: &Database, tid: &str) -> ApiResult<Task> {+ match db.get_task(tid) {+ Ok(Some(t)) => Ok(t),+ Ok(None) => Err(ApiError::NotFound(format!("task {tid}"))),+ Err(e) => Err(ApiError::Internal(format!("loading task: {e}"))),+ }+}++/// Editing or deleting a task that has left Backlog would change the work under+/// a running agent, so both are refused past that point β the same rule the MCP+/// tools enforce.+fn backlog_only(task: &Task, verb: &str) -> ApiResult<()> {+ if task.status == TaskStatus::Backlog {+ Ok(())+ } else {+ Err(ApiError::Conflict(format!(+ "can only {verb} a Backlog task; {:?} is in {}",+ task.title,+ task.status.as_str()+ )))+ }+}++fn validate_title(title: &str) -> ApiResult<&str> {+ let trimmed = title.trim();+ if trimmed.is_empty() {+ return Err(ApiError::BadRequest("a task needs a title".to_string()));+ }+ let chars = trimmed.chars().count();+ if chars > MAX_TASK_TITLE_CHARS {+ return Err(ApiError::BadRequest(format!(+ "title is {chars} characters; the maximum is {MAX_TASK_TITLE_CHARS}"+ )));+ }+ Ok(trimmed)+}++/// A reference to a task that does not exist would silently become a dependency+/// nothing can satisfy, leaving the referring task unable to leave Backlog with+/// no visible cause.+fn validate_refs(db: &Database, refs: Option<&str>) -> ApiResult<()> {+ let Some(refs) = refs else { return Ok(()) };+ for id in refs.split(',').map(str::trim).filter(|s| !s.is_empty()) {+ match db.get_task(id) {+ Ok(Some(_)) => {}+ Ok(None) => {+ return Err(ApiError::BadRequest(format!(+ "referenced task {id} not found"+ )))+ }+ Err(e) => return Err(ApiError::Internal(format!("checking reference {id}: {e}"))),+ }+ }+ Ok(())+}++/// The project's configured default agent and plugin, merged over the global+/// config exactly as the TUI does.+fn defaults_for(state: &ServerState, pid: &str) -> (String, Option<String>) {+ let global = crate::config::GlobalConfig::load().unwrap_or_default();+ match state.project_path(pid) {+ Ok(path) => {+ let project = crate::config::ProjectConfig::load(&path).unwrap_or_default();+ let merged = crate::config::MergedConfig::merge(&global, &project);+ (merged.default_agent.clone(), merged.workflow_plugin.clone())+ }+ Err(_) => (global.default_agent.clone(), None),+ }+}++fn project_name_for(state: &ServerState, pid: &str) -> String {+ state+ .project_path(pid)+ .ok()+ .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))+ .unwrap_or_else(|| pid.to_string())+}++// ββ POST /api/projects/:pid/tasks/:tid/input ββββββββββββββββββββββββββββ++/// Two fields, exactly one of which must be set.+///+/// Not one field the server disambiguates: `send-keys` without `-l` resolves an+/// argument matching a key name *as that key*, so a message of `"Space"` would+/// arrive as `0x20` and `"Escape"` as an actual Escape. The caller has to say+/// which it meant, and this is the shape that makes them say it.+#[derive(Deserialize)]+pub struct InputRequest {+ pub text: Option<String>,+ pub key: Option<String>,+}++#[derive(Serialize)]+pub struct InputResponse {+ delivered: bool,+}++/// The cap and null-byte rule from `send_to_task`, so MCP and HTTP refuse the+/// same messages.+const MAX_INPUT_BYTES: usize = 4096;++pub async fn task_input(+ State(state): State<Arc<ServerState>>,+ Path((pid, tid)): Path<(String, String)>,+ Json(body): Json<InputRequest>,+) -> ApiResult<Json<InputResponse>> {+ state.check_write_budget()?;++ let db = state.project_db(&pid)?;+ let task = load_task(&db, &tid)?;++ // Research keeps its task in Backlog; review and conflict resolution also+ // retain an agent. Every phase except Done can have an active session.+ if task.status == TaskStatus::Done {+ return Err(ApiError::Conflict(format!(+ "cannot send input to a completed task; {:?} is in {}",+ task.title,+ task.status.as_str()+ )));+ }+ let session = task+ .session_name+ .clone()+ .ok_or_else(|| ApiError::NotFound(format!("task {tid} has no active session")))?;++ let tmux_ops: Arc<dyn crate::tmux::TmuxOperations> = Arc::new(crate::tmux::RealTmuxOps);++ let delivered = match (body.text, body.key) {+ (Some(_), Some(_)) => {+ return Err(ApiError::BadRequest(+ "send either text or key, not both".to_string(),+ ))+ }+ (None, None) => {+ return Err(ApiError::BadRequest(+ "nothing to send: set text or key".to_string(),+ ))+ }+ (Some(text), None) => {+ if text.len() > MAX_INPUT_BYTES {+ return Err(ApiError::BadRequest(format!(+ "message is {} bytes; the maximum is {MAX_INPUT_BYTES}",+ text.len()+ )));+ }+ if text.contains('\0') {+ return Err(ApiError::BadRequest(+ "message contains null bytes".to_string(),+ ));+ }+ // Blocking work β a paste plus `submit_message`'s bounded Enter+ // loop, which polls the pane. Running it on the async runtime would+ // stall every other request on this thread for up to a few seconds.+ let agent = task.agent.clone();+ tokio::task::spawn_blocking(move || {+ send_user_text(&tmux_ops, &session, &text, agent_needs_paste(&agent))+ })+ .await+ .map_err(|e| ApiError::Internal(format!("sending input: {e}")))?+ }+ (None, Some(name)) => {+ let key = PaneKey::parse(&name).ok_or_else(|| {+ ApiError::BadRequest(format!(+ "unsupported key {name:?}. A closed set is deliberate: forwarding arbitrary \+ key names would let a request send C-d, which ends the agent's session."+ ))+ })?;+ tokio::task::spawn_blocking(move || send_user_key(&tmux_ops, &session, key))+ .await+ .map_err(|e| ApiError::Internal(format!("sending key: {e}")))?+ }+ };++ tracing::info!(task = %tid, delivered, "input from web");+ Ok(Json(InputResponse { delivered }))+}++// ββ POST /api/pair ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[derive(Deserialize)]+pub struct PairRequest {+ pub code: String,+ /// What to call this device in the list. Free text, shown and never matched+ /// on, so it needs no validation beyond not being able to flood a display.+ pub label: Option<String>,+}++#[derive(Serialize)]+pub struct PairResponse {+ token: String,+ label: String,+}++/// Exchange a pairing code for a device token.+///+/// The one unauthenticated route, so everything that guards it lives here: the+/// code is single-use and short-lived, failures are counted toward a lockout,+/// and the write budget applies. The token is returned exactly once β only its+/// hash is stored β so a device that loses it pairs again rather than asking+/// for it back.+pub async fn pair(+ State(state): State<Arc<ServerState>>,+ Json(body): Json<PairRequest>,+) -> ApiResult<Json<PairResponse>> {+ state.check_write_budget()?;++ // Nothing to pair *with* on a loopback bind: there is no auth to hold a+ // token against, so issuing one would imply a protection that is not there.+ if !state.require_auth {+ return Err(ApiError::Conflict(+ "this server is not requiring authentication, so there is nothing to pair".to_string(),+ ));+ }++ state+ .pairing+ .redeem(body.code.trim())+ .map_err(|e| match e {+ PairError::LockedOut => ApiError::TooManyRequests(e.message().to_string()),+ other => ApiError::BadRequest(other.message().to_string()),+ })?;++ let label = body.label.unwrap_or_default();+ let token = crate::web::auth::pair_device(&label, state.session_id.as_deref())+ .map_err(|e| ApiError::Internal(format!("pairing: {e}")))?;++ let stored = crate::web::auth::device_for_token(&token)+ .map(|d| d.label)+ .unwrap_or_else(|| "phone".to_string());+ tracing::info!(label = %stored, "device paired");++ Ok(Json(PairResponse {+ token,+ label: stored,+ }))+}diff --git a/src/web/ws.rs b/src/web/ws.rsnew file mode 100644index 0000000..aec3811--- /dev/null+++ b/src/web/ws.rs@@ -0,0 +1,258 @@+//! Live pane frames over a WebSocket.+//!+//! **Snapshot frames, not a PTY.** Each frame is a whole `capture-pane -p -e`+//! of the pane, so nothing has to be replayed in order and a dropped frame+//! costs one refresh rather than desynchronising a terminal emulator. Measured:+//! `capture-pane -e` emits *only* `ESC[β¦m` β no cursor motion, no scroll+//! regions β because it is a snapshot of an already-rendered grid. That is why+//! the client renders it with a small SGR-to-HTML pass rather than a terminal+//! emulator; there is no terminal control in the stream to emulate.+//!+//! **One capture loop per socket, and only while subscribed.** A capture makes+//! the tmux server format an entire pane, so the cost is real and it is paid+//! per subscriber. Nothing is captured for a task nobody is looking at.++use std::sync::Arc;+use std::time::Duration;++use axum::{+ extract::{+ ws::{Message, WebSocket},+ State, WebSocketUpgrade,+ },+ response::Response,+};+use serde::{Deserialize, Serialize};+use tokio::time::interval;++use crate::tmux::{RealTmuxOps, TmuxOperations};++use super::state::ServerState;++/// How often a subscribed pane is captured.+///+/// Matches the TUI watcher's own ceiling for agent output rather than its+/// typing-window floor: a phone is watching an agent work, not echoing its own+/// keystrokes, and the floor exists for local echo latency that does not apply+/// over a tunnel.+const FRAME_INTERVAL: Duration = Duration::from_millis(250);++/// Rows captured per frame. Enough to fill a phone screen with room to scroll,+/// far short of the popup's 500-line scrollback spec β this is a live view, not+/// a history browser.+const FRAME_LINES: i32 = 200;++/// What a client may say. Public because it *is* the wire contract: the+/// browser has a hand-written encoder for it, and a rename here that nothing+/// pins would break the live view silently β the socket would connect, the+/// subscribe would be rejected as a bad message, and the pane would sit empty.+#[derive(Debug, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ClientMessage {+ /// Start streaming a task's pane. Replaces any previous subscription: a+ /// socket watches one pane, because a phone shows one screen.+ Subscribe {+ project_id: String,+ task_id: String,+ },+ Unsubscribe,+}++/// What the server sends back. Public for the same reason as [`ClientMessage`].+#[derive(Debug, Serialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum ServerMessage<'a> {+ Frame {+ task_id: &'a str,+ content: &'a str,+ },+ /// The pane went away β the agent exited, or the window was killed. Sent+ /// once rather than every tick, so a client can say so and stop waiting.+ Gone {+ task_id: &'a str,+ },+ Error {+ message: String,+ },+}++pub async fn handler(+ ws: WebSocketUpgrade,+ State(state): State<Arc<ServerState>>,+ headers: axum::http::HeaderMap,+) -> Response {+ // Authentication already happened in the router's auth layer, which reads+ // the same subprotocol β it has to run *before* `WebSocketUpgrade` accepts+ // the upgrade, and an extractor cannot.+ //+ // What is left here is echoing the subprotocol back: a browser that offered+ // one and receives nothing fails the handshake itself, which surfaces as a+ // network error rather than as anything to do with tokens.+ let offered = headers+ .get(axum::http::header::SEC_WEBSOCKET_PROTOCOL)+ .and_then(|v| v.to_str().ok())+ .and_then(|v| {+ v.split(',')+ .map(str::trim)+ .find(|p| p.starts_with(super::auth::WS_TOKEN_PREFIX))+ .map(str::to_string)+ });++ let upgrade = match offered {+ Some(proto) => ws.protocols([proto]),+ None => ws,+ };+ let token = super::auth::presented_token(&headers).map(str::to_owned);+ upgrade.on_upgrade(move |socket| run(socket, state, token))+}++async fn run(mut socket: WebSocket, state: Arc<ServerState>, token: Option<String>) {+ let mut auth_tick = interval(Duration::from_secs(1));+ let mut sub: Option<Subscription> = None;+ let mut ticker = interval(FRAME_INTERVAL);+ let mut last_sent: Option<String> = None;++ loop {+ tokio::select! {+ // Check even idle/unsubscribed sockets. Removing a device from+ // SQLite must also end connections established before revocation.+ _ = auth_tick.tick() => {+ if !state.token_ok(token.as_deref()) {+ let _ = tokio::time::timeout(+ Duration::from_secs(1), socket.send(Message::Close(None)),+ ).await;+ break;+ }+ }++ // A client message. `None` is a closed socket.+ incoming = socket.recv() => {+ match incoming {+ Some(Ok(Message::Text(text))) => {+ match serde_json::from_str::<ClientMessage>(&text) {+ Ok(ClientMessage::Subscribe { project_id, task_id }) => {+ last_sent = None;+ match Subscription::open(&state, &project_id, &task_id) {+ Ok(s) => sub = Some(s),+ Err(message) => {+ let _ = send(&mut socket, &ServerMessage::Error { message }).await;+ sub = None;+ }+ }+ }+ Ok(ClientMessage::Unsubscribe) => {+ // Stops the captures immediately rather than at+ // the next tick: this is the message a client+ // sends when its screen closed.+ sub = None;+ last_sent = None;+ }+ Err(e) => {+ let _ = send(+ &mut socket,+ &ServerMessage::Error { message: format!("bad message: {e}") },+ )+ .await;+ }+ }+ }+ Some(Ok(Message::Close(_))) | None => break,+ // Ping/pong are handled by axum; other frames are ignored.+ Some(Ok(_)) => {}+ Some(Err(_)) => break,+ }+ }++ _ = ticker.tick() => {+ let Some(ref s) = sub else { continue };+ match s.capture() {+ Some(content) => {+ // Only send what changed. An idle agent is the common+ // case, and re-sending an identical pane every 250ms+ // over a tunnel is the cost this avoids.+ if last_sent.as_deref() != Some(content.as_str()) {+ let msg = ServerMessage::Frame { task_id: &s.task_id, content: &content };+ if send(&mut socket, &msg).await.is_err() {+ break;+ }+ last_sent = Some(content);+ }+ }+ None => {+ let msg = ServerMessage::Gone { task_id: &s.task_id };+ let _ = send(&mut socket, &msg).await;+ // Stop capturing a pane that is gone; the client+ // resubscribes if the task comes back.+ sub = None;+ last_sent = None;+ }+ }+ }+ }+ }+}++async fn send(socket: &mut WebSocket, msg: &ServerMessage<'_>) -> Result<(), axum::Error> {+ let text = serde_json::to_string(msg).unwrap_or_else(|_| "{}".to_string());+ match tokio::time::timeout(+ Duration::from_secs(1),+ socket.send(Message::Text(text.into())),+ )+ .await+ {+ Ok(result) => result,+ Err(_) => Err(axum::Error::new(std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ "websocket send timed out",+ ))),+ }+}++/// What a socket needs to capture one pane, resolved once at subscribe time+/// rather than per frame β the task's session name does not change while it is+/// being watched, and looking it up four times a second would put a SQLite read+/// on the frame path.+pub struct Subscription {+ task_id: String,+ session_name: String,+ /// Captures go through `TmuxOperations` rather than a hand-rolled `tmux`+ /// invocation. Two reasons, and the second is the one that bites: the+ /// socket name lives in exactly one place (`tmux::AGENT_SERVER`), and a+ /// second spelling of `capture-pane` here would be free to drift from the+ /// flags the popup uses β `-p -e` with wrapped rows kept separate β which+ /// is what the client's renderer is written against.+ tmux: Arc<dyn TmuxOperations>,+}++impl Subscription {+ pub fn open(state: &ServerState, project_id: &str, task_id: &str) -> Result<Self, String> {+ let db = state+ .project_db(project_id)+ .map_err(|_| format!("no project {project_id}"))?;+ let task = db+ .get_task(task_id)+ .map_err(|e| format!("reading task: {e}"))?+ .ok_or_else(|| format!("no task {task_id}"))?;+ let session_name = task+ .session_name+ .ok_or_else(|| format!("task {task_id} has no active session"))?;+ Ok(Self {+ task_id: task_id.to_string(),+ session_name,+ tmux: Arc::new(RealTmuxOps),+ })+ }++ /// `None` means the pane is gone, which is distinct from an empty pane β+ /// a window whose agent exited returns no bytes *and* no window, and only+ /// the first of those is worth telling the client about.+ fn capture(&self) -> Option<String> {+ if !self.tmux.window_exists(&self.session_name).unwrap_or(false) {+ return None;+ }+ let bytes = self+ .tmux+ .capture_pane_with_history(&self.session_name, FRAME_LINES);+ Some(String::from_utf8_lossy(&bytes).to_string())+ }+}diff --git a/tests/db_tests.rs b/tests/db_tests.rsindex 186cf2e..af21397 100644--- a/tests/db_tests.rs+++ b/tests/db_tests.rs@@ -1,4 +1,7 @@-use agtx::db::{Database, Notification, Project, Task, TaskStatus, TransitionRequest};+use agtx::db::{+ Database, Notification, NotificationKind, PhaseStatus, Project, Task, TaskRuntime, TaskStatus,+ TransitionRequest,+};// === TaskStatus Tests ===@@ -699,3 +702,167 @@ fn test_dep_graph_unblocks_chain_as_deps_complete() {// A is no longer Backlog, so it drops out of the unblocked set; B enters it.assert_eq!(graph.unblocked_ids(), vec![b.id.clone()]);}++// === Task Runtime (published phase status) ===++fn runtime_for(task_id: &str, phase: PhaseStatus) -> TaskRuntime {+ TaskRuntime {+ task_id: task_id.to_string(),+ phase_status: phase,+ pane_hash: Some("abc123".to_string()),+ pane_changed_at: Some(chrono::Utc::now()),+ updated_at: chrono::Utc::now(),+ }+}++#[test]+#[cfg(feature = "test-mocks")]+fn task_runtime_round_trips() {+ let db = Database::open_in_memory_project().unwrap();+ let task = Task::new("Runtime", "claude", "proj");+ db.create_task(&task).unwrap();++ db.publish_task_runtime(&[runtime_for(&task.id, PhaseStatus::Blocked)])+ .unwrap();++ let got = db.get_task_runtime(&task.id).unwrap().expect("row written");+ assert_eq!(got.task_id, task.id);+ assert_eq!(got.phase_status, PhaseStatus::Blocked);+ assert_eq!(got.pane_hash.as_deref(), Some("abc123"));+ assert!(got.pane_changed_at.is_some());+}++/// Every `PhaseStatus` must survive the trip. A variant that serialises to a+/// string `from_str` does not accept reads back as the `Working` fallback, and+/// the board would report a blocked task as busy.+#[test]+#[cfg(feature = "test-mocks")]+fn every_phase_status_survives_the_database() {+ let db = Database::open_in_memory_project().unwrap();+ let task = Task::new("Round trip", "claude", "proj");+ db.create_task(&task).unwrap();++ for phase in [+ PhaseStatus::Working,+ PhaseStatus::Blocked,+ PhaseStatus::Idle,+ PhaseStatus::Ready,+ PhaseStatus::Exited,+ ] {+ db.publish_task_runtime(&[runtime_for(&task.id, phase)])+ .unwrap();+ let got = db.get_task_runtime(&task.id).unwrap().unwrap();+ assert_eq!(got.phase_status, phase, "{:?} did not round-trip", phase);+ }+}++/// The refresh rewrites every live task on each pass, so the row is a current+/// snapshot rather than a history β a second write must replace, not duplicate+/// or fail on the primary key.+#[test]+#[cfg(feature = "test-mocks")]+fn task_runtime_publish_replaces() {+ let db = Database::open_in_memory_project().unwrap();+ let task = Task::new("Upsert", "claude", "proj");+ db.create_task(&task).unwrap();++ db.publish_task_runtime(&[runtime_for(&task.id, PhaseStatus::Working)])+ .unwrap();+ db.publish_task_runtime(&[runtime_for(&task.id, PhaseStatus::Ready)])+ .unwrap();++ assert_eq!(db.list_task_runtime().unwrap().len(), 1);+ let got = db.get_task_runtime(&task.id).unwrap().unwrap();+ assert_eq!(got.phase_status, PhaseStatus::Ready);+}++#[test]+#[cfg(feature = "test-mocks")]+fn task_runtime_missing_row_is_none() {+ let db = Database::open_in_memory_project().unwrap();+ assert!(db.get_task_runtime("nope").unwrap().is_none());+}++/// A deleted task's last status must not be served to readers as current. The+/// refresh only ever publishes live tasks, so the pruning has to ride inside the+/// publish rather than depend on the deleting caller remembering it β MCP+/// deletes tasks from another process entirely.+#[test]+#[cfg(feature = "test-mocks")]+fn publishing_drops_runtime_for_deleted_tasks() {+ let db = Database::open_in_memory_project().unwrap();+ let live = Task::new("Live", "claude", "proj");+ let gone = Task::new("Gone", "claude", "proj");+ db.create_task(&live).unwrap();+ db.create_task(&gone).unwrap();+ db.publish_task_runtime(&[+ runtime_for(&live.id, PhaseStatus::Working),+ runtime_for(&gone.id, PhaseStatus::Ready),+ ])+ .unwrap();+ assert_eq!(db.list_task_runtime().unwrap().len(), 2);++ db.delete_task(&gone.id).unwrap();+ // The next pass carries only the surviving task, as the refresh would.+ db.publish_task_runtime(&[runtime_for(&live.id, PhaseStatus::Working)])+ .unwrap();++ let rows = db.list_task_runtime().unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].task_id, live.id);+}++// === Notification routing fields ===++/// A consumer outside the TUI filters on the event and threads replies by task,+/// so both must survive the write β against prose, neither is recoverable.+#[test]+#[cfg(feature = "test-mocks")]+fn notifications_carry_task_and_kind() {+ let db = Database::open_in_memory_project().unwrap();+ let notif = Notification::for_task(+ NotificationKind::TaskStuck,+ "task-42",+ "Task is blocked waiting for user input",+ );+ db.create_notification(¬if).unwrap();++ let peeked = db.peek_notifications().unwrap();+ assert_eq!(peeked.len(), 1);+ assert_eq!(peeked[0].task_id.as_deref(), Some("task-42"));+ assert_eq!(peeked[0].kind, Some(NotificationKind::TaskStuck));++ // `consume` names its columns explicitly where `peek` uses `SELECT *`, so+ // the two can drift apart silently.+ let consumed = db.consume_notifications().unwrap();+ assert_eq!(consumed[0].task_id.as_deref(), Some("task-42"));+ assert_eq!(consumed[0].kind, Some(NotificationKind::TaskStuck));+}++/// Rows written before the columns existed still read back.+#[test]+#[cfg(feature = "test-mocks")]+fn untagged_notifications_still_read() {+ let db = Database::open_in_memory_project().unwrap();+ db.create_notification(&Notification::new("no task, no kind"))+ .unwrap();++ let notifs = db.consume_notifications().unwrap();+ assert_eq!(notifs.len(), 1);+ assert!(notifs[0].task_id.is_none());+ assert!(notifs[0].kind.is_none());+}++/// The stored spelling and the serde spelling are the same string, so a reader+/// going through the database and one going through serialised output agree.+#[test]+fn notification_kind_spellings_match_serde() {+ for kind in [+ NotificationKind::PhaseCompleted,+ NotificationKind::TaskStuck,+ ] {+ let json = serde_json::to_string(&kind).unwrap();+ assert_eq!(json, format!("\"{}\"", kind.as_str()));+ assert_eq!(NotificationKind::from_str(kind.as_str()), Some(kind));+ }+}diff --git a/tests/web_client_tests.mjs b/tests/web_client_tests.mjsnew file mode 100644index 0000000..7b1b75f--- /dev/null+++ b/tests/web_client_tests.mjs@@ -0,0 +1,73 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';+import vm from 'node:vm';++// Exercise the actual socket controller with browser transport/timer fakes.+const source = readFileSync(new URL('../web/app.js', import.meta.url), 'utf8');+function setup() {+ const connections = [];+ const timers = new Map();+ let nextTimer = 0;+ class WebSocket {+ static CONNECTING = 0;+ static OPEN = 1;+ constructor() {+ this.readyState = WebSocket.CONNECTING;+ this.handlers = {};+ this.sent = [];+ connections.push(this);+ }+ addEventListener(event, handler) { this.handlers[event] = handler; }+ send(message) { this.sent.push(JSON.parse(message)); }+ close() { this.readyState = 3; }+ emit(event) { this.handlers[event]?.({}); }+ }+ const context = vm.createContext({+ WebSocket, location: { protocol: 'https:', host: 'board.test' },+ wsProtocols: () => [], paintPane() {},+ setTimeout(fn) { const id = ++nextTimer; timers.set(id, fn); return id; },+ clearTimeout(id) { timers.delete(id); },+ });+ const socketState = source.slice(source.indexOf('let socket = null;'), source.indexOf('/// A live terminal.'));+ const controller = source.slice(source.indexOf('function openSocket('), source.indexOf('// ββ boot'));+ vm.runInContext(socketState + controller, context);+ const run = (code) => vm.runInContext(code, context);+ run("openSocket('project', 'task', {}, {})");+ return { connections, timers, run, context };+}++test('disconnect retries and subscribes to the same task', () => {+ const { connections, timers } = setup();+ connections[0].readyState = 3;+ connections[0].emit('close');+ assert.equal(timers.size, 1);+ [...timers.values()][0]();+ assert.equal(connections.length, 2);+ connections[1].readyState = 1;+ connections[1].emit('open');+ assert.deepEqual(connections[1].sent, [{ type: 'subscribe', project_id: 'project', task_id: 'task' }]);+});++test('leaving the terminal cancels pending reconnection', () => {+ const { connections, timers, run } = setup();+ connections[0].readyState = 3;+ connections[0].emit('close');+ const queued = [...timers.values()][0];+ run('closeSocket()');+ assert.equal(timers.size, 0);+ queued(); // Even a timer already queued by the browser cannot reopen it.+ assert.equal(connections.length, 1);+});++test('refresh replaces a suspended socket without replacing input DOM', async () => {+ const { connections, run, context } = setup();+ connections[0].readyState = 1;+ const screen = source.slice(source.indexOf('async function screenTask('), source.indexOf('function detailsBody('));+ run(`let taskTab = 'terminal'; let mountedTask = 'project/task/terminal'; ${screen}`);+ run('globalThis.originalPane = term.pane');+ await vm.runInContext("screenTask('project', 'task')", context);+ assert.equal(connections.length, 2);+ assert.equal(run('term.pane === originalPane'), true);+ assert.equal(connections[0].readyState, 3);+});diff --git a/tests/web_tests.rs b/tests/web_tests.rsnew file mode 100644index 0000000..4ad4081--- /dev/null+++ b/tests/web_tests.rs@@ -0,0 +1,2147 @@+//! Route tests for `agtx serve`.+//!+//! Most tests use `tower`'s `oneshot` without a listener. The revocation+//! regression uses an ephemeral loopback listener to exercise existing sockets.+//!+//! These run only with `--features serve`; the whole module compiles away+//! otherwise, the same way the server does.+#![cfg(all(feature = "serve", feature = "test-mocks"))]++use std::path::{Path, PathBuf};+use std::sync::MutexGuard;++use agtx::db::{Database, Project, Task, TaskRuntime, TaskStatus};+use agtx::web::{ServeMode, ServerState};+use axum::body::Body;+use axum::http::{Request, StatusCode};+use http_body_util::BodyExt;+use tempfile::TempDir;+use tower::ServiceExt;++/// Point `AGTX_DATA_DIR` at a scratch directory of this test's own.+///+/// A fresh directory per test rather than one shared for the run, because+/// several of these assert on the *whole* project list and a project left+/// behind by another test would be read as this one's. The lock is still+/// required: the redirect is a process-global env var, so two tests running+/// concurrently would each see the other's directory.+///+/// The returned `TempDir` must outlive the test β dropping it deletes the+/// database out from under the handlers.+fn redirect_data_dir() -> (TempDir, MutexGuard<'static, ()>) {+ static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());+ // A panicking test poisons the lock; the data is unit, so recover and go on.+ let guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let dir = TempDir::new().unwrap();+ std::env::set_var("AGTX_DATA_DIR", dir.path());+ (dir, guard)+}++/// A git repo with one commit on the base branch and one on a task branch, so+/// a diff between them is non-empty.+fn seed_repo(dir: &Path) -> String {+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(dir)+ .args(args)+ .output()+ .expect("git");+ };+ git(&["init", "-q", "-b", "main"]);+ git(&["config", "user.email", "[email protected]"]);+ git(&["config", "user.name", "t"]);+ std::fs::write(dir.join("a.txt"), "hello\n").unwrap();+ git(&["add", "-A"]);+ git(&["commit", "-qm", "init"]);+ git(&["checkout", "-qb", "task/demo"]);+ std::fs::write(dir.join("a.txt"), "hello\nworld\n").unwrap();+ git(&["commit", "-qam", "work"]);+ "main".to_string()+}++struct Fixture {+ project_id: String,+ project_path: PathBuf,+ _repo: TempDir,+ _data: TempDir,+ _guard: MutexGuard<'static, ()>,+}++fn fixture() -> Fixture {+ let (data, guard) = redirect_data_dir();+ let repo = TempDir::new().unwrap();+ // Canonicalize: macOS hands out `/var/...` which is a symlink to+ // `/private/var/...`, and the server canonicalizes what it is given. An+ // uncanonicalized path here makes project-mode matching fail on macOS only.+ let path = repo.path().canonicalize().unwrap();+ seed_repo(&path);++ let global = Database::open_global().unwrap();+ let project = Project::new("demo", path.to_string_lossy().to_string());+ global.upsert_project(&project).unwrap();++ Fixture {+ project_id: project.id,+ project_path: path,+ _repo: repo,+ _data: data,+ _guard: guard,+ }+}++fn state_for(f: &Fixture, mode: ServeMode) -> std::sync::Arc<ServerState> {+ let _ = f;+ ServerState::new(mode)+}++async fn get(state: std::sync::Arc<ServerState>, uri: &str) -> (StatusCode, serde_json::Value) {+ let app = agtx::web::routes::router(state);+ let res = app+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ let status = res.status();+ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null);+ (status, json)+}++// ββ health ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn health_reports_no_tui_when_nothing_is_beating() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(state, "/api/health").await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["project_count"], 1);+ assert_eq!(body["mode"], "global");+ // Nothing has beaten, so a tap would queue and sit there. This is the flag+ // the "no agtx instance connected" banner is built on, and defaulting it to+ // true would make the banner never appear.+ assert_eq!(body["tui_connected"], false);+}++#[tokio::test]+async fn health_sees_a_live_heartbeat() {+ let f = fixture();+ Database::open_global()+ .unwrap()+ .beat_tui_heartbeat(&f.project_path.to_string_lossy())+ .unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (_, body) = get(state, "/api/health").await;+ assert_eq!(body["tui_connected"], true);+}++/// A heartbeat older than the TTL is the same answer as no heartbeat: a TUI+/// that exited without cleaning up must not read as connected forever.+#[tokio::test]+async fn a_stale_heartbeat_is_not_a_connection() {+ let f = fixture();+ let global = Database::open_global().unwrap();+ global+ .beat_tui_heartbeat(&f.project_path.to_string_lossy())+ .unwrap();++ // Zero TTL: every beat is already expired.+ assert!(!global+ .tui_is_live(&f.project_path.to_string_lossy(), chrono::Duration::zero())+ .unwrap());+ assert!(global+ .tui_is_live(+ &f.project_path.to_string_lossy(),+ chrono::Duration::seconds(6)+ )+ .unwrap());+}++// ββ projects ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn global_mode_lists_every_project() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(state, "/api/projects").await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(body.as_array().unwrap().len(), 1);+ assert_eq!(body[0]["id"], f.project_id);+}++/// Serving one project must not advertise the whole index β the picker exists+/// either way, but in project mode it has exactly one entry.+#[tokio::test]+async fn project_mode_lists_only_its_own() {+ let f = fixture();+ let global = Database::open_global().unwrap();+ let other = Project::new("other", "/somewhere/else");+ global.upsert_project(&other).unwrap();++ let state = state_for(&f, ServeMode::Project(f.project_path.clone()));+ let (_, body) = get(state, "/api/projects").await;++ assert_eq!(body.as_array().unwrap().len(), 1);+ assert_eq!(body[0]["id"], f.project_id);+}++/// `/api/health`'s count and `/api/projects`'s length must be the same number.+/// They are two reads of one rule, and a client that sees five on one and one+/// on the other has no way to decide which is the board.+#[tokio::test]+async fn health_count_matches_the_project_list() {+ let f = fixture();+ let global = Database::open_global().unwrap();+ for name in ["other-a", "other-b"] {+ global+ .upsert_project(&Project::new(name, format!("/elsewhere/{name}")))+ .unwrap();+ }++ for mode in [+ ServeMode::Global,+ ServeMode::Project(f.project_path.clone()),+ ] {+ let (_, health) = get(state_for(&f, mode.clone()), "/api/health").await;+ let (_, list) = get(state_for(&f, mode.clone()), "/api/projects").await;+ assert_eq!(+ health["project_count"].as_u64().unwrap() as usize,+ list.as_array().unwrap().len(),+ "health and /api/projects disagree in {mode:?}"+ );+ }+}++/// A phone holding a bookmark for another project gets a 404 rather than this+/// project's board under the wrong name.+#[tokio::test]+async fn project_mode_refuses_another_projects_id() {+ let f = fixture();+ let global = Database::open_global().unwrap();+ let other = Project::new("other", "/somewhere/else");+ global.upsert_project(&other).unwrap();++ let state = state_for(&f, ServeMode::Project(f.project_path.clone()));+ let (status, _) = get(state, &format!("/api/projects/{}/tasks", other.id)).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn unknown_project_is_a_404() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(state, "/api/projects/no-such-project/tasks").await;+ assert_eq!(status, StatusCode::NOT_FOUND);+ assert!(body["error"].as_str().unwrap().contains("no-such-project"));+}++// ββ tasks βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++fn add_task(f: &Fixture, title: &str, status: TaskStatus) -> Task {+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new(title, "claude", &f.project_id);+ t.status = status;+ db.create_task(&t).unwrap();+ t+}++#[tokio::test]+async fn the_board_carries_actions_and_phase_status() {+ let f = fixture();+ let planning = add_task(&f, "Planning task", TaskStatus::Planning);++ let db = Database::open_project(&f.project_path).unwrap();+ db.publish_task_runtime(&[TaskRuntime {+ task_id: planning.id.clone(),+ phase_status: agtx::db::PhaseStatus::Blocked,+ pane_hash: None,+ pane_changed_at: None,+ updated_at: chrono::Utc::now(),+ }])+ .unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(state, &format!("/api/projects/{}/tasks", f.project_id)).await;++ assert_eq!(status, StatusCode::OK);+ let card = &body[0];+ assert_eq!(card["status"], "planning");+ assert_eq!(card["phase_status"], "blocked");+ assert!(card["phase_age_secs"].as_i64().unwrap() < 5);+ let actions: Vec<&str> = card["allowed_actions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();+ assert!(actions.contains(&"move_forward"));+}++/// Decision 9: the phone is a human caller, and a Backlog card with no actions+/// is a dead end β triage is most of what mobile is for. The orchestrator gets+/// the opposite answer for the same task.+#[tokio::test]+async fn backlog_offers_a_human_the_triage_actions() {+ let f = fixture();+ let task = add_task(&f, "Backlog task", TaskStatus::Backlog);++ let state = state_for(&f, ServeMode::Global);+ let (_, body) = get(state, &format!("/api/projects/{}/tasks", f.project_id)).await;++ let actions: Vec<&str> = body[0]["allowed_actions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();+ assert!(actions.contains(&"research"), "got {actions:?}");+ assert!(actions.contains(&"move_to_planning"), "got {actions:?}");+ assert!(actions.contains(&"move_to_running"), "got {actions:?}");++ // The same task, asked as the orchestrator, offers nothing.+ let db = Database::open_project(&f.project_path).unwrap();+ let t = db.get_task(&task.id).unwrap().unwrap();+ assert!(agtx::core::actions::allowed_actions(+ &t,+ true,+ agtx::core::actions::CallerKind::Orchestrator+ )+ .is_empty());+}++/// An unsatisfied dependency blocks the forward moves and nothing else. This+/// path is only reachable for a human caller, which is why it needs a test:+/// with the orchestrator it was unreachable code.+#[tokio::test]+async fn unsatisfied_dependencies_hide_the_forward_moves() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let dep = Task::new("Dependency", "claude", &f.project_id);+ db.create_task(&dep).unwrap();+ let mut blocked = Task::new("Blocked", "claude", &f.project_id);+ blocked.referenced_tasks = Some(dep.id.clone());+ db.create_task(&blocked).unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (_, body) = get(state, &format!("/api/projects/{}/tasks", f.project_id)).await;++ let card = body+ .as_array()+ .unwrap()+ .iter()+ .find(|c| c["id"] == blocked.id)+ .unwrap();+ assert_eq!(card["deps_satisfied"], false);+ let actions: Vec<&str> = card["allowed_actions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();+ assert!(!actions.contains(&"move_to_planning"), "got {actions:?}");+ assert!(!actions.contains(&"move_to_running"), "got {actions:?}");+ // `research` is not a forward transition and stays available.+ assert!(actions.contains(&"research"), "got {actions:?}");+}++/// A task with no published runtime row reports `null`, not a made-up status β+/// "nothing has observed this" and "this is working" are different claims.+#[tokio::test]+async fn a_task_with_no_runtime_row_reports_none() {+ let f = fixture();+ add_task(&f, "Never observed", TaskStatus::Backlog);++ let state = state_for(&f, ServeMode::Global);+ let (_, body) = get(state, &format!("/api/projects/{}/tasks", f.project_id)).await;+ assert!(body[0]["phase_status"].is_null());+ assert!(body[0]["phase_age_secs"].is_null());+}++#[tokio::test]+async fn task_detail_flattens_the_card_and_adds_the_rest() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new("Detailed", "codex", &f.project_id);+ t.status = TaskStatus::Review;+ t.description = Some("the description".to_string());+ t.branch_name = Some("task/demo".to_string());+ db.create_task(&t).unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(+ state,+ &format!("/api/projects/{}/tasks/{}", f.project_id, t.id),+ )+ .await;++ assert_eq!(status, StatusCode::OK);+ // Flattened, so a client reads one shape whether it came from the board or+ // the detail view.+ assert_eq!(body["id"], t.id);+ assert_eq!(body["agent"], "codex");+ assert_eq!(body["description"], "the description");+ assert_eq!(body["branch_name"], "task/demo");+ assert!(body["allowed_actions"]+ .as_array()+ .unwrap()+ .iter()+ .any(|a| a == "move_to_done"));+}++#[tokio::test]+async fn unknown_task_is_a_404() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);+ let (status, _) = get(state, &format!("/api/projects/{}/tasks/nope", f.project_id)).await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++// ββ diff ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn diff_returns_stat_and_patch_against_the_base_branch() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new("Has a worktree", "claude", &f.project_id);+ t.status = TaskStatus::Review;+ // The repo itself stands in for the worktree: it is checked out on+ // `task/demo`, which is what a real worktree would be.+ t.worktree_path = Some(f.project_path.to_string_lossy().to_string());+ t.base_branch = Some("main".to_string());+ db.create_task(&t).unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (status, body) = get(+ state,+ &format!("/api/projects/{}/tasks/{}/diff", f.project_id, t.id),+ )+ .await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["base"], "main");+ assert!(body["stat"].as_str().unwrap().contains("a.txt"));+ assert!(body["patch"].as_str().unwrap().contains("+world"));+}++/// A recorded base branch that no longer resolves must not read as "no+/// changes".+///+/// `git::diff_stat` only fails when git cannot be *spawned*: `git diff main+/// HEAD` in a repo with no `main` exits 128 with an empty stdout, which the+/// handler would otherwise render as an empty diff. On a review screen that is+/// a claim someone may merge on, so the base is verified and the response says+/// which one was actually used.+#[tokio::test]+async fn a_base_branch_that_does_not_resolve_falls_back_and_says_so() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new("Wrong base", "claude", &f.project_id);+ t.worktree_path = Some(f.project_path.to_string_lossy().to_string());+ t.base_branch = Some("no-such-branch".to_string());+ db.create_task(&t).unwrap();++ let (status, body) = get(+ state_for(&f, ServeMode::Global),+ &format!("/api/projects/{}/tasks/{}/diff", f.project_id, t.id),+ )+ .await;++ assert_eq!(status, StatusCode::OK);+ // Fell back to the repo's real default rather than reporting the missing+ // branch as an empty diff, and named what it used.+ assert_eq!(body["base"], "main");+ assert!(body["patch"].as_str().unwrap().contains("+world"));+}++/// A Backlog task has no worktree, and asking for its diff is a 404 rather+/// than a 500 β there is nothing wrong, there is just nothing there.+#[tokio::test]+async fn diff_without_a_worktree_is_a_404() {+ let f = fixture();+ let t = add_task(&f, "No worktree", TaskStatus::Backlog);++ let state = state_for(&f, ServeMode::Global);+ let (status, _) = get(+ state,+ &format!("/api/projects/{}/tasks/{}/diff", f.project_id, t.id),+ )+ .await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++/// A worktree recorded in the database but gone from disk β the task was+/// cleaned up, or the directory was removed by hand.+#[tokio::test]+async fn diff_with_a_vanished_worktree_is_a_404() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new("Gone", "claude", &f.project_id);+ t.worktree_path = Some("/nonexistent/worktree".to_string());+ db.create_task(&t).unwrap();++ let state = state_for(&f, ServeMode::Global);+ let (status, _) = get(+ state,+ &format!("/api/projects/{}/tasks/{}/diff", f.project_id, t.id),+ )+ .await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++// ββ pane ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// No session means no pane. Tested rather than assumed because the handler's+/// other path shells out to tmux, which a test must not depend on.+#[tokio::test]+async fn pane_without_a_session_is_a_404() {+ let f = fixture();+ let t = add_task(&f, "Not running", TaskStatus::Backlog);++ let state = state_for(&f, ServeMode::Global);+ let (status, _) = get(+ state,+ &format!("/api/projects/{}/tasks/{}/pane", f.project_id, t.id),+ )+ .await;+ assert_eq!(status, StatusCode::NOT_FOUND);+}++// ββ the embedded PWA ββββββββββββββββββββββββββββββββββββββββββββββββββββ++async fn raw(state: std::sync::Arc<ServerState>, uri: &str) -> (StatusCode, String, Vec<u8>) {+ let app = agtx::web::routes::router(state);+ let res = app+ .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ let status = res.status();+ let mime = res+ .headers()+ .get(axum::http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")+ .to_string();+ let body = res.into_body().collect().await.unwrap().to_bytes().to_vec();+ (status, mime, body)+}++/// Every declared asset is reachable and non-empty.+///+/// The table is `include_bytes!`, so a missing *file* is a compile error β but+/// a path that never gets routed is not, and a PWA missing one file is a blank+/// screen with a console error nobody sees.+#[tokio::test]+async fn every_asset_is_served() {+ let f = fixture();+ for asset in agtx::web::assets::ASSETS {+ let (status, mime, body) = raw(+ state_for(&f, ServeMode::Global),+ &format!("/{}", asset.path),+ )+ .await;+ assert_eq!(status, StatusCode::OK, "{} status", asset.path);+ assert_eq!(mime, asset.mime, "{} content-type", asset.path);+ assert!(!body.is_empty(), "{} is empty", asset.path);+ }+}++/// Every file in `web/` is in the asset table.+///+/// `include_bytes!` guarantees the other direction β a *listed* file must exist+/// or the build fails β but nothing makes every file on disk listed. A new+/// module left out 404s to the SPA shell, so an `import` receives HTML, the+/// module graph fails to parse, and the whole app renders a blank page with the+/// error only in a console nobody is looking at. That is not hypothetical: it+/// is exactly what `ansi.js` did when it was added.+#[test]+fn the_asset_table_covers_the_web_directory() {+ let listed: std::collections::HashSet<&str> =+ agtx::web::assets::ASSETS.iter().map(|a| a.path).collect();++ let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("web");+ let mut missing = Vec::new();+ for entry in std::fs::read_dir(&dir).expect("web/ exists") {+ let entry = entry.unwrap();+ if !entry.file_type().unwrap().is_file() {+ continue;+ }+ let name = entry.file_name().to_string_lossy().to_string();+ if name.starts_with('.') {+ continue;+ }+ if !listed.contains(name.as_str()) {+ missing.push(name);+ }+ }+ assert!(+ missing.is_empty(),+ "these files are in web/ but not in ASSETS, so they 404 to the shell: {missing:?}"+ );+}++/// The service worker precaches the shell by name, so its list has the same+/// drift risk as the asset table β a module missing from it simply is not+/// available offline.+#[tokio::test]+async fn the_service_worker_precaches_every_script() {+ let f = fixture();+ let (_, _, body) = raw(state_for(&f, ServeMode::Global), "/sw.js").await;+ let js = String::from_utf8_lossy(&body);+ for asset in agtx::web::assets::ASSETS {+ if asset.path.ends_with(".js") && asset.path != "sw.js" {+ assert!(+ js.contains(asset.path),+ "{} is served but not precached by the service worker",+ asset.path+ );+ }+ }+}++/// A module script whose MIME is not a JavaScript type is refused outright by+/// the browser, which fails the entire app with a blank page.+#[tokio::test]+async fn scripts_are_served_as_javascript() {+ let f = fixture();+ for path in ["/app.js", "/api.js", "/sw.js"] {+ let (_, mime, _) = raw(state_for(&f, ServeMode::Global), path).await;+ assert!(+ mime.starts_with("text/javascript"),+ "{path} served as {mime}, which a browser will refuse for type=module"+ );+ }+}++#[tokio::test]+async fn the_root_serves_the_shell() {+ let f = fixture();+ let (status, mime, body) = raw(state_for(&f, ServeMode::Global), "/").await;+ assert_eq!(status, StatusCode::OK);+ assert!(mime.starts_with("text/html"));+ let html = String::from_utf8_lossy(&body);+ assert!(html.contains("<title>agtx</title>"));+ assert!(html.contains(r#"type="module""#));+ assert!(html.contains("manifest.webmanifest"));+}++/// An unmatched `/api/...` must stay JSON. Answering it with the HTML shell+/// hands `fetch` a 200 full of markup, which surfaces as a JSON parse error+/// somewhere unrelated to the actual mistake.+#[tokio::test]+async fn an_unknown_api_path_is_json_not_the_shell() {+ let f = fixture();+ let (status, mime, body) = raw(state_for(&f, ServeMode::Global), "/api/nope").await;+ assert_eq!(status, StatusCode::NOT_FOUND);+ assert!(mime.contains("json"), "got {mime}");+ assert!(!String::from_utf8_lossy(&body).contains("<html"));+}++/// Assets must not shadow the API: both are on the same router, and a+/// fallback that caught `/api/health` would be invisible until a client asked.+#[tokio::test]+async fn the_api_still_wins_over_the_fallback() {+ let f = fixture();+ let (status, mime, _) = raw(state_for(&f, ServeMode::Global), "/api/health").await;+ assert_eq!(status, StatusCode::OK);+ assert!(mime.contains("json"), "got {mime}");+}++/// The manifest has to parse and name icons that exist, or the install prompt+/// never appears β and on iOS an uninstallable PWA cannot receive Web Push.+#[tokio::test]+async fn the_manifest_is_valid_and_its_icons_resolve() {+ let f = fixture();+ let (_, _, body) = raw(state_for(&f, ServeMode::Global), "/manifest.webmanifest").await;+ let manifest: serde_json::Value = serde_json::from_slice(&body).expect("manifest is JSON");++ assert_eq!(manifest["display"], "standalone");+ assert!(manifest["name"].is_string());++ for icon in manifest["icons"].as_array().unwrap() {+ let src = icon["src"].as_str().unwrap();+ let (status, mime, bytes) = raw(state_for(&f, ServeMode::Global), &format!("/{src}")).await;+ assert_eq!(status, StatusCode::OK, "icon {src}");+ assert_eq!(mime, "image/png", "icon {src}");+ // PNG magic: a manifest pointing at something that is not an image is+ // accepted by the manifest parser and rejected by the installer.+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n", "icon {src} is not a PNG");+ }+}++/// The service worker must not cache `/api/*`. A cached board shows a stale+/// phase status with a fresh-looking timestamp, which is worse than an error.+#[tokio::test]+async fn the_service_worker_leaves_the_api_alone() {+ let f = fixture();+ let (_, _, body) = raw(state_for(&f, ServeMode::Global), "/sw.js").await;+ let js = String::from_utf8_lossy(&body);+ assert!(+ js.contains("/api/"),+ "the worker must mention /api/ to exclude it"+ );+ assert!(+ js.contains("startsWith(\"/api/\")"),+ "the worker no longer excludes /api/ from caching"+ );+}++// ββ writes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++async fn send(+ state: std::sync::Arc<ServerState>,+ method: &str,+ uri: &str,+ body: Option<serde_json::Value>,+) -> (StatusCode, serde_json::Value) {+ let app = agtx::web::routes::router(state);+ let mut req = Request::builder().method(method).uri(uri);+ let body = match body {+ Some(v) => {+ req = req.header("content-type", "application/json");+ Body::from(serde_json::to_vec(&v).unwrap())+ }+ None => Body::empty(),+ };+ let res = app.oneshot(req.body(body).unwrap()).await.unwrap();+ let status = res.status();+ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json = serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null);+ (status, json)+}++/// An action queues a row and says so. It must never report the board as moved:+/// only a running TUI drains `transition_requests`.+#[tokio::test]+async fn an_action_queues_rather_than_executing() {+ let f = fixture();+ let task = add_task(&f, "To plan", TaskStatus::Backlog);++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "move_to_planning" })),+ )+ .await;++ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["status"], "queued");+ assert_eq!(body["tui_connected"], false);++ // The row is really there, and the task itself has not moved.+ let db = Database::open_project(&f.project_path).unwrap();+ let queued = db.get_pending_transition_requests().unwrap();+ assert_eq!(queued.len(), 1);+ assert_eq!(queued[0].action, "move_to_planning");+ assert_eq!(+ db.get_task(&task.id).unwrap().unwrap().status,+ TaskStatus::Backlog,+ "the API must not move the task itself"+ );++ // And the client can poll it.+ let rid = body["request_id"].as_str().unwrap();+ let (status, poll) = get(+ state_for(&f, ServeMode::Global),+ &format!("/api/projects/{}/requests/{rid}", f.project_id),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(poll["status"], "pending");+}++/// A client is not the authority on what it may do. Its copy of the task can be+/// seconds old, so the same policy that rendered the buttons is enforced again+/// on arrival.+#[tokio::test]+async fn an_action_the_task_does_not_permit_is_refused() {+ let f = fixture();+ let task = add_task(&f, "Backlog task", TaskStatus::Backlog);++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "move_to_done" })),+ )+ .await;++ assert_eq!(status, StatusCode::CONFLICT);+ assert!(body["error"].as_str().unwrap().contains("not available"));+ let db = Database::open_project(&f.project_path).unwrap();+ assert!(db.get_pending_transition_requests().unwrap().is_empty());+}++/// `escalate_to_user` means "stop and ask the person". Offering it to the+/// person is incoherent, so it is the orchestrator's alone.+#[tokio::test]+async fn a_human_cannot_escalate_to_themselves() {+ let f = fixture();+ let task = add_task(&f, "Running task", TaskStatus::Running);++ let (status, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "escalate_to_user" })),+ )+ .await;+ assert_eq!(status, StatusCode::CONFLICT);++ // The orchestrator still has it.+ let db = Database::open_project(&f.project_path).unwrap();+ let t = db.get_task(&task.id).unwrap().unwrap();+ assert!(agtx::core::actions::allowed_actions(+ &t,+ true,+ agtx::core::actions::CallerKind::Orchestrator+ )+ .contains(&"escalate_to_user".to_string()));+}++/// An unknown verb is malformed and will never work; a verb the task does not+/// currently permit may work later. A client that cannot tell them apart either+/// retries forever or gives up too early.+#[tokio::test]+async fn an_unknown_verb_is_a_400_not_a_409() {+ let f = fixture();+ let task = add_task(&f, "Task", TaskStatus::Backlog);++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "rm_minus_rf" })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(body["error"].as_str().unwrap().contains("unknown action"));+}++/// Dependencies are the one refusal that clears on its own, so it says so+/// rather than reading as an invalid request.+#[tokio::test]+async fn a_dependency_refusal_explains_itself() {+ let f = fixture();+ let db = Database::open_project(&f.project_path).unwrap();+ let dep = Task::new("Dependency", "claude", &f.project_id);+ db.create_task(&dep).unwrap();+ let mut blocked = Task::new("Blocked", "claude", &f.project_id);+ blocked.referenced_tasks = Some(dep.id.clone());+ db.create_task(&blocked).unwrap();++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, blocked.id),+ Some(serde_json::json!({ "action": "move_to_planning" })),+ )+ .await;+ assert_eq!(status, StatusCode::CONFLICT);+ assert!(+ body["error"].as_str().unwrap().contains("dependencies"),+ "got {}",+ body["error"]+ );++ // `research` is not a forward transition and stays available.+ let (status, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, blocked.id),+ Some(serde_json::json!({ "action": "research" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+}++// ββ task CRUD βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn a_task_can_be_created_edited_and_deleted() {+ let f = fixture();+ let base = format!("/api/projects/{}/tasks", f.project_id);++ let (status, created) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &base,+ Some(serde_json::json!({ "title": " From the phone ", "description": "hi" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ // Trimmed, not stored with its whitespace.+ assert_eq!(created["title"], "From the phone");+ assert_eq!(created["status"], "backlog");+ let id = created["id"].as_str().unwrap().to_string();++ let (status, edited) = send(+ state_for(&f, ServeMode::Global),+ "PATCH",+ &format!("{base}/{id}"),+ Some(serde_json::json!({ "title": "Renamed" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(edited["title"], "Renamed");++ let (status, _) = send(+ state_for(&f, ServeMode::Global),+ "DELETE",+ &format!("{base}/{id}"),+ None,+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ let db = Database::open_project(&f.project_path).unwrap();+ assert!(db.get_task(&id).unwrap().is_none());+}++/// Editing or deleting a task past Backlog would change the work under a+/// running agent β the same rule the MCP tools enforce.+#[tokio::test]+async fn only_backlog_tasks_can_be_edited_or_deleted() {+ let f = fixture();+ let running = add_task(&f, "In flight", TaskStatus::Running);+ let base = format!("/api/projects/{}/tasks/{}", f.project_id, running.id);++ for (method, body) in [+ ("PATCH", Some(serde_json::json!({ "title": "nope" }))),+ ("DELETE", None),+ ] {+ let (status, json) = send(state_for(&f, ServeMode::Global), method, &base, body).await;+ assert_eq!(status, StatusCode::CONFLICT, "{method} was allowed");+ assert!(json["error"].as_str().unwrap().contains("Backlog"));+ }++ let db = Database::open_project(&f.project_path).unwrap();+ assert!(db.get_task(&running.id).unwrap().is_some());+}++#[tokio::test]+async fn a_task_needs_a_usable_title() {+ let f = fixture();+ let base = format!("/api/projects/{}/tasks", f.project_id);++ for title in ["", " ", "\t\n "] {+ let (status, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &base,+ Some(serde_json::json!({ "title": title })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{title:?} was accepted");+ }++ let too_long = "x".repeat(agtx::core::actions::MAX_TASK_TITLE_CHARS + 1);+ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &base,+ Some(serde_json::json!({ "title": too_long })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(body["error"].as_str().unwrap().contains("maximum"));+}++/// A reference to a task that does not exist becomes a dependency nothing can+/// satisfy, leaving the referring task stuck in Backlog with no visible cause.+#[tokio::test]+async fn a_reference_to_a_missing_task_is_refused() {+ let f = fixture();+ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks", f.project_id),+ Some(serde_json::json!({ "title": "Refers to a ghost", "referenced_tasks": "nope" })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(body["error"].as_str().unwrap().contains("not found"));+}++/// A runaway client β an optimistic UI retrying a failing action in a render+/// loop β must not be able to queue unbounded work for the TUI.+#[tokio::test]+async fn writes_are_rate_limited() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);+ let base = format!("/api/projects/{}/tasks", f.project_id);++ let mut limited = false;+ for i in 0..200 {+ let (status, _) = send(+ state.clone(),+ "POST",+ &base,+ Some(serde_json::json!({ "title": format!("task {i}") })),+ )+ .await;+ if status == StatusCode::TOO_MANY_REQUESTS {+ limited = true;+ break;+ }+ }+ assert!(limited, "the write budget never kicked in");++ // Reads are unaffected: a client that hit the ceiling must still be able to+ // see the board it just changed.+ let (status, _) = get(state, &format!("/api/projects/{}/tasks", f.project_id)).await;+ assert_eq!(status, StatusCode::OK);+}++// ββ live pane socket ββββββββββββββββββββββββββββββββββββββββββββββββββββ++use agtx::web::ws::{ClientMessage, ServerMessage, Subscription};++/// The browser writes these by hand, so a rename that nothing pins breaks the+/// live view silently: the socket connects, the subscribe is rejected as a bad+/// message, and the pane just stays empty.+#[test]+fn the_socket_wire_format_is_what_the_client_writes() {+ let sub: ClientMessage =+ serde_json::from_str(r#"{"type":"subscribe","project_id":"p","task_id":"t"}"#).unwrap();+ assert!(matches!(+ sub,+ ClientMessage::Subscribe { project_id, task_id } if project_id == "p" && task_id == "t"+ ));++ let un: ClientMessage = serde_json::from_str(r#"{"type":"unsubscribe"}"#).unwrap();+ assert!(matches!(un, ClientMessage::Unsubscribe));++ // And the three the client switches on.+ let frame = serde_json::to_string(&ServerMessage::Frame {+ task_id: "t",+ content: "hi",+ })+ .unwrap();+ assert_eq!(frame, r#"{"type":"frame","task_id":"t","content":"hi"}"#);+ assert_eq!(+ serde_json::to_string(&ServerMessage::Gone { task_id: "t" }).unwrap(),+ r#"{"type":"gone","task_id":"t"}"#+ );+ assert!(serde_json::to_string(&ServerMessage::Error {+ message: "nope".into()+ })+ .unwrap()+ .starts_with(r#"{"type":"error""#));+}++/// `Subscription` holds a `dyn TmuxOperations`, which has no business+/// implementing `Debug` just so a test can call `unwrap_err`.+fn subscribe_err(state: &ServerState, pid: &str, tid: &str) -> String {+ Subscription::open(state, pid, tid)+ .err()+ .expect("expected a refusal")+}++/// Subscribing is where every "why is my terminal blank" question gets its+/// answer, so each refusal has to name its own cause rather than share one.+#[tokio::test]+async fn subscribing_refuses_with_a_specific_reason() {+ let f = fixture();+ let state = state_for(&f, ServeMode::Global);++ let err = subscribe_err(&state, "no-such-project", "t");+ assert!(err.contains("no-such-project"), "got {err}");++ let err = subscribe_err(&state, &f.project_id, "no-such-task");+ assert!(err.contains("no-such-task"), "got {err}");++ // A task with no tmux session has no pane to stream β the common case for+ // anything in Backlog.+ let idle = add_task(&f, "Never started", TaskStatus::Backlog);+ let err = subscribe_err(&state, &f.project_id, &idle.id);+ assert!(err.contains("no active session"), "got {err}");+}++/// `/ws` must be a real route rather than falling through to the SPA shell β+/// a plain GET without upgrade headers is a 400 from axum, not a 404 or HTML.+#[tokio::test]+async fn the_socket_route_exists() {+ let f = fixture();+ let app = agtx::web::routes::router(state_for(&f, ServeMode::Global));+ let res = app+ .oneshot(Request::builder().uri("/ws").body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_ne!(res.status(), StatusCode::NOT_FOUND);+ let mime = res+ .headers()+ .get(axum::http::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .unwrap_or("");+ assert!(!mime.contains("text/html"), "/ws fell through to the shell");+}++// ββ /input ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++fn running_task(f: &Fixture) -> Task {+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new("Running", "claude", &f.project_id);+ t.status = TaskStatus::Running;+ t.session_name = Some("agtx-test-nonexistent:pane".to_string());+ db.create_task(&t).unwrap();+ t+}++/// Text and keys are different requests, and the server must not have to guess+/// which was meant: `send-keys` without `-l` resolves anything matching a key+/// name *as that key*, so a message of "Space" would arrive as `0x20`.+#[tokio::test]+async fn input_needs_exactly_one_of_text_or_key() {+ let f = fixture();+ let t = running_task(&f);+ let uri = format!("/api/projects/{}/tasks/{}/input", f.project_id, t.id);++ for body in [+ serde_json::json!({}),+ serde_json::json!({ "text": "hi", "key": "Enter" }),+ ] {+ let (status, _) = send(state_for(&f, ServeMode::Global), "POST", &uri, Some(body)).await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ }+}++/// A closed key set is deliberate: forwarding arbitrary tmux key names would+/// let a request send `C-d`, an EOF that ends the agent's session, or `C-u`,+/// which kills the composer line.+#[tokio::test]+async fn only_known_keys_are_forwarded() {+ let f = fixture();+ let t = running_task(&f);+ let uri = format!("/api/projects/{}/tasks/{}/input", f.project_id, t.id);++ for key in ["C-d", "C-u", "M-x", "F13", "PageUp", ""] {+ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &uri,+ Some(serde_json::json!({ "key": key })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST, "{key:?} was accepted");+ assert!(body["error"].as_str().unwrap().contains("unsupported key"));+ }++ // What the chips actually send is all accepted by the parser.+ for key in [+ "y", "n", "1", "2", "3", "Enter", "Escape", "Up", "Down", "C-c",+ ] {+ assert!(+ agtx::core::input::PaneKey::parse(key).is_some(),+ "the UI offers {key:?} but the server rejects it"+ );+ }+}++/// Research and review are input-capable, but still require a session.+#[tokio::test]+async fn input_only_reaches_an_active_phase() {+ let f = fixture();+ for status in [+ TaskStatus::Backlog,+ TaskStatus::Planning,+ TaskStatus::Running,+ TaskStatus::Review,+ TaskStatus::Done,+ ] {+ let mut t = add_task(&f, &format!("Task {}", status.as_str()), status);+ let uri = format!("/api/projects/{}/tasks/{}/input", f.project_id, t.id);+ let (code, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &uri,+ Some(serde_json::json!({ "text": "hello" })),+ )+ .await;+ assert_eq!(+ code,+ if status == TaskStatus::Done {+ StatusCode::CONFLICT+ } else {+ StatusCode::NOT_FOUND+ }+ );+ t.session_name = Some("test:agent".into());+ Database::open_project(&f.project_path)+ .unwrap()+ .update_task(&t)+ .unwrap();+ // Invalid input reaches payload validation without invoking real tmux.+ let (code, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &uri,+ Some(serde_json::json!({ "text": "hello", "key": "Enter" })),+ )+ .await;+ assert_eq!(+ code,+ if status == TaskStatus::Done {+ StatusCode::CONFLICT+ } else {+ StatusCode::BAD_REQUEST+ }+ );+ }+}++/// The same 4096-byte cap and null-byte rule `send_to_task` enforces, so the+/// two callers refuse the same messages.+#[tokio::test]+async fn oversized_and_null_bearing_messages_are_refused() {+ let f = fixture();+ let t = running_task(&f);+ let uri = format!("/api/projects/{}/tasks/{}/input", f.project_id, t.id);++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &uri,+ Some(serde_json::json!({ "text": "x".repeat(4097) })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(body["error"].as_str().unwrap().contains("4096"));++ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &uri,+ Some(serde_json::json!({ "text": format!("before{}after", char::from(0u8)) })),+ )+ .await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+ assert!(body["error"].as_str().unwrap().contains("null"));+}++/// The one-shot `/pane` answers JSON, so it must not carry the SGR escapes the+/// live socket deliberately keeps.+#[test]+fn the_one_shot_capture_is_plain_text() {+ let coloured = "\u{1b}[1;31mRED\u{1b}[0m plain \u{1b}[32mgreen\u{1b}[0m";+ assert_eq!(agtx::web::routes::strip_sgr(coloured), "RED plain green");+ // Text with no escapes is untouched, including the box-drawing an agent TUI+ // is full of.+ let plain = "β β done β\nββββββββββ";+ assert_eq!(agtx::web::routes::strip_sgr(plain), plain);+}++// ββ access token ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// A state that requires pairing, so the auth layer is actually exercised β+/// the other tests run unauthenticated, as a loopback bind does.+fn guarded(f: &Fixture) -> std::sync::Arc<ServerState> {+ let _ = f;+ ServerState::with_auth(ServeMode::Global, true)+}++/// Pair a device directly and return its token.+fn paired_token(label: &str) -> String {+ agtx::web::auth::pair_device(label, None).expect("pairing")+}++async fn with_auth(+ state: std::sync::Arc<ServerState>,+ uri: &str,+ bearer: Option<&str>,+) -> StatusCode {+ let app = agtx::web::routes::router(state);+ let mut req = Request::builder().uri(uri);+ if let Some(b) = bearer {+ req = req.header("authorization", format!("Bearer {b}"));+ }+ app.oneshot(req.body(Body::empty()).unwrap())+ .await+ .unwrap()+ .status()+}++#[tokio::test]+async fn the_api_requires_the_token() {+ let f = fixture();+ assert_eq!(+ with_auth(guarded(&f), "/api/health", None).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some("wrong")).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&paired_token("test"))).await,+ StatusCode::OK+ );+}++/// Writes are behind the same gate as reads. Worth its own assertion because+/// the middleware is layered once and a route registered outside that layer+/// would be open with nothing to notice it.+#[tokio::test]+async fn every_api_route_is_behind_the_token() {+ let f = fixture();+ let t = add_task(&f, "Task", TaskStatus::Backlog);+ let pid = &f.project_id;++ for (method, uri) in [+ ("GET", format!("/api/projects")),+ ("GET", format!("/api/projects/{pid}/tasks")),+ ("GET", format!("/api/projects/{pid}/tasks/{}", t.id)),+ ("GET", format!("/api/projects/{pid}/tasks/{}/diff", t.id)),+ ("GET", format!("/api/projects/{pid}/tasks/{}/pane", t.id)),+ ("POST", format!("/api/projects/{pid}/tasks/{}/action", t.id)),+ ("POST", format!("/api/projects/{pid}/tasks/{}/input", t.id)),+ ("POST", format!("/api/projects/{pid}/tasks")),+ ("PATCH", format!("/api/projects/{pid}/tasks/{}", t.id)),+ ("DELETE", format!("/api/projects/{pid}/tasks/{}", t.id)),+ ] {+ let app = agtx::web::routes::router(guarded(&f));+ let res = app+ .oneshot(+ Request::builder()+ .method(method)+ .uri(&uri)+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ res.status(),+ StatusCode::UNAUTHORIZED,+ "{method} {uri} answered without a token"+ );+ }+}++/// The shell must stay open. A browser cannot put a header on the initial+/// navigation, so gating the assets would mean carrying the token in the URL of+/// every page load β and they are this app's own JS and CSS, not board data.+#[tokio::test]+async fn the_shell_loads_without_a_token() {+ let f = fixture();+ for path in [+ "/",+ "/index.html",+ "/app.js",+ "/api.js",+ "/ansi.js",+ "/app.css",+ ] {+ assert_eq!(+ with_auth(guarded(&f), path, None).await,+ StatusCode::OK,+ "{path} required a token"+ );+ }+}++/// A real handshake, minus the token.+///+/// The `/ws` route is exempt from the header middleware β a browser cannot put+/// `Authorization` on an upgrade β so this is the assertion that the exemption+/// did not simply leave the socket open. It has to be a *genuine* handshake:+/// `WebSocketUpgrade` is an extractor, so a plain GET is rejected 400 before+/// the handler's token check ever runs, and testing that proves nothing.+fn ws_handshake(uri: &str, protocol: Option<&str>) -> Request<Body> {+ let mut req = Request::builder()+ .uri(uri)+ .header("connection", "Upgrade")+ .header("upgrade", "websocket")+ .header("sec-websocket-version", "13")+ .header("sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ==");+ if let Some(p) = protocol {+ req = req.header("sec-websocket-protocol", p);+ }+ req.body(Body::empty()).unwrap()+}++#[tokio::test]+async fn the_socket_requires_the_token_by_subprotocol() {+ let f = fixture();++ // No subprotocol at all.+ let res = agtx::web::routes::router(guarded(&f))+ .oneshot(ws_handshake("/ws", None))+ .await+ .unwrap();+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);++ // A subprotocol carrying the wrong token.+ let res = agtx::web::routes::router(guarded(&f))+ .oneshot(ws_handshake("/ws", Some("agtx.token.wrong")))+ .await+ .unwrap();+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);++ // The accepting case is deliberately not asserted here. `WebSocketUpgrade`+ // needs a real hyper `OnUpgrade` extension, which `oneshot` cannot supply β+ // a correct token gets 426 Upgrade Required from the extractor rather than+ // 101, so an assertion here would be testing the harness. What matters is+ // that the *refusals* happen before the upgrade, which is what the two+ // above pin. The accept path and the subprotocol echo were verified against+ // a browser.+}++/// Comparison is constant-time, so it must still be *correct* β the obvious way+/// to write that loop is to get the length check wrong.+#[test]+fn token_comparison_accepts_only_an_exact_match() {+ use agtx::web::auth::token_matches;+ assert!(token_matches("abc123", "abc123"));+ assert!(!token_matches("abc123", "abc124"));+ assert!(!token_matches("abc123", "abc12"));+ assert!(!token_matches("abc123", "abc1234"));+ assert!(!token_matches("abc123", ""));+ assert!(!token_matches("", "abc123"));+}++// ββ pairing QR ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// Decode the rendered half-blocks back into a module grid.+///+/// Each cell is `ESC[<fg>m ESC[<bg>m β`, where the foreground paints the upper+/// module and the background the lower one.+fn qr_grid(rendered: &str) -> Vec<Vec<bool>> {+ let mut grid: Vec<Vec<bool>> = Vec::new();+ for line in rendered.lines() {+ let (mut upper, mut lower) = (Vec::new(), Vec::new());+ // Split on the block character; each chunk before one holds its colours.+ for cell in line.split('β').filter(|c| !c.is_empty()) {+ if cell.contains("[0m") {+ continue; // the row reset+ }+ upper.push(cell.contains("[30m"));+ lower.push(cell.contains("[40m"));+ }+ if !upper.is_empty() {+ grid.push(upper);+ grid.push(lower);+ }+ }+ grid+}++/// The two ways a QR that *looks* fine fails to scan: no quiet zone, and+/// finder patterns that are wrong or in the wrong corners. Neither is visible+/// by eye in a terminal, and both make a phone simply do nothing.+#[test]+fn the_pairing_qr_is_scannable() {+ let url = "http://192.168.178.26:8787/#token=be29ea5a70c64030a63526d89f24ba070866a9e273664767";+ let rendered = agtx::web::qr::render(url).expect("a URL always fits a QR");+ let grid = qr_grid(&rendered);++ let w = grid[0].len();+ let h = grid.len();+ assert!(+ w >= 21 + 8,+ "grid is {w} wide, smaller than the smallest QR plus its quiet zone"+ );+ assert!(grid.iter().all(|r| r.len() == w), "ragged grid");++ // Quiet zone: four light modules on every side. Without it a decoder cannot+ // find the code's edges and gives up silently.+ for y in 0..4 {+ assert!(+ !grid[y].iter().any(|m| *m),+ "row {y} of the quiet zone has a dark module"+ );+ assert!(+ !grid[h - 1 - y].iter().any(|m| *m),+ "bottom quiet zone is not clear"+ );+ }+ for (y, row) in grid.iter().enumerate() {+ assert!(+ !row[..4].iter().any(|m| *m),+ "left quiet zone dirty at row {y}"+ );+ assert!(+ !row[w - 4..].iter().any(|m| *m),+ "right quiet zone dirty at row {y}"+ );+ }++ // Finder patterns in three corners. Checking all three is what catches a+ // transposed x/y, which is otherwise a perfectly plausible-looking square.+ const FINDER: [&str; 7] = [+ "#######", "#.....#", "#.###.#", "#.###.#", "#.###.#", "#.....#", "#######",+ ];+ let finder_at = |ox: usize, oy: usize| -> bool {+ FINDER.iter().enumerate().all(|(dy, row)| {+ row.chars()+ .enumerate()+ .all(|(dx, ch)| grid[oy + dy][ox + dx] == (ch == '#'))+ })+ };+ let size = w - 8;+ assert!(finder_at(4, 4), "no finder pattern top-left");+ assert!(finder_at(4 + size - 7, 4), "no finder pattern top-right");+ assert!(finder_at(4, 4 + size - 7), "no finder pattern bottom-left");+}++/// The QR is for a phone, and a phone cannot reach `127.0.0.1` on another+/// machine. Printing one there would scan perfectly and go nowhere.+#[test]+fn a_long_url_still_encodes() {+ // Longer than any realistic pairing URL, to prove the renderer picks a+ // bigger version rather than failing.+ let long = format!("http://192.168.178.26:8787/#token={}", "a".repeat(200));+ assert!(agtx::web::qr::render(&long).is_some());+}++// ββ merge-conflict triage βββββββββββββββββββββββββββββββββββββββββββββββ++/// Give the fixture repo a branch that conflicts with `main`, and one that+/// does not, so both answers are exercised against real git.+fn seed_conflict(dir: &Path) {+ let git = |args: &[&str]| {+ std::process::Command::new("git")+ .current_dir(dir)+ .args(args)+ .output()+ .expect("git");+ };+ // `task/demo` already edited a.txt; move main underneath it so the two+ // disagree on the same line.+ git(&["checkout", "-q", "main"]);+ std::fs::write(dir.join("a.txt"), "hello\nfrom-main\n").unwrap();+ git(&["commit", "-qam", "main moves"]);++ // And a branch that only adds a file, which merges cleanly.+ git(&["checkout", "-qb", "task/clean", "main"]);+ std::fs::write(dir.join("new.txt"), "fresh\n").unwrap();+ git(&["add", "-A"]);+ git(&["commit", "-qm", "clean"]);+ git(&["checkout", "-q", "task/demo"]);+}++fn review_task(f: &Fixture, title: &str, branch: &str) -> Task {+ let db = Database::open_project(&f.project_path).unwrap();+ let mut t = Task::new(title, "claude", &f.project_id);+ t.status = TaskStatus::Review;+ t.worktree_path = Some(f.project_path.to_string_lossy().to_string());+ t.branch_name = Some(branch.to_string());+ t.base_branch = Some("main".to_string());+ db.create_task(&t).unwrap();+ t+}++/// "Merges cleanly" and "not checked yet" must not look alike β one of them is+/// an answer someone merges on.+#[tokio::test]+async fn the_diff_reports_conflicts_against_the_base() {+ let f = fixture();+ seed_conflict(&f.project_path);++ let conflicting = review_task(&f, "Conflicting", "task/demo");+ let (status, body) = get(+ state_for(&f, ServeMode::Global),+ &format!(+ "/api/projects/{}/tasks/{}/diff",+ f.project_id, conflicting.id+ ),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(body["conflicted"], true);+ let files: Vec<&str> = body["conflicting_files"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v.as_str().unwrap())+ .collect();+ assert_eq!(files, vec!["a.txt"], "only the genuinely conflicting file");++ let clean = review_task(&f, "Clean", "task/clean");+ let (_, body) = get(+ state_for(&f, ServeMode::Global),+ &format!("/api/projects/{}/tasks/{}/diff", f.project_id, clean.id),+ )+ .await;+ assert_eq!(body["conflicted"], false);+ assert!(body["conflicting_files"].as_array().unwrap().is_empty());+}++/// A task that is not in Review is not asked about: the question is only+/// meaningful once work is up for merging, and a branch still being written to+/// would answer differently many times before anyone cared.+#[tokio::test]+async fn only_review_tasks_are_checked_for_conflicts() {+ let f = fixture();+ seed_conflict(&f.project_path);++ let db = Database::open_project(&f.project_path).unwrap();+ let mut running = Task::new("Still running", "claude", &f.project_id);+ running.status = TaskStatus::Running;+ running.worktree_path = Some(f.project_path.to_string_lossy().to_string());+ running.branch_name = Some("task/demo".to_string());+ db.create_task(&running).unwrap();++ let (_, body) = get(+ state_for(&f, ServeMode::Global),+ &format!("/api/projects/{}/tasks", f.project_id),+ )+ .await;+ let card = body+ .as_array()+ .unwrap()+ .iter()+ .find(|c| c["id"] == running.id)+ .unwrap();+ assert!(+ card["conflicted"].is_null(),+ "a Running task should not carry a conflict verdict"+ );+}++/// The board must not block on git. The first ask reports `null` and a+/// background pass fills the cache β checking N branches inside a request that+/// is polled every two seconds is the cost decision 3 refuses for phase status.+#[tokio::test]+async fn the_board_never_waits_on_the_conflict_check() {+ let f = fixture();+ seed_conflict(&f.project_path);+ let task = review_task(&f, "Conflicting", "task/demo");+ let state = state_for(&f, ServeMode::Global);++ let started = std::time::Instant::now();+ let (status, body) = get(+ state.clone(),+ &format!("/api/projects/{}/tasks", f.project_id),+ )+ .await;+ let first_ask = started.elapsed();+ assert_eq!(status, StatusCode::OK);+ assert!(+ first_ask < std::time::Duration::from_millis(500),+ "the board waited {first_ask:?} β it should answer from cache and refresh behind"+ );++ let card = body+ .as_array()+ .unwrap()+ .iter()+ .find(|c| c["id"] == task.id)+ .unwrap();+ assert!(card["conflicted"].is_null(), "first ask should be unknown");++ // The background pass lands within a poll or two.+ let mut seen = None;+ for _ in 0..40 {+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ let (_, body) = get(+ state.clone(),+ &format!("/api/projects/{}/tasks", f.project_id),+ )+ .await;+ let card = body+ .as_array()+ .unwrap()+ .iter()+ .find(|c| c["id"] == task.id)+ .cloned()+ .unwrap();+ if !card["conflicted"].is_null() {+ seen = Some(card);+ break;+ }+ }+ let card = seen.expect("the background pass never filled the conflict cache");+ assert_eq!(card["conflicted"], true);+}++// ββ pairing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[test]+fn a_pairing_code_is_single_use() {+ let codes = agtx::web::auth::PairingCodes::default();+ let code = codes.issue();++ assert!(codes.redeem(&code).is_ok());+ // Spent. A code that could be replayed is a credential anyone who saw the+ // screen keeps.+ assert_eq!(+ codes.redeem(&code),+ Err(agtx::web::auth::PairError::Unknown)+ );+}++/// Wrong codes are counted, and enough of them shut pairing until the next+/// launch. `/api/pair` is the one unauthenticated route, so it is the one that+/// must not be hammerable.+#[test]+fn repeated_bad_codes_lock_pairing_out() {+ let codes = agtx::web::auth::PairingCodes::default();+ let real = codes.issue();++ for _ in 0..agtx::web::auth::PAIRING_MAX_FAILURES {+ assert_eq!(+ codes.redeem("not-a-code"),+ Err(agtx::web::auth::PairError::Unknown)+ );+ }++ // Even the genuine code is refused now: the lockout is about the endpoint,+ // not about the code being wrong.+ assert_eq!(+ codes.redeem(&real),+ Err(agtx::web::auth::PairError::LockedOut)+ );+}++/// A device token is minted once and only its hash is kept, so the database+/// cannot hand the credential back to anyone who reads it.+#[tokio::test]+async fn a_paired_device_stores_only_a_hash() {+ let _f = fixture();+ let token = paired_token("Test phone");++ let db = Database::open_global().unwrap();+ let devices = db.list_mobile_devices().unwrap();+ assert_eq!(devices.len(), 1);+ assert_eq!(devices[0].label, "Test phone");+ assert_ne!(devices[0].token_hash, token, "the token itself was stored");+ assert_eq!(devices[0].token_hash, agtx::web::auth::sha(&token));+}++/// Revoking one device must not disturb the others β the whole reason this+/// replaced a single shared secret.+#[tokio::test]+async fn revoking_one_device_leaves_the_rest() {+ let f = fixture();+ let keep = paired_token("Keeper");+ let lose = paired_token("Lost phone");++ let db = Database::open_global().unwrap();+ let lost_id = db+ .list_mobile_devices()+ .unwrap()+ .into_iter()+ .find(|d| d.label == "Lost phone")+ .unwrap()+ .id;+ assert!(db.revoke_mobile_device(&lost_id).unwrap());+ // A second revoke reports false rather than succeeding twice.+ assert!(!db.revoke_mobile_device(&lost_id).unwrap());++ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&lose)).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&keep)).await,+ StatusCode::OK+ );+}++/// A pairing outlives the server that issued it. The device row is in the+/// global database and the token is in the phone's storage, so a home-screen+/// app reconnects to a later `agtx serve` without a new scan.+///+/// Locked down because the opposite β dropping devices on shutdown β is a+/// reasonable-looking change that would silently make every phone re-scan.+#[tokio::test]+async fn a_pairing_survives_the_server_that_issued_it() {+ let f = fixture();+ let token = agtx::web::auth::pair_device("Phone", Some("session-a")).expect("pairing");++ // A fresh state and router: the same thing a restarted `agtx serve` builds.+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&token)).await,+ StatusCode::OK,+ "the device had to pair again after a restart"+ );+ assert_eq!(Database::open_global().unwrap().list_mobile_devices().unwrap().len(), 1);+}++/// `revoke_session_devices` is scoped to one session, which is what would let a+/// future expiry or forget-on-exit policy be safe: `mobile_devices` is global,+/// so a second agtx serving another project must keep its devices.+#[tokio::test]+async fn revoking_a_session_leaves_another_sessions_devices() {+ let f = fixture();+ let mine = agtx::web::auth::pair_device("Mine", Some("session-a")).expect("pairing");+ let theirs = agtx::web::auth::pair_device("Theirs", Some("session-b")).expect("pairing");++ let db = Database::open_global().unwrap();+ assert_eq!(db.revoke_session_devices("session-a").unwrap(), 1);+ // Idempotent, and it never reaches beyond its own session.+ assert_eq!(db.revoke_session_devices("session-a").unwrap(), 0);++ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&mine)).await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(&theirs)).await,+ StatusCode::OK,+ "another agtx instance lost its device"+ );+}++/// A device paired through the API records the server's session. Pairing and+/// the scoped revoke live in different files, so a missing stamp would leave+/// the provenance blank with nothing failing.+#[tokio::test]+async fn pairing_over_the_api_records_the_serving_session() {+ let _f = fixture();+ let state = agtx::web::state::ServerState::with_session(+ ServeMode::Global,+ true,+ Some("session-a".to_string()),+ );+ let code = state.pairing.issue();+ let app = agtx::web::routes::router(state);++ let res = app+ .oneshot(+ Request::builder()+ .method("POST")+ .uri("/api/pair")+ .header("content-type", "application/json")+ .body(Body::from(format!(+ r#"{{"code":"{code}","label":"Phone"}}"#+ )))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let db = Database::open_global().unwrap();+ assert_eq!(+ db.list_mobile_devices().unwrap()[0].session_id.as_deref(),+ Some("session-a")+ );+}++/// An existing `serve-token` becomes a paired device rather than silently+/// ceasing to work β the phone that was already set up keeps connecting.+#[tokio::test]+async fn the_legacy_token_is_adopted_once() {+ let f = fixture();+ let cfg = tempfile::TempDir::new().unwrap();+ std::env::set_var("AGTX_CONFIG_DIR", cfg.path());++ let legacy = "legacy-token-value";+ std::fs::write(agtx::web::auth::token_path().unwrap(), legacy).unwrap();++ let migrated = agtx::web::auth::migrate_legacy_token(None).unwrap();+ assert_eq!(migrated.as_deref(), Some(legacy));+ assert_eq!(+ with_auth(guarded(&f), "/api/health", Some(legacy)).await,+ StatusCode::OK,+ "the previously paired device stopped working"+ );++ // The file is gone, so there is exactly one credential path, and a second+ // run is a no-op rather than a duplicate row.+ assert!(!agtx::web::auth::token_path().unwrap().exists());+ assert!(agtx::web::auth::migrate_legacy_token(None).unwrap().is_none());+ assert_eq!(+ Database::open_global()+ .unwrap()+ .list_mobile_devices()+ .unwrap()+ .len(),+ 1+ );++ std::env::remove_var("AGTX_CONFIG_DIR");+}++// ββ tunnel planning βββββββββββββββββββββββββββββββββββββββββββββββββββββ++use agtx::web::tunnel::{plan, TunnelScope};++/// `private` is `tailscale serve`; `public` is `funnel` or `cloudflared`. They+/// are a tailnet and the open internet, and Tailscale's own naming invites+/// confusing them.+#[test]+fn private_never_reaches_for_funnel() {+ let only_tailscale = |p: &str| p == "tailscale";+ let p = plan(TunnelScope::Private, 8787, &only_tailscale).unwrap();+ assert_eq!(p.program, "tailscale");+ assert!(p.args.contains(&"serve".to_string()));+ assert!(+ !p.args.contains(&"funnel".to_string()),+ "private must never use funnel β that is the public one"+ );+ assert!(p.args.iter().any(|a| a.contains("127.0.0.1:8787")));++ // And it undoes itself: `tailscale serve` configures the daemon, so it+ // outlives this process unless explicitly turned off.+ let teardown = p.teardown.expect("tailscale serve must be torn down");+ assert!(teardown.contains(&"off".to_string()));+}++#[test]+fn public_prefers_cloudflared_and_says_where_it_reaches() {+ let both = |_: &str| true;+ let p = plan(TunnelScope::Public, 9000, &both).unwrap();+ assert_eq!(p.program, "cloudflared");+ // The child *is* the tunnel, so dying is the teardown.+ assert!(p.teardown.is_none());+ assert!(p.reach.contains("internet"));++ let only_tailscale = |x: &str| x == "tailscale";+ let p = plan(TunnelScope::Public, 9000, &only_tailscale).unwrap();+ assert!(p.args.contains(&"funnel".to_string()));+ assert!(p.reach.contains("internet"));+}++#[test]+fn a_missing_provider_explains_the_alternative() {+ let none = |_: &str| false;+ let err = plan(TunnelScope::Private, 8787, &none)+ .unwrap_err()+ .to_string();+ assert!(err.contains("Tailscale"), "got {err}");++ let err = plan(TunnelScope::Public, 8787, &none)+ .unwrap_err()+ .to_string();+ assert!(+ err.contains("--tunnel private"),+ "public should point at the safer option: {err}"+ );+}++#[test]+fn tunnel_scope_is_never_guessed() {+ assert_eq!(TunnelScope::parse("private"), Some(TunnelScope::Private));+ assert_eq!(TunnelScope::parse("public"), Some(TunnelScope::Public));+ for bad in ["", "yes", "PUBLIC", "prviate", "funnel"] {+ assert_eq!(TunnelScope::parse(bad), None, "{bad:?} was accepted");+ }+}++/// A tunnel is exposure even though the listener stays on loopback, so pairing+/// must be required. Reading only the bind address is how a tunnelled server+/// ends up open.+#[test]+fn a_tunnel_counts_as_off_loopback() {+ let mut opts = agtx::web::ServeOptions::default();+ assert!(opts.is_loopback(), "a plain serve is loopback");+ opts.tunnel = Some(TunnelScope::Private);+ assert!(+ !opts.is_loopback(),+ "a tunnelled server must require pairing even though it binds 127.0.0.1"+ );+}++// ββ the publish gate ββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// `task_runtime` exists for a reader outside the TUI process. With no such+/// reader the write is pure cost β a transaction every couple of seconds for+/// the life of every session, on the chance a phone might one day connect. So+/// a board request is what turns publishing on.+#[tokio::test]+async fn asking_for_a_board_marks_it_as_watched() {+ let f = fixture();+ let db = Database::open_global().unwrap();+ let path = f.project_path.to_string_lossy().to_string();+ let window = chrono::Duration::seconds(600);++ assert!(+ !db.board_watched_recently(&path, window).unwrap(),+ "nothing has asked for this board yet"+ );++ let (status, _) = get(+ state_for(&f, ServeMode::Global),+ &format!("/api/projects/{}/tasks", f.project_id),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ assert!(+ db.board_watched_recently(&path, window).unwrap(),+ "a board request should mark the project as watched"+ );+}++/// The marker ages out, so publishing stops again once nobody is reading.+#[tokio::test]+async fn a_stale_watch_does_not_keep_publishing_alive() {+ let f = fixture();+ let db = Database::open_global().unwrap();+ let path = f.project_path.to_string_lossy().to_string();++ db.note_board_watched(&path).unwrap();+ assert!(db+ .board_watched_recently(&path, chrono::Duration::seconds(600))+ .unwrap());+ // Zero window: every marker is already expired.+ assert!(!db+ .board_watched_recently(&path, chrono::Duration::zero())+ .unwrap());+ // And a project nobody ever asked about is never watched.+ assert!(!db+ .board_watched_recently("/not/a/project", chrono::Duration::seconds(600))+ .unwrap());+}++/// Reads other than the board must not switch publishing on. Opening one task+/// detail is not a reason to start mirroring the whole project's phase status.+#[tokio::test]+async fn only_a_board_request_counts_as_watching() {+ let f = fixture();+ let task = add_task(&f, "A task", TaskStatus::Backlog);+ let db = Database::open_global().unwrap();+ let path = f.project_path.to_string_lossy().to_string();+ let window = chrono::Duration::seconds(600);++ for uri in [+ "/api/health".to_string(),+ "/api/projects".to_string(),+ format!("/api/projects/{}/tasks/{}", f.project_id, task.id),+ ] {+ let (status, _) = get(state_for(&f, ServeMode::Global), &uri).await;+ assert_eq!(status, StatusCode::OK, "{uri}");+ }++ assert!(+ !db.board_watched_recently(&path, window).unwrap(),+ "a non-board read switched publishing on"+ );+}++/// Real upgrades exercise the running socket, not just the HTTP auth gate.+#[tokio::test]+async fn revoking_a_device_closes_its_existing_socket_only() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ use tokio::time::{timeout, Duration};+ let f = fixture();+ let lost = paired_token("Lost phone");+ let kept = paired_token("Kept phone");+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let app = agtx::web::routes::router(guarded(&f));+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ async fn connect(address: std::net::SocketAddr, token: &str) -> tokio::net::TcpStream {+ let mut stream = tokio::net::TcpStream::connect(address).await.unwrap();+ let request = format!("GET /ws HTTP/1.1\r\nHost: {address}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Protocol: agtx.token.{token}\r\n\r\n");+ stream.write_all(request.as_bytes()).await.unwrap();+ let mut response = Vec::new();+ while !response.ends_with(b"\r\n\r\n") {+ response.push(stream.read_u8().await.unwrap());+ }+ assert!(String::from_utf8(response)+ .unwrap()+ .starts_with("HTTP/1.1 101"));+ stream+ }+ let mut lost_socket = timeout(Duration::from_secs(3), connect(address, &lost))+ .await+ .unwrap();+ let mut kept_socket = timeout(Duration::from_secs(3), connect(address, &kept))+ .await+ .unwrap();+ let device = agtx::web::auth::device_for_token(&lost).unwrap();+ Database::open_global()+ .unwrap()+ .revoke_mobile_device(&device.id)+ .unwrap();+ // An idle socket must be closed too: no new request triggers this check.+ let opcode = timeout(Duration::from_secs(3), lost_socket.read_u8())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(opcode & 0x0f, 8, "expected a WebSocket close frame");+ // A masked ping verifies the other connection is still usable.+ kept_socket+ .write_all(&[0x89, 0x80, 0, 0, 0, 0])+ .await+ .unwrap();+ let opcode = timeout(Duration::from_secs(3), kept_socket.read_u8())+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ opcode & 0x0f,+ 10,+ "expected a pong from the retained device"+ );+ server.abort();+}++#[tokio::test]+async fn completion_refuses_dirty_worktrees_without_queueing() {+ let f = fixture();+ let mut task = add_task(&f, "Dirty review", TaskStatus::Review);+ task.worktree_path = Some(f.project_path.to_string_lossy().into_owned());+ let db = Database::open_project(&f.project_path).unwrap();+ db.update_task(&task).unwrap();+ // Tracked, staged and untracked changes must all block completion.+ for kind in ["tracked", "staged", "untracked"] {+ if kind == "untracked" {+ std::fs::write(f.project_path.join("new.txt"), "new work").unwrap();+ } else {+ std::fs::write(f.project_path.join("a.txt"), "unfinished work").unwrap();+ if kind == "staged" {+ assert!(std::process::Command::new("git")+ .current_dir(&f.project_path)+ .args(["add", "a.txt"])+ .status()+ .unwrap()+ .success());+ }+ }+ let (status, body) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "move_to_done" })),+ )+ .await;+ assert_eq!(status, StatusCode::CONFLICT, "{kind}");+ assert!(body["error"]+ .as_str()+ .unwrap()+ .contains("Uncommitted changes"));+ assert!(db.get_pending_transition_requests().unwrap().is_empty());+ // Restore only the tracked test file before the next variant.+ assert!(std::process::Command::new("git")+ .current_dir(&f.project_path)+ .args([+ "restore",+ "--source=HEAD",+ "--staged",+ "--worktree",+ "a.txt"+ ])+ .status()+ .unwrap()+ .success());+ }+ assert_eq!(+ db.get_task(&task.id).unwrap().unwrap().status,+ TaskStatus::Review+ );+}++#[tokio::test]+async fn completion_allows_a_clean_worktree() {+ let f = fixture();+ let mut task = add_task(&f, "Clean review", TaskStatus::Review);+ task.worktree_path = Some(f.project_path.to_string_lossy().into_owned());+ let db = Database::open_project(&f.project_path).unwrap();+ db.update_task(&task).unwrap();+ let (status, _) = send(+ state_for(&f, ServeMode::Global),+ "POST",+ &format!("/api/projects/{}/tasks/{}/action", f.project_id, task.id),+ Some(serde_json::json!({ "action": "move_to_done" })),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ assert_eq!(db.get_pending_transition_requests().unwrap().len(), 1);+}diff --git a/web/ansi.js b/web/ansi.jsnew file mode 100644index 0000000..c3d11ca--- /dev/null+++ b/web/ansi.js@@ -0,0 +1,156 @@+// Render a tmux pane capture as HTML.+//+// This is deliberately *not* a terminal emulator, and does not need to be.+// Measured against tmux 3.5a: `capture-pane -e -p` emits only `ESC[β¦m` β SGR+// colour and attributes. No cursor motion, no scroll regions, no alternate+// screen, because the capture is a snapshot of an already-rendered grid rather+// than a stream of terminal control. There is nothing here for an emulator to+// emulate, so ~150 lines replaces a 250KB dependency and keeps the app free of+// any npm build step (see `src/web/assets.rs`).+//+// If agtx ever grows a real PTY-backed terminal β deferred in the mobile plan β+// that is the point at which xterm.js earns its place, and this file is what it+// would replace.++/// xterm's standard 16, in the agtx palette's register so a pane sits in the+/// same picture as the board around it.+const BASE = [+ "#2a3140", "#ff8b7a", "#7ee787", "#ead49a", "#a0d2fa", "#d3a4f9", "#5cfff7", "#c8c3bc",+ "#5b6273", "#ffab9d", "#a2f0a9", "#f2e4bd", "#c2e2ff", "#e4c6ff", "#a5fff9", "#f2ece6",+];++/// The xterm 256-colour cube and greyscale ramp, computed rather than tabulated.+function xterm256(n) {+ if (n < 16) return BASE[n];+ if (n < 232) {+ const i = n - 16;+ const step = (v) => (v === 0 ? 0 : 55 + v * 40);+ const r = step(Math.floor(i / 36) % 6);+ const g = step(Math.floor(i / 6) % 6);+ const b = step(i % 6);+ return `rgb(${r},${g},${b})`;+ }+ const v = 8 + (n - 232) * 10;+ return `rgb(${v},${v},${v})`;+}++function blankState() {+ return { fg: null, bg: null, bold: false, dim: false, italic: false, underline: false, inverse: false };+}++/// Apply one SGR sequence's parameters to `st`.+function applySgr(st, params) {+ for (let i = 0; i < params.length; i++) {+ const p = params[i];+ switch (p) {+ case 0: Object.assign(st, blankState()); break;+ case 1: st.bold = true; break;+ case 2: st.dim = true; break;+ case 3: st.italic = true; break;+ case 4: st.underline = true; break;+ case 7: st.inverse = true; break;+ case 22: st.bold = false; st.dim = false; break;+ case 23: st.italic = false; break;+ case 24: st.underline = false; break;+ case 27: st.inverse = false; break;+ case 39: st.fg = null; break;+ case 49: st.bg = null; break;+ // Extended colour: `38;5;n` (256) or `38;2;r;g;b` (truecolor). The+ // sub-parameters are consumed here so they are not read as further SGR+ // codes β treating `38;5;1` as "38, then 5, then 1" would set blink and+ // a red foreground instead of colour 1.+ case 38:+ case 48: {+ const target = p === 38 ? "fg" : "bg";+ if (params[i + 1] === 5) {+ st[target] = xterm256(params[i + 2] ?? 0);+ i += 2;+ } else if (params[i + 1] === 2) {+ const [r, g, b] = [params[i + 2] ?? 0, params[i + 3] ?? 0, params[i + 4] ?? 0];+ st[target] = `rgb(${r},${g},${b})`;+ i += 4;+ }+ break;+ }+ default:+ if (p >= 30 && p <= 37) st.fg = BASE[p - 30];+ else if (p >= 90 && p <= 97) st.fg = BASE[p - 90 + 8];+ else if (p >= 40 && p <= 47) st.bg = BASE[p - 40];+ else if (p >= 100 && p <= 107) st.bg = BASE[p - 100 + 8];+ break;+ }+ }+}++function styleFor(st) {+ let fg = st.fg;+ let bg = st.bg;+ if (st.inverse) {+ // Swapped against the pane's own defaults, not against nothing: an inverse+ // run with no explicit colours is how a selection or a status bar is drawn,+ // and leaving it unstyled makes it vanish.+ [fg, bg] = [bg || "var(--surface)", fg || "var(--text)"];+ }+ const bits = [];+ if (fg) bits.push(`color:${fg}`);+ if (bg) bits.push(`background:${bg}`);+ if (st.bold) bits.push("font-weight:700");+ if (st.dim) bits.push("opacity:.65");+ if (st.italic) bits.push("font-style:italic");+ if (st.underline) bits.push("text-decoration:underline");+ return bits.join(";");+}++const SGR = /\x1b\[([0-9;]*)m/g;++/// Parse `text` into a document fragment of styled spans.+///+/// Returns a fragment rather than an HTML string so the caller never has to+/// think about escaping: pane content is agent output, which routinely contains+/// `<` and `&`, and one missed escape here would be an injection from anything+/// the agent happens to print.+export function renderAnsi(text) {+ const frag = document.createDocumentFragment();+ const st = blankState();+ let last = 0;++ const emit = (chunk) => {+ if (!chunk) return;+ const style = styleFor(st);+ if (!style) {+ frag.append(document.createTextNode(chunk));+ return;+ }+ const span = document.createElement("span");+ span.setAttribute("style", style);+ span.textContent = chunk;+ frag.append(span);+ };++ SGR.lastIndex = 0;+ let m;+ while ((m = SGR.exec(text)) !== null) {+ emit(text.slice(last, m.index));+ // An empty parameter list means SGR 0 β `ESC[m` is a reset.+ const params = m[1] === "" ? [0] : m[1].split(";").map((n) => parseInt(n, 10) || 0);+ applySgr(st, params);+ last = m.index + m[0].length;+ }+ emit(text.slice(last));++ // Any other escape that slipped through would render as mojibake. Strip the+ // C0 controls that are not newline or tab, since a pane capture should not+ // contain them and showing them as glyphs looks like corruption.+ return frag;+}++/// Replace `node`'s contents with `text` rendered.+///+/// A full replace per frame is the whole synchronisation story: every frame is+/// a complete pane, so there is no incremental state that can drift out of step+/// with the server.+export function paintPane(node, text) {+ // eslint-disable-next-line no-control-regex+ const cleaned = text.replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, "");+ node.replaceChildren(renderAnsi(cleaned));+}diff --git a/web/api.js b/web/api.jsnew file mode 100644index 0000000..a313634--- /dev/null+++ b/web/api.js@@ -0,0 +1,271 @@+// Thin wrappers over the API.+//+// Every call is same-origin: the page is served by the same `agtx serve` that+// answers /api, so there is no base URL to configure and nothing to get wrong+// when the tunnel hostname changes.++const TOKEN_KEY = "agtx.token";++/// Consume a credential from the URL fragment.+///+/// Two forms. `#pair=<code>` is the QR: a single-use code exchanged once for+/// this device's own token. `#token=<t>` is the older direct hand-off, kept so+/// a link from before per-device pairing still works.+///+/// Either way the secret has to leave the address bar immediately β it should+/// not sit in a screenshot, a shared link, or browser history. Fragments are+/// never sent to the server, which is why credentials travel this way rather+/// than in a query parameter.+///+/// Note the collision this avoids: the app's own router lives in the hash+/// (`#/p/...`), so the credential forms are consumed *before* the first route+/// is read, and the hash is replaced with the default route rather than+/// cleared β an empty hash leaves the router nothing to parse.+export async function captureCredential() {+ const hash = location.hash.replace(/^#/, "");++ if (hash.startsWith("token=")) {+ storeToken(decodeURIComponent(hash.slice("token=".length)));+ history.replaceState(null, "", `${location.pathname}#/`);+ return null;+ }++ if (!hash.startsWith("pair=")) return null;+ const code = decodeURIComponent(hash.slice("pair=".length));+ // Replace the hash *before* the exchange: a reload mid-request would+ // otherwise retry a code that is already spent and show a failure for+ // pairing that actually succeeded.+ history.replaceState(null, "", `${location.pathname}#/`);++ try {+ const res = await request("POST", "/api/pair", { code, label: deviceLabel() });+ storeToken(res.token);+ return { paired: res.label };+ } catch (e) {+ return { error: e.message };+ }+}++function storeToken(token) {+ if (!token) return;+ try {+ localStorage.setItem(TOKEN_KEY, token);+ } catch {+ // Private browsing, or storage disabled. The token still works for this+ // page load; it just will not survive a reload.+ memoryToken = token;+ }+}++/// A human-readable name for this device, for the revoke list.+///+/// Deliberately coarse. The list needs "which phone is this" answered well+/// enough to revoke the right row, and a full user-agent string is both longer+/// and worse at saying that.+function deviceLabel() {+ const ua = navigator.userAgent || "";+ const device =+ /iPhone/.test(ua) ? "iPhone"+ : /iPad/.test(ua) ? "iPad"+ : /Android/.test(ua) ? "Android"+ : /Macintosh/.test(ua) ? "Mac"+ : /Windows/.test(ua) ? "Windows"+ : /Linux/.test(ua) ? "Linux"+ : "device";+ const browser =+ /CriOS|Chrome/.test(ua) ? "Chrome"+ : /Firefox/.test(ua) ? "Firefox"+ : /Safari/.test(ua) ? "Safari"+ : null;+ return browser ? `${device} (${browser})` : device;+}++let memoryToken = null;++export function getToken() {+ if (memoryToken) return memoryToken;+ try {+ return localStorage.getItem(TOKEN_KEY) || null;+ } catch {+ return null;+ }+}++async function get(path) {+ return request("GET", path);+}++async function request(method, path, body) {+ const headers = { accept: "application/json" };+ if (body) headers["content-type"] = "application/json";+ const token = getToken();+ if (token) headers.authorization = `Bearer ${token}`;++ const res = await fetch(path, {+ method,+ headers,+ body: body ? JSON.stringify(body) : undefined,+ });+ if (!res.ok) {+ // The server answers errors as {"error": "..."} β prefer its wording over+ // a status code, since it says which id was not found.+ let detail = `HTTP ${res.status}`;+ try {+ const body = await res.json();+ if (body && body.error) detail = body.error;+ } catch {+ /* not JSON; the status is all we have */+ }+ if (res.status === 401) {+ // Nothing the user can fix by retrying: the page needs the link agtx+ // printed, and saying so beats an endless row of failed requests.+ const err = new Error(+ "This device is not authorised. Open the link agtx printed at startup β it carries the token.",+ );+ err.status = 401;+ throw err;+ }+ const err = new Error(detail);+ err.status = res.status;+ // 409 means "not yet" rather than "never": the board can move underneath a+ // phone between rendering a button and someone pressing it, and a client+ // should offer a refresh rather than tell the user they did something wrong.+ err.retryable = res.status === 409 || res.status === 429;+ throw err;+ }+ return res.json();+}++export const api = {+ health: () => get("/api/health"),+ projects: () => get("/api/projects"),+ tasks: (pid) => get(`/api/projects/${encodeURIComponent(pid)}/tasks`),+ task: (pid, tid) =>+ get(`/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}`),+ diff: (pid, tid) =>+ get(`/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}/diff`),+ pane: (pid, tid, lines = 200) =>+ get(+ `/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}/pane?lines=${lines}`,+ ),++ // Writes. `action` only *queues*: the board moves when a TUI drains the+ // request, which is what `requestStatus` reports.+ action: (pid, tid, action, reason) =>+ request(+ "POST",+ `/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}/action`,+ { action, reason },+ ),+ requestStatus: (pid, rid) =>+ get(`/api/projects/${encodeURIComponent(pid)}/requests/${encodeURIComponent(rid)}`),+ createTask: (pid, fields) =>+ request("POST", `/api/projects/${encodeURIComponent(pid)}/tasks`, fields),+ updateTask: (pid, tid, fields) =>+ request(+ "PATCH",+ `/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}`,+ fields,+ ),+ input: (pid, tid, payload) =>+ request(+ "POST",+ `/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}/input`,+ payload,+ ),+ deleteTask: (pid, tid) =>+ request(+ "DELETE",+ `/api/projects/${encodeURIComponent(pid)}/tasks/${encodeURIComponent(tid)}`,+ ),+};++/// How each action reads on a button. The API speaks verbs; a person reads+/// destinations, and "Start planning" is what the board's `m` key means.+export const ACTION_LABELS = {+ research: "Start research",+ move_forward: "Move forward",+ move_to_planning: "Start planning",+ move_to_running: "Start running",+ move_to_review: "Move to review",+ move_to_done: "Mark done",+ resume: "Resume",+ escalate_to_user: "Escalate",+};++/// The action a swipe performs β the one thing you would most likely want from+/// a card without opening it. Everything else needs the action sheet.+export const PRIMARY_ACTION = {+ backlog: "move_to_planning",+ planning: "move_forward",+ running: "move_forward",+ review: "move_to_done",+};++/// The board's five columns, in board order. `backlog` carries research, which+/// is why its label is not just "Backlog" β it matches `TaskStatus::display_name`.+export const COLUMNS = [+ { id: "backlog", label: "Backlog" },+ { id: "planning", label: "Planning" },+ { id: "running", label: "Running" },+ { id: "review", label: "Review" },+ { id: "done", label: "Done" },+];++/// Phase glyphs, matching the TUI's vocabulary so the two views read the same.+export const PHASE = {+ working: { glyph: "βΆ", label: "working" },+ blocked: { glyph: "?", label: "blocked" },+ idle: { glyph: "βΈ", label: "idle" },+ ready: { glyph: "β", label: "ready" },+ exited: { glyph: "β", label: "exited" },+};++/// A published phase older than this is a snapshot, not a reading: with no TUI+/// running nothing refreshes `task_runtime`. Generous next to the 2s refresh β+/// this marks "nobody is watching", not "the last tick was slow".+export const PHASE_STALE_SECS = 30;++export function isStale(task) {+ return typeof task.phase_age_secs === "number" && task.phase_age_secs > PHASE_STALE_SECS;+}++/// Whether a task is worth surfacing on the projects screen. Blocked outranks+/// the rest: a task waiting on a permission prompt is the one where a reply+/// from a phone actually unblocks something.+export function needsAttention(task) {+ if (task.escalation_note) return true;+ if (isStale(task)) return false;+ return task.phase_status === "blocked" || task.phase_status === "ready";+}++/// The keys agents actually ask for, in the order a thumb wants them.+///+/// A closed set, mirrored by `PaneKey::parse` on the server: forwarding+/// arbitrary key names would let a tap send `C-d`, which is an EOF that ends+/// the agent's session.+export const KEY_CHIPS = [+ { key: "y", label: "y" },+ { key: "n", label: "n" },+ { key: "1", label: "1" },+ { key: "2", label: "2" },+ { key: "3", label: "3" },+ { key: "Enter", label: "β" },+ { key: "Escape", label: "esc" },+ { key: "Up", label: "β" },+ { key: "Down", label: "β" },+ { key: "C-c", label: "^C" },+];++/// Phases whose pane can be typed into. Matches the server's own rule, so the+/// keyboard toggle is not offered where every keystroke would 409.+export const INPUTTABLE = new Set(["backlog", "planning", "running", "review"]);++/// The subprotocol that carries the token on a WebSocket handshake.+///+/// A browser cannot set `Authorization` there, and a query parameter would put+/// the credential in every access log. Mirrors `auth::WS_TOKEN_PREFIX`.+export function wsProtocols() {+ const token = getToken();+ return token ? [`agtx.token.${token}`] : [];+}diff --git a/web/app.css b/web/app.cssnew file mode 100644index 0000000..4427d89--- /dev/null+++ b/web/app.css@@ -0,0 +1,424 @@+/* agtx mobile β thumb-first, one column, no framework.+ Colours track the TUI's default theme so the two read as one product. */++:root {+ --bg: #11141a;+ --surface: #171b23;+ --surface-2: #1e232d;+ --border: #2a3140;+ --text: #f2ece6;+ --dim: #9c9991;+ --desc: #c4b0ac;+ --accent: #5cfff7;+ --selected: #ead49a;+ --column: #a0d2fa;+ --danger: #ff8b7a;+ --ok: #7ee787;+ --radius: 12px;+ /* Space for the home indicator / notch on iOS, zero elsewhere. */+ --safe-top: env(safe-area-inset-top, 0px);+ --safe-bottom: env(safe-area-inset-bottom, 0px);+}++@media (prefers-color-scheme: light) {+ :root {+ --bg: #f7f5f2;+ --surface: #ffffff;+ --surface-2: #efece7;+ --border: #ddd7cf;+ --text: #1d2129;+ --dim: #6b6862;+ --desc: #5c5550;+ --accent: #0f8f88;+ --selected: #9a7a1f;+ --column: #2f6ea8;+ --danger: #b3402c;+ --ok: #2b7a3d;+ }+}++* { box-sizing: border-box; }++html, body {+ margin: 0;+ padding: 0;+ background: var(--bg);+ color: var(--text);+ font: 15px/1.45 ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;+ /* The board scrolls, the page does not: a rubber-banding document under a+ sticky header is what makes a web app feel unlike an app. */+ overscroll-behavior-y: none;+}++.app { min-height: 100dvh; display: flex; flex-direction: column; }+.boot { padding: 2rem; color: var(--dim); }++/* ββ header βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */++.hdr {+ position: sticky;+ top: 0;+ z-index: 10;+ padding: calc(var(--safe-top) + 0.6rem) 0.9rem 0.6rem;+ background: color-mix(in srgb, var(--bg) 88%, transparent);+ backdrop-filter: blur(12px);+ border-bottom: 1px solid var(--border);+}+.hdr-row { display: flex; align-items: center; gap: 0.6rem; min-height: 32px; }+.hdr h1 { font-size: 1.05rem; margin: 0; font-weight: 600; letter-spacing: -0.01em; flex: 1; }+.hdr h1 .sub { display: block; font-size: 0.72rem; font-weight: 400; color: var(--dim); }++.back {+ appearance: none;+ border: 0;+ background: none;+ color: var(--accent);+ font: inherit;+ font-size: 1.35rem;+ line-height: 1;+ padding: 0.2rem 0.5rem 0.2rem 0;+ cursor: pointer;+}++/* ββ the "nothing is draining the queue" banner βββββββββββββββββββββββ */++.banner {+ margin: 0.55rem 0.9rem 0;+ padding: 0.55rem 0.7rem;+ border: 1px solid color-mix(in srgb, var(--selected) 45%, var(--border));+ background: color-mix(in srgb, var(--selected) 12%, transparent);+ border-radius: var(--radius);+ font-size: 0.8rem;+ color: var(--text);+}+.banner b { color: var(--selected); }++/* ββ segmented status switcher ββββββββββββββββββββββββββββββββββββββββ */++.segs {+ display: flex;+ gap: 0.3rem;+ overflow-x: auto;+ scrollbar-width: none;+ padding: 0.55rem 0 0.1rem;+ margin: 0 -0.2rem;+}+.segs::-webkit-scrollbar { display: none; }+.seg {+ appearance: none;+ flex: 0 0 auto;+ border: 1px solid var(--border);+ background: var(--surface);+ color: var(--dim);+ font: inherit;+ font-size: 0.78rem;+ padding: 0.34rem 0.7rem;+ border-radius: 999px;+ cursor: pointer;+ white-space: nowrap;+}+.seg[aria-selected="true"] {+ border-color: var(--accent);+ color: var(--bg);+ background: var(--accent);+ font-weight: 600;+}+.seg .n { opacity: 0.75; margin-left: 0.3rem; font-variant-numeric: tabular-nums; }++/* ββ lists and cards ββββββββββββββββββββββββββββββββββββββββββββββββββ */++main { flex: 1; padding: 0.7rem 0.9rem calc(var(--safe-bottom) + 2rem); }++.card {+ display: block;+ width: 100%;+ text-align: left;+ appearance: none;+ font: inherit;+ color: inherit;+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 0.7rem 0.8rem;+ margin-bottom: 0.55rem;+ cursor: pointer;+}+.card:active { background: var(--surface-2); }+.card-top { display: flex; align-items: flex-start; gap: 0.5rem; }+.card-title { flex: 1; font-weight: 550; line-height: 1.3; overflow-wrap: anywhere; }+.card-meta { display: flex; flex-wrap: wrap; gap: 0.35rem; margin-top: 0.5rem; }++.chip {+ font-size: 0.68rem;+ padding: 0.13rem 0.45rem;+ border-radius: 999px;+ border: 1px solid var(--border);+ color: var(--dim);+ background: var(--surface-2);+ white-space: nowrap;+}+.chip.agent { color: var(--column); border-color: color-mix(in srgb, var(--column) 40%, var(--border)); }+.chip.blocked { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 45%, var(--border)); }+.chip.deps { color: var(--selected); border-color: color-mix(in srgb, var(--selected) 45%, var(--border)); }++/* Phase glyph β same vocabulary as the TUI's cards. */+.phase { font-size: 0.95rem; line-height: 1.3; width: 1.1em; text-align: center; flex: 0 0 auto; }+.phase.working { color: var(--accent); }+.phase.ready { color: var(--ok); }+.phase.blocked { color: var(--danger); font-weight: 700; }+.phase.idle { color: var(--dim); }+.phase.exited { color: var(--dim); }+/* Nothing has refreshed this row recently, so it is a snapshot rather than a+ reading. Dimming it is the whole reason `phase_age_secs` is on the wire. */+.phase.stale { opacity: 0.35; }++.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--selected); flex: 0 0 auto; margin-top: 0.45rem; }++.empty { color: var(--dim); text-align: center; padding: 2.5rem 1rem; font-size: 0.9rem; }+.err {+ margin: 0.6rem 0;+ padding: 0.6rem 0.7rem;+ border: 1px solid color-mix(in srgb, var(--danger) 50%, var(--border));+ border-radius: var(--radius);+ color: var(--danger);+ font-size: 0.82rem;+}++/* ββ task detail ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */++.tabs { display: flex; gap: 0.3rem; padding-top: 0.5rem; }+.tab {+ appearance: none; flex: 1; border: 0; border-bottom: 2px solid transparent;+ background: none; color: var(--dim); font: inherit; font-size: 0.85rem;+ padding: 0.4rem 0.2rem; cursor: pointer;+}+.tab[aria-selected="true"] { color: var(--text); border-bottom-color: var(--accent); font-weight: 600; }++.kv { display: grid; grid-template-columns: minmax(6.5rem, auto) 1fr; gap: 0.3rem 0.8rem; font-size: 0.85rem; }+.kv dt { color: var(--dim); }+.kv dd { margin: 0; overflow-wrap: anywhere; }++.note {+ border: 1px solid color-mix(in srgb, var(--selected) 45%, var(--border));+ background: color-mix(in srgb, var(--selected) 10%, transparent);+ border-radius: var(--radius);+ padding: 0.6rem 0.7rem;+ margin-bottom: 0.7rem;+ font-size: 0.85rem;+}+.note h3 { margin: 0 0 0.25rem; font-size: 0.75rem; color: var(--selected); text-transform: uppercase; letter-spacing: 0.05em; }++.desc { white-space: pre-wrap; font-size: 0.88rem; color: var(--desc); overflow-wrap: anywhere; }++/* Monospace panes β diff and terminal. Both scroll inside themselves; the+ page never scrolls sideways. */+.mono {+ background: var(--surface);+ border: 1px solid var(--border);+ border-radius: var(--radius);+ padding: 0.6rem;+ overflow-x: auto;+ -webkit-overflow-scrolling: touch;+ font: 11px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: pre;+ tab-size: 4;+}+.diff-add { color: var(--ok); }+.diff-del { color: var(--danger); }+.diff-hunk { color: var(--column); }+.diff-file { color: var(--selected); font-weight: 600; }++.files { list-style: none; margin: 0 0 0.7rem; padding: 0; }+.files li {+ display: flex; gap: 0.5rem; align-items: baseline;+ padding: 0.35rem 0.1rem; border-bottom: 1px solid var(--border);+ font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+}+.files .path { flex: 1; overflow-wrap: anywhere; }+.files .n { color: var(--dim); font-variant-numeric: tabular-nums; }++.foot { color: var(--dim); font-size: 0.72rem; text-align: center; padding-top: 0.8rem; }+.spin { color: var(--dim); font-size: 0.8rem; padding: 0.4rem 0; }++/* ββ action sheet, toasts, forms βββββββββββββββββββββββββββββββββββββββ */++.scrim {+ position: fixed; inset: 0; z-index: 40;+ background: rgba(0, 0, 0, 0.55);+ display: flex; align-items: flex-end;+}+.sheet {+ width: 100%;+ background: var(--surface);+ border-top: 1px solid var(--border);+ border-radius: 16px 16px 0 0;+ padding: 0.7rem 0.9rem calc(var(--safe-bottom) + 0.9rem);+ max-height: 80dvh;+ overflow-y: auto;+}+.sheet h2 { margin: 0.2rem 0 0.7rem; font-size: 0.95rem; font-weight: 600; overflow-wrap: anywhere; }+.sheet-grip {+ width: 36px; height: 4px; border-radius: 2px;+ background: var(--border); margin: 0 auto 0.6rem;+}++/* Touch targets are 44px minimum β a mis-tap here queues real work. */+.act {+ display: block; width: 100%; min-height: 44px;+ appearance: none; font: inherit; text-align: left;+ border: 1px solid var(--border); border-radius: var(--radius);+ background: var(--surface-2); color: var(--text);+ padding: 0.6rem 0.8rem; margin-bottom: 0.4rem; cursor: pointer;+}+.act:active { background: var(--border); }+.act.primary { border-color: var(--accent); color: var(--accent); font-weight: 600; }+.act.danger { border-color: color-mix(in srgb, var(--danger) 50%, var(--border)); color: var(--danger); }+.act.cancel { background: none; text-align: center; color: var(--dim); }++.toast {+ position: fixed; left: 0.9rem; right: 0.9rem;+ bottom: calc(var(--safe-bottom) + 0.9rem);+ z-index: 50;+ display: flex; align-items: center; gap: 0.7rem;+ padding: 0.7rem 0.85rem;+ border-radius: var(--radius);+ border: 1px solid var(--border);+ background: var(--surface-2);+ font-size: 0.85rem;+ box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35);+}+.toast.bad { border-color: color-mix(in srgb, var(--danger) 55%, var(--border)); color: var(--danger); }+.toast .msg { flex: 1; overflow-wrap: anywhere; }+.toast button {+ appearance: none; border: 0; background: none; font: inherit; font-weight: 600;+ color: var(--accent); cursor: pointer; padding: 0.2rem 0.1rem; white-space: nowrap;+}++/* Swipe: the card slides over a fixed action label underneath. */+.swipe { position: relative; overflow: hidden; border-radius: var(--radius); margin-bottom: 0.55rem; }+.swipe-bg {+ position: absolute; inset: 0;+ display: flex; align-items: center; padding-left: 1rem;+ background: color-mix(in srgb, var(--accent) 20%, var(--surface));+ color: var(--accent); font-size: 0.82rem; font-weight: 600;+}+.swipe .card { margin-bottom: 0; position: relative; touch-action: pan-y; }+.swipe .card.sliding { transition: none; }+.swipe .card.settling { transition: transform 0.18s ease-out; }+/* Queued but not yet executed β the row is waiting on a TUI to drain it. */+.card.pending { opacity: 0.55; }++.field { margin-bottom: 0.7rem; }+.field label { display: block; font-size: 0.75rem; color: var(--dim); margin-bottom: 0.25rem; }+.field input, .field textarea {+ width: 100%; font: inherit; color: var(--text);+ background: var(--bg); border: 1px solid var(--border);+ border-radius: var(--radius); padding: 0.55rem 0.65rem;+}+.field textarea { min-height: 6rem; resize: vertical; }+.field input:focus, .field textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; }++.fab {+ position: fixed; right: 1rem; bottom: calc(var(--safe-bottom) + 1rem);+ z-index: 20; width: 52px; height: 52px; border-radius: 50%;+ appearance: none; border: 0; cursor: pointer;+ background: var(--accent); color: var(--bg);+ font-size: 1.6rem; line-height: 1;+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.35);+}++/* ββ live terminal βββββββββββββββββββββββββββββββββββββββββββββββββββββ */++.term {+ background: #11141a; /* the pane's own ground, in both themes: */+ color: #f2ece6; /* an agent's colours were chosen against */+ border: 1px solid var(--border); /* a dark terminal and invert badly */+ border-radius: var(--radius);+ padding: 0.6rem;+ overflow: auto;+ -webkit-overflow-scrolling: touch;+ font: 11px/1.35 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+ white-space: pre;+ tab-size: 8;+ max-height: 62dvh;+}+.term.narrow { font-size: 13px; }++.term-bar { display: flex; align-items: center; gap: 0.4rem; margin-bottom: 0.5rem; flex-wrap: wrap; }+.term-bar .live { color: var(--ok); }+.term-bar .live.off { color: var(--dim); }+.term-bar button {+ appearance: none; font: inherit; font-size: 0.72rem; cursor: pointer;+ border: 1px solid var(--border); background: var(--surface-2); color: var(--dim);+ border-radius: 999px; padding: 0.2rem 0.6rem;+}+.term-bar button[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }++.keys { display: flex; gap: 0.3rem; overflow-x: auto; scrollbar-width: none; padding: 0.5rem 0 0.3rem; }+.keys::-webkit-scrollbar { display: none; }+.keys button {+ appearance: none; flex: 0 0 auto; cursor: pointer;+ min-width: 44px; min-height: 40px;+ border: 1px solid var(--border); border-radius: 10px;+ background: var(--surface-2); color: var(--text);+ font: 13px/1 ui-monospace, SFMono-Regular, Menlo, monospace;+}+.keys button:active { background: var(--accent); color: var(--bg); }+.keys button.warn { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 45%, var(--border)); }++.compose { display: flex; gap: 0.4rem; padding-top: 0.4rem; }+.compose input {+ flex: 1; font: inherit; color: var(--text);+ background: var(--bg); border: 1px solid var(--border);+ border-radius: var(--radius); padding: 0.55rem 0.65rem;+}+.compose button {+ appearance: none; cursor: pointer; font: inherit; font-weight: 600;+ border: 1px solid var(--accent); border-radius: var(--radius);+ background: none; color: var(--accent); padding: 0 0.9rem;+}++/* ββ diff triage βββββββββββββββββββββββββββββββββββββββββββββββββββββββ */++.chip.conflict {+ color: var(--danger);+ border-color: color-mix(in srgb, var(--danger) 55%, var(--border));+ background: color-mix(in srgb, var(--danger) 12%, var(--surface-2));+}+.chip.ok { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 45%, var(--border)); }++.file { border: 1px solid var(--border); border-radius: var(--radius); margin-bottom: 0.45rem; overflow: hidden; }+.file-row {+ display: flex; align-items: baseline; gap: 0.5rem; width: 100%;+ appearance: none; border: 0; cursor: pointer; text-align: left;+ background: var(--surface); color: var(--text);+ padding: 0.6rem 0.7rem; min-height: 44px;+ font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;+}+.file-row:active { background: var(--surface-2); }+.file-row .caret { color: var(--dim); width: 1em; flex: 0 0 auto; }+.file-row .path { flex: 1; overflow-wrap: anywhere; }+.file-row .n { color: var(--dim); font-variant-numeric: tabular-nums; white-space: nowrap; }+/* The hunks sit inside the file's own box, so the border reads as one unit. */+.file .mono { border: 0; border-top: 1px solid var(--border); border-radius: 0; max-height: 60dvh; }++/* ββ refresh βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */++.refresh {+ appearance: none; border: 0; background: none; cursor: pointer;+ color: var(--dim); font: inherit; font-size: 1.1rem; line-height: 1;+ /* 44px of touch target, without 44px of visible chrome. */+ padding: 0.6rem; margin: -0.6rem -0.4rem -0.6rem 0;+}+.refresh:active { color: var(--accent); }+.refresh.spinning { animation: spin 0.7s linear infinite; color: var(--accent); }+@keyframes spin { to { transform: rotate(360deg); } }+/* A reduced-motion preference means the spin is a colour change instead. */+@media (prefers-reduced-motion: reduce) { .refresh.spinning { animation: none; } }++.pull {+ height: 0; overflow: hidden;+ display: flex; align-items: center; justify-content: center;+ color: var(--dim); font-size: 0.75rem;+ transition: height 0.15s ease-out;+}diff --git a/web/app.js b/web/app.jsnew file mode 100644index 0000000..61512bb--- /dev/null+++ b/web/app.js@@ -0,0 +1,1200 @@+// agtx mobile β read-only board.+//+// No framework and no build step: plain ES modules, served straight out of the+// binary. Routing is hash-based, which means the server needs no SPA fallback+// and a reload of any screen lands where it was.+//+// Rendering is a full re-render of one screen into `#app`. At the size of a+// kanban board that is cheaper than the machinery to avoid it, and it removes+// the whole class of bugs where the DOM and the data disagree.++import {+ api,+ captureCredential,+ wsProtocols,+ ACTION_LABELS,+ COLUMNS,+ INPUTTABLE,+ KEY_CHIPS,+ PHASE,+ PRIMARY_ACTION,+ isStale,+ needsAttention,+} from "./api.js";+import { paintPane } from "./ansi.js";++const app = document.getElementById("app");++/// The board does not poll.+///+/// A timer refetching every couple of seconds spends battery and cellular data+/// to answer a question nobody asked β a kanban board changes on the scale of+/// minutes, and the person holding the phone knows when they care. So the board+/// is fetched when something *happened*: opened, pulled down, returned to, or+/// changed by an action taken here.+///+/// The live pane is the exception and stays on its socket: that is push, not+/// polling, and watching an agent work is exactly the case where waiting for a+/// human to ask would be wrong.++/// The current screen's fetch, re-run on refresh.+let currentRender = null;+/// When it last completed, so staleness is legible rather than implied.+let lastLoaded = null;++// ββ tiny DOM helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ++function el(tag, attrs = {}, ...children) {+ const node = document.createElement(tag);+ for (const [k, v] of Object.entries(attrs)) {+ if (v === null || v === undefined || v === false) continue;+ if (k === "class") node.className = v;+ else if (k === "onclick") node.addEventListener("click", v);+ else if (k === "text") node.textContent = v;+ else node.setAttribute(k, v === true ? "" : String(v));+ }+ for (const c of children.flat()) {+ if (c === null || c === undefined || c === false) continue;+ node.append(c instanceof Node ? c : document.createTextNode(String(c)));+ }+ return node;+}++function mount(...nodes) {+ app.replaceChildren(...nodes.filter(Boolean));+ lastLoaded = Date.now();+ const main = app.querySelector("main");+ if (main) attachPullToRefresh(main);+}++function header(title, sub, onBack) {+ // A visible control as well as the pull gesture. A gesture is the fast path+ // for a thumb, but it is invisible on a desktop browser and undiscoverable+ // on a phone until someone happens to try it.+ const button = el(+ "button",+ {+ class: "refresh",+ "aria-label": "Refresh",+ onclick: async () => {+ button.classList.add("spinning");+ await refresh();+ button.classList.remove("spinning");+ },+ },+ "β»",+ );++ return el(+ "header",+ { class: "hdr" },+ el(+ "div",+ { class: "hdr-row" },+ onBack && el("button", { class: "back", "aria-label": "Back", onclick: onBack }, "βΉ"),+ el("h1", {}, title, sub ? el("span", { class: "sub", text: sub }) : null),+ button,+ ),+ );+}++function errorBox(e) {+ return el("div", { class: "err" }, e.message || String(e));+}++/// The banner that separates "queued" from "done".+///+/// Nothing drains `transition_requests` without a running TUI, so actions taken+/// here pile up and the board does not move. Saying so is the whole reason the+/// heartbeat exists β a phone that accepts taps and silently does nothing is+/// worse than one that refuses them.+function disconnectedBanner() {+ return el(+ "div",+ { class: "banner" },+ el("b", {}, "No agtx running. "),+ "Actions will queue until a board is open, and phase status is a snapshot.",+ );+}++// ββ overlays ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+//+// Toasts and sheets live outside `#app` so a re-render β which happens every+// two seconds β cannot tear one down while it is being read or tapped.++const overlay = document.createElement("div");+document.body.append(overlay);++let toastTimer = null;++/// `undo` gets a button; without one the toast just reports.+function toast(message, { bad = false, undo = null, ms = 5000 } = {}) {+ clearTimeout(toastTimer);+ const node = el(+ "div",+ { class: `toast${bad ? " bad" : ""}`, role: "status" },+ el("span", { class: "msg", text: message }),+ undo ? el("button", { onclick: () => { dismissToast(); undo(); } }, "Undo") : null,+ );+ overlay.replaceChildren(node);+ toastTimer = setTimeout(dismissToast, ms);+}++function dismissToast() {+ clearTimeout(toastTimer);+ if (overlay.firstChild?.classList.contains("toast")) overlay.replaceChildren();+}++function closeOverlay() {+ overlay.replaceChildren();+}++/// A bottom sheet. Tapping the scrim closes it, which is what every native+/// sheet does and what a thumb reaches for first.+function sheet(title, ...rows) {+ const scrim = el("div", {+ class: "scrim",+ onclick: (e) => {+ if (e.target === scrim) closeOverlay();+ },+ });+ scrim.append(+ el(+ "div",+ { class: "sheet", role: "dialog", "aria-modal": "true" },+ el("div", { class: "sheet-grip" }),+ el("h2", { text: title }),+ ...rows.flat().filter(Boolean),+ el("button", { class: "act cancel", onclick: closeOverlay }, "Cancel"),+ ),+ );+ overlay.replaceChildren(scrim);+}++/// Queue an action, optimistically.+///+/// The row lands in `transition_requests` and a TUI executes it later, so there+/// is nothing to await: the card is marked pending immediately and the next+/// refresh shows the real state. Failed transitions report their error when+/// the board reconciles the queued request.+async function runAction(pid, task, action) {+ closeOverlay();+ const label = ACTION_LABELS[action] || action;+ // Mark it before the request so the card dims on the tap rather than on the+ // response β the whole point of doing this optimistically.+ pending.set(task.id, { pid, status: task.status, label, rid: null });+ currentRender && currentRender();++ try {+ const res = await api.action(pid, task.id, action);+ pending.set(task.id, { pid, status: task.status, label, rid: res.request_id });+ toast(+ res.tui_connected ? `${label}: queued` : `${label}: queued β no agtx running`,+ );+ } catch (e) {+ // Roll back: the server refused, so nothing is queued and the card must+ // stop claiming otherwise.+ pending.delete(task.id);+ currentRender && currentRender();+ toast(e.message, { bad: true, ms: 7000 });+ }+}++/// Tasks with a queued action, keyed by task id.+///+/// A `Set` would not be enough: clearing needs to know what the task's status+/// *was* when the action was queued, since "it moved" is the only signal that+/// the TUI executed it.+const pending = new Map();++/// Reconcile optimistic state against a freshly fetched board.+///+/// Two ways a queued action stops being pending, and both need handling. It+/// lands β the task's status changed, so the card should stop being dimmed. Or+/// the TUI tried and failed, which is reported on the request rather than the+/// task: without checking, a transition that errored would leave the card+/// greyed out forever with no explanation anywhere.+async function reconcilePending(pid, tasks) {+ for (const [tid, entry] of [...pending]) {+ if (entry.pid !== pid) continue;+ const task = tasks.find((t) => t.id === tid);+ if (!task) {+ pending.delete(tid);+ continue;+ }+ if (task.status !== entry.status) {+ pending.delete(tid);+ continue;+ }+ try {+ const status = await api.requestStatus(pid, entry.rid);+ if (status.status === "error") {+ pending.delete(tid);+ toast(`${entry.label} failed: ${status.error || "unknown error"}`, {+ bad: true,+ ms: 9000,+ });+ } else if (status.status === "completed") {+ // Executed without moving the task β a no-op transition, or one whose+ // effect is not a status change. Either way it is no longer pending.+ pending.delete(tid);+ }+ } catch {+ // The request was reaped, so it finished over an hour ago.+ pending.delete(tid);+ }+ }+}++function actionSheet(pid, task) {+ const actions = task.allowed_actions || [];+ const primary = PRIMARY_ACTION[task.status];+ const rows = actions.map((a) =>+ el(+ "button",+ {+ class: `act${a === primary ? " primary" : ""}`,+ onclick: () => runAction(pid, task, a),+ },+ ACTION_LABELS[a] || a,+ ),+ );++ if (task.status === "backlog") {+ rows.push(+ el("button", { class: "act", onclick: () => taskForm(pid, task) }, "Edit"),+ el(+ "button",+ { class: "act danger", onclick: () => confirmDelete(pid, task) },+ "Delete",+ ),+ );+ }++ sheet(+ task.title,+ rows.length ? rows : el("div", { class: "empty" }, "Nothing to do from here."),+ );+}++function confirmDelete(pid, task) {+ sheet(+ `Delete β${task.title}β?`,+ el(+ "button",+ {+ class: "act danger",+ onclick: async () => {+ closeOverlay();+ try {+ await api.deleteTask(pid, task.id);+ toast("Task deleted.");+ currentRender && currentRender();+ } catch (e) {+ toast(e.message, { bad: true, ms: 7000 });+ }+ },+ },+ "Delete",+ ),+ );+}++/// Create when `task` is null, edit otherwise. Both are Backlog-only, which the+/// server enforces regardless of what this offers.+function taskForm(pid, task) {+ const title = el("input", { type: "text", value: task?.title || "", maxlength: 120 });+ const description = el("textarea", {}, task?.description || "");++ const save = el(+ "button",+ {+ class: "act primary",+ onclick: async () => {+ const fields = { title: title.value, description: description.value };+ try {+ if (task) await api.updateTask(pid, task.id, fields);+ else await api.createTask(pid, fields);+ closeOverlay();+ toast(task ? "Saved." : "Task created.");+ currentRender && currentRender();+ } catch (e) {+ toast(e.message, { bad: true, ms: 7000 });+ }+ },+ },+ task ? "Save" : "Create",+ );++ sheet(+ task ? "Edit task" : "New task",+ el("div", { class: "field" }, el("label", { text: "Title" }), title),+ el("div", { class: "field" }, el("label", { text: "Description" }), description),+ save,+ );+ // Focus after the sheet is in the DOM, or iOS ignores it and the keyboard+ // never opens.+ requestAnimationFrame(() => title.focus());+}++// ββ routing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++function route() {+ const raw = location.hash.replace(/^#\/?/, "");+ const parts = raw.split("/").filter(Boolean).map(decodeURIComponent);+ if (parts[0] === "p" && parts[1] && parts[2] === "t" && parts[3]) {+ return { screen: "task", pid: parts[1], tid: parts[3] };+ }+ if (parts[0] === "p" && parts[1]) {+ return { screen: "board", pid: parts[1], column: parts[2] || null };+ }+ return { screen: "projects" };+}++function go(hash) {+ location.hash = hash;+}++/// Show `fn`'s screen, and remember it as what a refresh re-runs.+function show(fn) {+ currentRender = fn;+ return fn();+}++/// Re-run the current screen's fetch.+async function refresh() {+ if (!currentRender) return;+ await currentRender();+ lastLoaded = Date.now();+}++/// Coming back to the app refreshes it.+///+/// Not polling β it fires once, on a deliberate act. Returning to a board that+/// is quietly minutes old is the one case where "the user will pull down" is+/// the wrong answer, because they have no way to know they need to.+document.addEventListener("visibilitychange", () => {+ if (document.visibilityState === "visible") refresh();+});++/// How stale the screen is, in words.+function staleness() {+ if (!lastLoaded) return null;+ const secs = Math.round((Date.now() - lastLoaded) / 1000);+ if (secs < 45) return "just now";+ if (secs < 90) return "a minute ago";+ if (secs < 3600) return `${Math.round(secs / 60)} minutes ago`;+ return "over an hour ago";+}++/// Pull down at the top of the page to refresh.+///+/// Two things it must not do, both found by asking what else is scrolling:+///+/// - **Arm mid-scroll.** `main` is a flex child that does not scroll β the+/// *document* does β so checking `node.scrollTop` would read 0 everywhere and+/// turn any downward drag on a long board into a refresh. The check is+/// against the scrolling element.+/// - **Steal the terminal's own scrolling.** A `.term` or `.mono` pane scrolls+/// inside itself, and a drag there is someone reading output, not asking for+/// fresh data. Those are excluded outright rather than by position, because+/// being at the top of a pane is not a request to leave it.+function attachPullToRefresh(node) {+ const THRESHOLD = 64;+ let startY = null;+ let pulled = 0;++ const indicator = el("div", { class: "pull" }, "β pull to refresh");+ node.prepend(indicator);++ const atTop = () => (document.scrollingElement?.scrollTop ?? 0) <= 0;++ node.addEventListener(+ "touchstart",+ (e) => {+ const inPane = e.target instanceof Element && e.target.closest(".term, .mono");+ startY = !inPane && atTop() ? e.touches[0].clientY : null;+ pulled = 0;+ },+ { passive: true },+ );++ node.addEventListener(+ "touchmove",+ (e) => {+ if (startY === null) return;+ pulled = Math.max(0, e.touches[0].clientY - startY);+ // Damped, so the indicator trails the finger rather than tracking it β+ // the standard feel, and it makes the threshold reachable without a+ // gesture that runs off the screen.+ indicator.style.height = `${Math.min(pulled / 2, 48)}px`;+ indicator.textContent = pulled >= THRESHOLD ? "β» release to refresh" : "β pull to refresh";+ },+ { passive: true },+ );++ const release = async () => {+ const fired = startY !== null && pulled >= THRESHOLD;+ startY = null;+ pulled = 0;+ indicator.style.height = "";+ if (fired) {+ indicator.textContent = "β» refreshingβ¦";+ indicator.style.height = "24px";+ await refresh();+ }+ };+ node.addEventListener("touchend", release);+ node.addEventListener("touchcancel", release);+}++// ββ screens βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++async function screenProjects() {+ let projects;+ let health;+ try {+ [projects, health] = await Promise.all([api.projects(), api.health()]);+ } catch (e) {+ mount(header("Projects"), el("main", {}, errorBox(e)));+ return;+ }++ // One board fetch per project, so a card can show counts and whether+ // anything wants a human. Fine at the size of a project index; if that stops+ // being true the answer is a summary field on /api/projects, not fewer cards.+ const boards = await Promise.all(+ projects.map((p) =>+ api.tasks(p.id).catch(() => null),+ ),+ );++ const cards = projects.map((p, i) => {+ const tasks = boards[i];+ const active = tasks+ ? tasks.filter((t) => t.status !== "done" && t.status !== "backlog").length+ : null;+ const attention = tasks ? tasks.filter(needsAttention).length : 0;++ return el(+ "button",+ { class: "card", onclick: () => go(`#/p/${encodeURIComponent(p.id)}`) },+ el(+ "div",+ { class: "card-top" },+ el("span", { class: "card-title", text: p.name }),+ attention > 0 ? el("span", { class: "dot", title: "needs attention" }) : null,+ ),+ el(+ "div",+ { class: "card-meta" },+ tasks === null+ ? el("span", { class: "chip", text: "unreachable" })+ : el("span", { class: "chip", text: `${tasks.length} tasks` }),+ active ? el("span", { class: "chip", text: `${active} active` }) : null,+ attention ? el("span", { class: "chip deps", text: `${attention} need you` }) : null,+ p.tui_connected+ ? null+ : el("span", { class: "chip", text: "no agtx running" }),+ ),+ );+ });++ mount(+ header("agtx", `${projects.length} project${projects.length === 1 ? "" : "s"}`),+ el(+ "main",+ {},+ cards.length ? cards : el("div", { class: "empty" }, "No projects indexed yet."),+ el("div", { class: "foot", text: `agtx ${health.version}` }),+ ),+ );+}++async function screenBoard(pid, column) {+ let tasks;+ let projects;+ try {+ [tasks, projects] = await Promise.all([api.tasks(pid), api.projects()]);+ } catch (e) {+ mount(header("Board", null, () => go("#/")), el("main", {}, errorBox(e)));+ return;+ }++ const project = projects.find((p) => p.id === pid);+ await reconcilePending(pid, tasks);+ const counts = Object.fromEntries(+ COLUMNS.map((c) => [c.id, tasks.filter((t) => t.status === c.id).length]),+ );+ // Open on the first column with anything in it, so a board whose work is all+ // in Running does not greet the user with an empty Backlog.+ const active = column || COLUMNS.find((c) => counts[c.id] > 0)?.id || "backlog";+ const shown = tasks.filter((t) => t.status === active);++ const segs = el(+ "div",+ { class: "segs", role: "tablist" },+ COLUMNS.map((c) =>+ el(+ "button",+ {+ class: "seg",+ role: "tab",+ "aria-selected": String(c.id === active),+ onclick: () => go(`#/p/${encodeURIComponent(pid)}/${c.id}`),+ },+ c.label,+ el("span", { class: "n", text: counts[c.id] }),+ ),+ ),+ );++ const head = header(project?.name || "Board", null, () => go("#/"));+ head.append(segs);++ mount(+ head,+ project && !project.tui_connected ? disconnectedBanner() : null,+ el(+ "main",+ {},+ shown.length+ ? shown.map((t) => swipeable(pid, t))+ : el("div", { class: "empty" }, `Nothing in ${active}.`),+ // Said plainly, because nothing refreshes on its own: a board with no+ // clock on it invites being read as live when it is an hour old.+ el("div", { class: "foot", text: `Updated ${staleness() ?? "just now"} Β· pull to refresh` }),+ ),+ el(+ "button",+ { class: "fab", "aria-label": "New task", onclick: () => taskForm(pid, null) },+ "+",+ ),+ );+}++/// Wrap a card so a rightward drag performs its primary action.+///+/// Two things make this safe to have at all. `touch-action: pan-y` on the card+/// lets the browser own vertical scrolling, so a swipe can never fight the+/// list; and the direction is locked on the first few pixels of movement, so a+/// slightly diagonal scroll does not queue work by accident.+///+/// The gesture is a shortcut, never the only route: everything it does is also+/// on the action sheet, which is reachable by long-press here and by a button+/// on the task screen. A hidden gesture as the sole path to an action is how a+/// feature becomes undiscoverable.+function swipeable(pid, task) {+ const card = taskCard(pid, task);++ // Long-press opens the full sheet. Attached to *every* card, before the+ // swipe wrapper is even considered: a task with no primary action β one+ // whose dependencies have not cleared, say β is exactly the one whose+ // remaining actions are hardest to find, and gating the sheet on having a+ // swipe left those cards with no way to act on them at all.+ //+ // `contextmenu` is what a held touch fires on both iOS and Android, and+ // preventing it also suppresses the text-selection callout over the card.+ card.addEventListener("contextmenu", (e) => {+ e.preventDefault();+ actionSheet(pid, task);+ });++ const action = PRIMARY_ACTION[task.status];+ if (!action || !(task.allowed_actions || []).includes(action)) return card;++ const wrap = el(+ "div",+ { class: "swipe" },+ el("div", { class: "swipe-bg" }, ACTION_LABELS[action] || action),+ card,+ );++ const THRESHOLD = 96;+ let x0 = 0;+ let y0 = 0;+ let dx = 0;+ let axis = null;++ card.addEventListener(+ "touchstart",+ (e) => {+ x0 = e.touches[0].clientX;+ y0 = e.touches[0].clientY;+ dx = 0;+ axis = null;+ card.classList.add("sliding");+ card.classList.remove("settling");+ },+ { passive: true },+ );++ card.addEventListener(+ "touchmove",+ (e) => {+ const mx = e.touches[0].clientX - x0;+ const my = e.touches[0].clientY - y0;+ if (axis === null) {+ if (Math.abs(mx) < 8 && Math.abs(my) < 8) return;+ axis = Math.abs(mx) > Math.abs(my) ? "x" : "y";+ }+ if (axis !== "x") return;+ // Rightward only: a leftward drag is where a delete gesture would live,+ // and half-implementing it invites a mis-swipe into a destructive action.+ dx = Math.max(0, mx);+ card.style.transform = `translateX(${dx}px)`;+ },+ { passive: true },+ );++ const settle = () => {+ card.classList.remove("sliding");+ card.classList.add("settling");+ card.style.transform = "";+ const fired = axis === "x" && dx >= THRESHOLD;+ axis = null;+ dx = 0;+ if (fired) runAction(pid, task, action);+ };+ card.addEventListener("touchend", settle);+ card.addEventListener("touchcancel", settle);++ return wrap;+}++function phaseGlyph(task) {+ const p = PHASE[task.phase_status];+ if (!p) return null;+ const stale = isStale(task);+ return el("span", {+ class: `phase ${task.phase_status}${stale ? " stale" : ""}`,+ text: p.glyph,+ title: stale ? `${p.label} (${task.phase_age_secs}s ago)` : p.label,+ });+}++function taskCard(pid, t) {+ return el(+ "button",+ {+ class: `card${pending.has(t.id) ? " pending" : ""}`,+ onclick: () => go(`#/p/${encodeURIComponent(pid)}/t/${encodeURIComponent(t.id)}`),+ },+ el(+ "div",+ { class: "card-top" },+ phaseGlyph(t),+ el("span", { class: "card-title", text: t.title }),+ t.escalation_note ? el("span", { class: "dot", title: "escalated" }) : null,+ ),+ el(+ "div",+ { class: "card-meta" },+ el("span", { class: "chip agent", text: t.agent }),+ t.plugin ? el("span", { class: "chip", text: t.plugin }) : null,+ t.cycle > 1 ? el("span", { class: "chip", text: `cycle ${t.cycle}` }) : null,+ t.pr_number ? el("span", { class: "chip", text: `#${t.pr_number}` }) : null,+ t.deps_satisfied === false+ ? el("span", { class: "chip deps", text: "blocked on deps" })+ : null,+ // `null` is "not checked yet", which must not read as clean β that is+ // the answer someone might merge on. Only a definite `true` shows.+ t.conflicted === true+ ? el("span", { class: "chip conflict", text: "conflicts" })+ : null,+ ),+ );+}++// ββ task detail βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++/// Which tab the task screen is on. Deliberately module state rather than the+/// URL: it is a view preference within one task, and putting it in the hash+/// would make the back button walk through tabs before leaving the task.+let taskTab = "details";++/// The task screen currently mounted, so the poll can tell a refresh from a+/// first render.+let mountedTask = null;++async function screenTask(pid, tid) {+ // The terminal tab owns its own updates: frames arrive over the socket, and+ // re-rendering here would blank the pane between frames and β worse β take+ // focus out of the compose field every two seconds, mid-message.+ if (taskTab === "terminal" && mountedTask === `${pid}/${tid}/terminal`) {+ // Refresh also handles a socket that still looks OPEN after suspension.+ const { pane, live } = term;+ closeSocket();+ openSocket(pid, tid, pane, live);+ return;+ }++ let task;+ try {+ task = await api.task(pid, tid);+ } catch (e) {+ mount(+ header("Task", null, () => go(`#/p/${encodeURIComponent(pid)}`)),+ el("main", {}, errorBox(e)),+ );+ return;+ }++ const head = header(task.title, `${task.status} Β· ${task.agent}`, () =>+ go(`#/p/${encodeURIComponent(pid)}`),+ );+ const tabs = ["details", "diff", "terminal"];+ head.append(+ el(+ "div",+ { class: "tabs", role: "tablist" },+ tabs.map((name) =>+ el(+ "button",+ {+ class: "tab",+ role: "tab",+ "aria-selected": String(name === taskTab),+ onclick: () => {+ if (taskTab === "terminal" && name !== "terminal") closeSocket();+ taskTab = name;+ mountedTask = null;+ currentRender && currentRender();+ },+ },+ name[0].toUpperCase() + name.slice(1),+ ),+ ),+ ),+ );++ const body = el("main", {});+ mount(head, body);+ mountedTask = `${pid}/${tid}/${taskTab}`;++ if (taskTab === "details") body.replaceChildren(...detailsBody(pid, task));+ else if (taskTab === "diff") body.replaceChildren(await diffBody(pid, tid));+ else body.replaceChildren(terminalBody(pid, task));+}++function detailsBody(pid, task) {+ const actions = task.allowed_actions || [];+ const primary = PRIMARY_ACTION[task.status];+ const buttons = actions.map((a) =>+ el(+ "button",+ {+ class: `act${a === primary ? " primary" : ""}`,+ onclick: () => runAction(pid, task, a),+ },+ ACTION_LABELS[a] || a,+ ),+ );+ if (task.status === "backlog") {+ buttons.push(+ el("button", { class: "act", onclick: () => taskForm(pid, task) }, "Edit"),+ el(+ "button",+ { class: "act danger", onclick: () => confirmDelete(pid, task) },+ "Delete",+ ),+ );+ }++ const rows = [+ ["Status", task.status],+ ["Phase", task.phase_status ? phaseText(task) : "not observed"],+ ["Agent", task.agent],+ ["Agent state", task.blocked_reason || task.agent_state || "β"],+ ["Plugin", task.plugin || "β"],+ ["Branch", task.branch_name || "β"],+ ["Base", task.base_branch || "β"],+ ["Worktree", task.worktree_path || "β"],+ ["Session", task.session_name || "β"],+ ["Dependencies", task.deps_satisfied ? "satisfied" : "not satisfied"],+ ["Updated", new Date(task.updated_at).toLocaleString()],+ ];++ return [+ task.escalation_note+ ? el("div", { class: "note" }, el("h3", { text: "Escalation" }), task.escalation_note)+ : null,+ ...buttons,+ buttons.length+ ? el("hr", { style: "border:0;border-top:1px solid var(--border);margin:0.9rem 0" })+ : null,+ task.description+ ? el("div", { class: "desc", text: task.description })+ : el("div", { class: "empty" }, "No description."),+ el("hr", { style: "border:0;border-top:1px solid var(--border);margin:0.9rem 0" }),+ el(+ "dl",+ { class: "kv" },+ rows.flatMap(([k, v]) => [el("dt", { text: k }), el("dd", { text: v })]),+ ),+ ].filter(Boolean);+}++function phaseText(task) {+ const p = PHASE[task.phase_status];+ const age = task.phase_age_secs;+ const label = p ? p.label : task.phase_status;+ if (isStale(task)) return `${label} β stale, ${age}s ago`;+ return label;+}++async function diffBody(pid, tid) {+ let diff;+ try {+ diff = await api.diff(pid, tid);+ } catch (e) {+ return errorBox(e);+ }+ if (!diff.patch.trim()) {+ return el("div", { class: "empty" }, `No changes against ${diff.base}.`);+ }++ // One collapsible section per file, closed by default. A phone screen holds+ // maybe forty lines; a flat patch of a dozen files means scrolling past all+ // of them to find the one worth reading. Triage is picking the file, then+ // reading it β so the file list *is* the interface and the hunks are what+ // opens underneath.+ const byFile = splitPatchByFile(diff.patch);+ const stats = statLines(diff.stat);++ const sections = byFile.map(({ path, body }) => {+ const hunks = el("div", { class: "mono", hidden: true }, ...colourDiff(body));+ const stat = stats.get(path);+ const head = el(+ "button",+ {+ class: "file-row",+ "aria-expanded": "false",+ onclick: () => {+ const open = hunks.hidden;+ hunks.hidden = !open;+ head.setAttribute("aria-expanded", String(open));+ head.querySelector(".caret").textContent = open ? "βΎ" : "βΈ";+ },+ },+ el("span", { class: "caret", text: "βΈ" }),+ el("span", { class: "path", text: path }),+ stat ? el("span", { class: "n", text: stat }) : null,+ );+ return el("div", { class: "file" }, head, hunks);+ });++ return el(+ "div",+ {},+ el(+ "div",+ { class: "term-bar" },+ el("span", { class: "chip", text: `vs ${diff.base}` }),+ conflictChip(diff),+ el("span", { class: "chip", text: `${byFile.length} files` }),+ ),+ conflictDetail(diff),+ sections.length+ ? sections+ : el("div", { class: "mono" }, ...colourDiff(diff.patch)),+ );+}++function conflictChip(diff) {+ if (diff.conflicted === true) {+ return el("span", { class: "chip conflict", text: "conflicts with base" });+ }+ if (diff.conflicted === false) {+ return el("span", { class: "chip ok", text: "merges cleanly" });+ }+ return null; // not checked β say nothing rather than imply either answer+}++function conflictDetail(diff) {+ if (diff.conflicted !== true || !diff.conflicting_files?.length) return null;+ return el(+ "div",+ { class: "note" },+ el("h3", { text: "Conflicting files" }),+ el("div", { class: "desc", text: diff.conflicting_files.join("\n") }),+ );+}++/// Split a unified diff into one entry per file.+///+/// Anchored on `diff --git`, which git emits once per file regardless of+/// rename, mode change or binary content β unlike `+++ b/...`, which is absent+/// for a deleted file and misleading for a rename.+function splitPatchByFile(patch) {+ const out = [];+ let current = null;+ for (const line of patch.split("\n")) {+ if (line.startsWith("diff --git ")) {+ if (current) out.push(current);+ // `diff --git a/x b/x` β take the b-side, which is the path after any+ // rename, falling back to the whole line if it is shaped unexpectedly.+ const m = line.match(/ b\/(.*)$/);+ current = { path: m ? m[1] : line.slice("diff --git ".length), body: line + "\n" };+ } else if (current) {+ current.body += line + "\n";+ }+ }+ if (current) out.push(current);+ return out;+}++/// `path => "12 +++---"` from `git diff --stat`, for the counts beside each row.+function statLines(stat) {+ const map = new Map();+ for (const line of (stat || "").trim().split("\n")) {+ const bar = line.indexOf("|");+ if (bar === -1) continue;+ map.set(line.slice(0, bar).trim(), line.slice(bar + 1).trim());+ }+ return map;+}++/// Colour a unified diff without a syntax highlighter: +/- and hunk headers+/// carry nearly all the signal at phone width.+function colourDiff(patch) {+ return patch.split("\n").map((line) => {+ let cls = "";+ if (line.startsWith("+++") || line.startsWith("---") || line.startsWith("diff ")) {+ cls = "diff-file";+ } else if (line.startsWith("@@")) cls = "diff-hunk";+ else if (line.startsWith("+")) cls = "diff-add";+ else if (line.startsWith("-")) cls = "diff-del";+ return el("span", { class: cls, text: line + "\n" });+ });+}++/// The live pane socket, and the task it is showing.+///+/// One socket for the whole app rather than one per view: a phone shows one+/// pane at a time, and reconnecting on every tab switch would cost a handshake+/// for nothing. Closed when the terminal tab is left, so the server stops+/// capturing β nothing is captured for a task nobody is looking at.+let socket = null;+let socketTask = null;+let reconnectTimer = null;+/// Where the live socket paints, and the last frame it painted.+///+/// The frame is cached because the server only sends what *changed*: an idle+/// agent produces no frames at all, so a freshly built pane node with nothing+/// to paint would sit on "connectingβ¦" indefinitely.+const term = { pane: null, live: null, frame: null };++function closeSocket() {+ clearTimeout(reconnectTimer);+ reconnectTimer = null;+ if (socket) {+ try {+ socket.send(JSON.stringify({ type: "unsubscribe" }));+ } catch {+ /* already closing */+ }+ socket.close();+ }+ socket = null;+ socketTask = null;+ term.pane = null;+ term.live = null;+ term.frame = null;+}++/// A live terminal. Returns immediately with the shell; frames arrive over the+/// socket and repaint in place, so this is not re-rendered by the poll.+function terminalBody(pid, task) {+ const tid = task.id;+ const pane = el("div", { class: "term" });+ const live = el("span", { class: "live off", text: "β offline" });+ if (term.frame && socketTask === tid) paintPane(pane, term.frame);+ else pane.textContent = "connectingβ¦";++ let narrow = false;+ const narrowBtn = el(+ "button",+ {+ "aria-pressed": "false",+ onclick: () => {+ narrow = !narrow;+ narrowBtn.setAttribute("aria-pressed", String(narrow));+ pane.classList.toggle("narrow", narrow);+ },+ },+ "Bigger text",+ );++ const bar = el(+ "div",+ { class: "term-bar" },+ live,+ el("span", { class: "chip", text: task.session_name || "no session" }),+ narrowBtn,+ );++ const wrap = el("div", {}, bar, pane);++ // Research and review have composers too, provided a session exists.+ if (INPUTTABLE.has(task.status) && task.session_name) {+ const send = async (payload, what) => {+ try {+ await api.input(pid, tid, payload);+ } catch (e) {+ toast(`${what}: ${e.message}`, { bad: true, ms: 7000 });+ }+ };++ wrap.append(+ el(+ "div",+ { class: "keys" },+ KEY_CHIPS.map((k) =>+ el(+ "button",+ {+ class: k.key === "C-c" ? "warn" : "",+ onclick: () => send({ key: k.key }, k.label),+ },+ k.label,+ ),+ ),+ ),+ );++ const field = el("input", {+ type: "text",+ placeholder: "Message the agentβ¦",+ enterkeyhint: "send",+ autocapitalize: "off",+ autocorrect: "off",+ });+ const submit = async () => {+ const text = field.value.trim();+ if (!text) return;+ // Clear first: the send takes a second or two β a paste plus the Enter+ // loop that gets past a composer's picker β and a field that stays full+ // invites a second tap that would double the message.+ field.value = "";+ await send({ text }, "message");+ };+ field.addEventListener("keydown", (e) => {+ if (e.key === "Enter") submit();+ });+ wrap.append(+ el(+ "div",+ { class: "compose" },+ field,+ el("button", { onclick: submit }, "Send"),+ ),+ );+ }++ openSocket(pid, tid, pane, live);+ return wrap;+}++function openSocket(pid, tid, pane, live) {+ term.pane = pane;+ term.live = live;+ if (+ socket && socketTask === tid &&+ (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)+ ) {+ // Already watching this pane β the new nodes were repainted from the frame+ // cache above, so there is nothing to re-request.+ if (socket.readyState === WebSocket.OPEN) {+ live.className = "live";+ live.textContent = "β live";+ }+ return;+ }+ closeSocket();+ term.pane = pane;+ term.live = live;++ const url = `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`;+ const ws = new WebSocket(url, wsProtocols());+ socket = ws;+ socketTask = tid;++ ws.addEventListener("open", () => {+ if (socket !== ws) return;+ term.live.className = "live";+ term.live.textContent = "β live";+ ws.send(JSON.stringify({ type: "subscribe", project_id: pid, task_id: tid }));+ });++ ws.addEventListener("message", (e) => {+ if (socket !== ws) return;+ let msg;+ try {+ msg = JSON.parse(e.data);+ } catch {+ return;+ }+ if (msg.type === "frame") {+ term.frame = msg.content;+ if (term.pane) paintPane(term.pane, msg.content);+ } else if (msg.type === "gone") {+ term.live.className = "live off";+ term.live.textContent = "β pane gone";+ } else if (msg.type === "error") {+ if (term.pane) term.pane.textContent = msg.message;+ term.live.className = "live off";+ term.live.textContent = "β offline";+ }+ });++ const offline = () => {+ if (socket !== ws || !term.live) return;+ term.live.className = "live off";+ term.live.textContent = "β offline";+ };+ ws.addEventListener("close", () => {+ offline();+ if (socket !== ws) return;+ clearTimeout(reconnectTimer);+ reconnectTimer = setTimeout(() => {+ if (socket === ws && term.pane && term.live) {+ openSocket(pid, tid, term.pane, term.live);+ }+ }, 1000);+ });+ ws.addEventListener("error", offline);+}++// ββ boot ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++function render() {+ const r = route();+ if (r.screen !== "task") {+ // Nothing is captured for a task nobody is looking at β the socket is what+ // makes the server's capture loop run at all.+ closeSocket();+ mountedTask = null;+ }+ if (r.screen === "projects") show(() => screenProjects());+ else if (r.screen === "board") show(() => screenBoard(r.pid, r.column));+ else show(() => screenTask(r.pid, r.tid));+}++// Before the first route is read: a `#pair=β¦` or `#token=β¦` hand-off occupies+// the same fragment the router uses, so it has to be consumed first. Pairing is+// a round trip, so the first render waits for it β otherwise the board's own+// requests race the token into storage and the screen opens on an auth error.+captureCredential().then((result) => {+ if (result?.paired) toast(`Paired as β${result.paired}β.`);+ else if (result?.error) toast(result.error, { bad: true, ms: 9000 });+ render();+});++addEventListener("hashchange", render);++if ("serviceWorker" in navigator) {+ // Failure here is not worth surfacing: it costs the offline shell and+ // nothing else, and it always fails over plain http on a non-loopback host.+ navigator.serviceWorker.register("sw.js").catch(() => {});+}diff --git a/web/icon-192.png b/web/icon-192.pngnew file mode 100644index 0000000..83945c1Binary files /dev/null and b/web/icon-192.png differdiff --git a/web/icon-512.png b/web/icon-512.pngnew file mode 100644index 0000000..fd3b093Binary files /dev/null and b/web/icon-512.png differdiff --git a/web/index.html b/web/index.htmlnew file mode 100644index 0000000..446a373--- /dev/null+++ b/web/index.html@@ -0,0 +1,29 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<!-- viewport-fit=cover plus the safe-area insets in app.css is what keeps the+ sticky header and footer clear of the notch and the home indicator. -->+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">+<meta name="theme-color" content="#11141a" media="(prefers-color-scheme: dark)">+<meta name="theme-color" content="#f7f5f2" media="(prefers-color-scheme: light)">+<meta name="color-scheme" content="dark light">+<!-- Standalone once added to the Home Screen: no address bar, own icon. On+ iOS this is also what makes Web Push possible at all β Safari delivers it+ to installed web apps and never to a tab. -->+<meta name="apple-mobile-web-app-capable" content="yes">+<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">+<meta name="apple-mobile-web-app-title" content="agtx">+<link rel="manifest" href="manifest.webmanifest">+<link rel="apple-touch-icon" href="icon-192.png">+<link rel="icon" href="icon-192.png">+<link rel="stylesheet" href="app.css">+<title>agtx</title>+</head>+<body>+<div id="app" class="app">+ <div class="boot">Loadingβ¦</div>+</div>+<script type="module" src="app.js"></script>+</body>+</html>diff --git a/web/manifest.webmanifest b/web/manifest.webmanifestnew file mode 100644index 0000000..97dfdd2--- /dev/null+++ b/web/manifest.webmanifest@@ -0,0 +1,16 @@+{+ "name": "agtx",+ "short_name": "agtx",+ "description": "Terminal-native kanban board for coding agents",+ "start_url": ".",+ "scope": ".",+ "display": "standalone",+ "orientation": "portrait",+ "background_color": "#11141a",+ "theme_color": "#11141a",+ "icons": [+ { "src": "icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },+ { "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },+ { "src": "icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }+ ]+}diff --git a/web/sw.js b/web/sw.jsnew file mode 100644index 0000000..a8c34d2--- /dev/null+++ b/web/sw.js@@ -0,0 +1,52 @@+// Offline shell for the installed PWA.+//+// Network-first for everything, cache as the fallback. The obvious alternative+// β cache-first for the shell β pins a viewer to whatever HTML they installed,+// and `agtx update` swaps the binary underneath them, so the app would keep+// serving a stale UI against a newer API with no way to notice. Paying one+// conditional request per asset is worth never being able to wedge that way.+//+// The API is deliberately not cached: a board is only useful when it is true,+// and a cached one would show yesterday's phase status with today's timestamp.++const CACHE = "agtx-shell-v1";+const SHELL = [+ "./",+ "index.html",+ "app.css",+ "app.js",+ "api.js",+ "ansi.js",+ "manifest.webmanifest",+ "icon-192.png",+ "icon-512.png",+];++self.addEventListener("install", (e) => {+ e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));+});++self.addEventListener("activate", (e) => {+ e.waitUntil(+ caches+ .keys()+ .then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))+ .then(() => self.clients.claim()),+ );+});++self.addEventListener("fetch", (e) => {+ const url = new URL(e.request.url);+ if (e.request.method !== "GET" || url.origin !== location.origin) return;+ if (url.pathname.startsWith("/api/")) return; // always live++ e.respondWith(+ fetch(e.request)+ .then((res) => {+ const copy = res.clone();+ caches.open(CACHE).then((c) => c.put(e.request, copy)).catch(() => {});+ return res;+ })+ .catch(() => caches.match(e.request).then((hit) => hit || caches.match("index.html"))),+ );+});