garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/device.rs

raw

//! Devices: an app on a person's phone, paired to the hub, whose MCP tools the
//! person's sessions call (docs/mockups/device-link/design.md).
//!
//! The phone is behind NAT, so it dials out: `GET /v1/device/link`, a WebSocket
//! through the web proxy, held open while the app's link is on. The hub relays
//! a session's `tools/call` down it and the answer back (`call`). In a session
//! a device is an MCP server of its own, `midas device mcp <id>` (the runner
//! names one per device in ACP's `mcpServers`), whose tool list is the one the
//! device announced when it last connected, kept here — so its tools are there
//! while the phone sleeps, and a call then says it is not connected.
//!
//! **Pairing** is a one-time code a person logged in to the page makes
//! (`code`, 10 minutes, single use), which the app trades for a **device
//! token** (`pair`). The token is a credential of its own (`X-Midas-Device`:
//! Caddy strips `Authorization`), accepted through the proxy but only on
//! `/v1/device/*`, where it can hold its link, answer calls and push a message
//! to a session. It is kept hashed; *Forget* on the page revokes it and drops
//! the link at once.

use std::collections::{BTreeMap, HashMap};
use std::io::{BufRead, Write};
use std::net::TcpStream;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use crate::events;
use crate::registry;
use crate::store;

/// How long a pairing code holds.
const CODE_TTL: i64 = 600;
/// The code's letters: no 0/O, 1/I/L, so it can be read off one screen and typed on another.
const ALPHABET: &[u8] = b"ABCDEFGHJKMNPQRSTUVWXYZ23456789";
const CODE_LEN: usize = 8;
/// Wrong codes the hub takes in a window before it takes none: 31^8 codes, so
/// guessing is hopeless anyway, but a loop at it should not get to try.
const WRONG_MAX: u32 = 20;
const WRONG_WINDOW: Duration = Duration::from_secs(600);
/// The largest message a device may send: a screenshot or a recording, base64.
pub const FRAME_MAX: u64 = 32 << 20;
/// Devices linked at once: each link holds two threads.
const LINKS_MAX: usize = 16;
const PING: Duration = Duration::from_secs(25);
/// A call's longest wait, whatever it asks for.
pub const CALL_MAX_S: u64 = 300;
/// How long a device that acknowledges calls (its hello says `"ack": true`)
/// has to say it got one. A phone that went to sleep or changed networks
/// leaves a socket that still writes but reaches nothing, and a call down it
/// waited its whole timeout, 60–90 s, before it said so (2026-11-04).
const ACK: Duration = Duration::from_secs(5);
/// How long a call waits for a device that is not linked to link again,
/// after telling the person their phone is wanted. It was 30 s, and a person
/// who follows the page on the same phone came back in 39 (2026-11-04): from
/// the notice to the app, and the app to its link, takes longer than that.
const RETURN_WAIT: Duration = Duration::from_secs(90);

#[derive(Serialize, Deserialize, Default)]
struct Devices {
    #[serde(default)]
    devices: BTreeMap<String, Value>,
    /// sha256(code) → {account, expires}.
    #[serde(default)]
    codes: BTreeMap<String, Value>,
}

fn path() -> PathBuf {
    registry::root().join("devices.json")
}

fn read() -> Devices {
    store::read(&path()).unwrap_or_default()
}

fn update<R>(f: impl FnOnce(&mut Devices) -> Result<R>) -> Result<R> {
    let mut s = store::Store::<Devices>::open(path())?.private();
    let r = f(&mut s.data)?;
    s.save()?;
    Ok(r)
}

/// A code as a person types it: any case, spaces and dashes left out.
fn normal(code: &str) -> String {
    code.chars().filter(|c| c.is_ascii_alphanumeric()).map(|c| c.to_ascii_uppercase()).collect()
}

/// A name as an MCP server's: `OnePlus 15` → `oneplus-15`, `Cartopolis` → `cartopolis`.
pub fn slug(name: &str) -> String {
    let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect();
    let s = s.split('-').filter(|p| !p.is_empty()).collect::<Vec<_>>().join("-");
    if s.is_empty() { "device".into() } else { s.chars().take(40).collect() }
}

/// A one-time pairing code for `account`, with the link that opens an app at it.
pub fn code(account: &str, hub: &str) -> Result<Value> {
    let bytes = crate::accounts::random(CODE_LEN)?;
    let code: String = bytes.iter().map(|b| ALPHABET[*b as usize % ALPHABET.len()] as char).collect();
    let expires = registry::now() + CODE_TTL;
    update(|d| {
        let now = registry::now();
        d.codes.retain(|_, c| c["expires"].as_i64().unwrap_or(0) > now);
        d.codes.insert(crate::accounts::sha256(&code), json!({"account": account, "expires": expires}));
        Ok(())
    })?;
    events::emit("device_code", json!({"actor": account}));
    let shown = format!("{}-{}", &code[..4], &code[4..]);
    let link = format!("cartopolis://midas-pair?hub={}&code={code}", crate::hub::pct_encode(hub));
    let qr = qrcode::QrCode::new(link.as_bytes()).map(|q| q.render::<qrcode::render::svg::Color>().min_dimensions(200, 200).build()).ok();
    Ok(json!({"code": shown, "expires": expires, "link": link, "qr": qr}))
}

static WRONG: Mutex<Option<(Instant, u32)>> = Mutex::new(None);

/// Trade a pairing code for a device token: `{id, token, name}`. The token is
/// shown this once; the hub keeps its hash.
pub fn pair(code: &str, name: &str, app: &str, version: &str) -> Result<Value> {
    {
        let mut w = WRONG.lock().unwrap_or_else(|p| p.into_inner());
        if let Some((since, n)) = *w {
            if since.elapsed() > WRONG_WINDOW {
                *w = None;
            } else if n >= WRONG_MAX {
                bail!("too many wrong codes; pairing is closed for a few minutes");
            }
        }
    }
    let name = name.trim();
    if name.is_empty() || name.len() > 60 || name.contains(['\n', '\r']) {
        bail!("a device's name is one short line, as `OnePlus 15`");
    }
    let key = crate::accounts::sha256(&normal(code));
    let token = crate::accounts::token()?;
    let id = format!("d{}", crate::mirror::random_hex(4)?);
    let paired = update(|d| {
        let now = registry::now();
        d.codes.retain(|_, c| c["expires"].as_i64().unwrap_or(0) > now);
        let Some(c) = d.codes.remove(&key) else { return Ok(None) };
        let account = c["account"].as_str().unwrap_or("").to_string();
        d.devices.insert(id.clone(), json!({
            "name": name, "app": app, "version": version, "account": account,
            "token": crate::accounts::sha256(&token), "created": now, "seen": null, "tools": [], "build": null,
        }));
        Ok(Some(account))
    })?;
    let Some(account) = paired else {
        let mut w = WRONG.lock().unwrap_or_else(|p| p.into_inner());
        let n = w.map_or(0, |(_, n)| n) + 1;
        *w = Some((w.map_or_else(Instant::now, |(s, _)| s), n));
        events::emit("refused", json!({"why": "a wrong or spent pairing code", "path": "device/pair"}));
        bail!("that code is wrong, spent or more than ten minutes old: make a new one on the page");
    };
    events::emit("device_paired", json!({"actor": account, "device": id, "name": name, "app": app}));
    Ok(json!({"id": id, "token": token, "name": name}))
}

/// The device a token is, if it is one: `(id, its record)`.
pub fn by_token(token: &str) -> Option<(String, Value)> {
    if token.len() < 32 {
        return None;
    }
    let h = crate::accounts::sha256(token);
    read().devices.into_iter().find(|(_, d)| d["token"].as_str().is_some_and(|t| {
        t.len() == h.len() && t.bytes().zip(h.bytes()).fold(0u8, |x, (a, b)| x | (a ^ b)) == 0
    }))
}

/// Every device, as the page and the sessions see them: no token.
pub fn list() -> Vec<Value> {
    let (online, away): (Vec<String>, Vec<String>) = {
        let links = LINKS.lock().unwrap_or_else(|p| p.into_inner());
        (links.keys().cloned().collect(), links.iter().filter(|(_, l)| l.away.load(Ordering::SeqCst)).map(|(k, _)| k.clone()).collect())
    };
    let devices = read().devices;
    // A session's MCP server is named for the app, as its tools are the app's
    // (`mcp__cartopolis__view`), not for the phone it runs on; only two devices
    // with one app are told apart by the device's name.
    let app_of = |d: &Value| slug(d["app"].as_str().unwrap_or(""));
    let mut per_app = HashMap::<String, usize>::new();
    for d in devices.values() {
        *per_app.entry(app_of(d)).or_default() += 1;
    }
    devices.into_iter().map(|(id, mut d)| {
        if let Some(o) = d.as_object_mut() {
            o.remove("token");
        }
        d["id"] = json!(id);
        d["online"] = json!(online.contains(&id));
        d["away"] = json!(away.contains(&id));
        let app = app_of(&d);
        d["server"] = json!(if per_app[&app] > 1 { format!("{app}-{}", slug(d["name"].as_str().unwrap_or(""))) } else { app });
        d
    }).collect()
}

pub fn get(id: &str) -> Option<Value> {
    list().into_iter().find(|d| d["id"] == id)
}

/// Forget a device: its token is void and its link dropped, now.
pub fn forget(id: &str, by: &str) -> Result<()> {
    let gone = update(|d| Ok(d.devices.remove(id).is_some()))?;
    if !gone {
        bail!("no device {id}");
    }
    if let Some(l) = LINKS.lock().unwrap_or_else(|p| p.into_inner()).remove(id) {
        let _ = l.out.send(Out::Close);
    }
    events::emit("device_forgotten", json!({"actor": by, "device": id}));
    Ok(())
}

fn set(id: &str, f: impl FnOnce(&mut Value)) -> Result<()> {
    update(|d| {
        if let Some(dev) = d.devices.get_mut(id) {
            f(dev);
        }
        Ok(())
    })
}

// ── The link ────────────────────────────────────────────────────────────────

enum Out {
    Text(String),
    Pong(Vec<u8>),
    Close,
}

/// What the device said about a call.
enum Reply {
    /// It has the call (`{"type":"ack"}`): the answer may take a while.
    Got,
    Answer(Value),
}

type Waiting = Arc<Mutex<HashMap<u64, mpsc::Sender<Reply>>>>;

struct Link {
    out: mpsc::Sender<Out>,
    /// Calls sent down it, waiting for their answer: call id → where it goes.
    waiting: Waiting,
    /// Which connection this is: a device that reconnects replaces its old link.
    n: u64,
    /// The device acknowledges each call, so one it does not is a dead link.
    acks: Arc<AtomicBool>,
    /// The app is linked but off screen (`{"type":"away","away":true}`): it
    /// holds a call until it is opened, so the person is told one waits.
    away: Arc<AtomicBool>,
}

static LINKS: Mutex<BTreeMap<String, Link>> = Mutex::new(BTreeMap::new());
static NEXT: AtomicU64 = AtomicU64::new(1);

/// Calls waiting for a device to link again: (device, session, since). The
/// person is told (`push::needs`) while one is here.
static WANTED: Mutex<Vec<(String, String, i64)>> = Mutex::new(Vec::new());

/// What waits for a device, as `push::needs` lists it: a session wants the phone.
pub fn wanted() -> Vec<Value> {
    let wanted = WANTED.lock().unwrap_or_else(|p| p.into_inner()).clone();
    let devices = read().devices;
    wanted.into_iter().map(|(dev, session, since)| {
        let name = devices.get(&dev).and_then(|d| d["name"].as_str()).unwrap_or("your phone").to_string();
        json!({"key": format!("device:{dev}:{session}:{since}"), "title": format!("{session} wants your phone"),
               "body": format!("open Cartopolis on {name}: the link comes back by itself"), "url": format!("/sessions/{session}")})
    }).collect()
}

/// Answer the upgrade and carry calls until the device goes.
///
/// The device's messages are JSON text: `{"type":"hello","tools":[…],"build":{…},
/// "ack":true}` first (and again whenever its tools change), then for each
/// call `{"type":"ack","id":n}` the moment it arrives, if the hello said
/// `ack`, and `{"type":"result","id":n,"response":{…}}` when it is answered.
/// The hub's are `{"type":"call","id":n,"session":id,"request":{jsonrpc tools/call}}`.
pub fn serve_link(mut stream: TcpStream, mut reader: impl BufRead + Send + 'static, ws_key: &str, id: &str) -> Result<()> {
    {
        let links = LINKS.lock().unwrap_or_else(|p| p.into_inner());
        if links.len() >= LINKS_MAX && !links.contains_key(id) {
            drop(links);
            write!(stream, "HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")?;
            return Ok(());
        }
    }
    write!(stream, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {}\r\n\r\n",
           crate::ws::accept(ws_key))?;
    stream.set_read_timeout(Some(PING * 2 + Duration::from_secs(10)))?;
    stream.set_write_timeout(Some(Duration::from_secs(30)))?;
    let n = NEXT.fetch_add(1, Ordering::SeqCst);
    let (tx, rx) = mpsc::channel::<Out>();
    let waiting: Waiting = Arc::default();
    let acks = Arc::new(AtomicBool::new(false));
    let away = Arc::new(AtomicBool::new(false));
    if let Some(old) = LINKS.lock().unwrap_or_else(|p| p.into_inner())
        .insert(id.to_string(), Link { out: tx.clone(), waiting: waiting.clone(), n, acks: acks.clone(), away: away.clone() }) {
        let _ = old.out.send(Out::Close);
    }
    let _ = set(id, |d| d["seen"] = json!(registry::now()));
    events::emit("device_linked", json!({"device": id}));
    crate::ws::nudge();

    struct Shut(TcpStream);
    impl Drop for Shut {
        fn drop(&mut self) {
            let _ = self.0.shutdown(std::net::Shutdown::Both);
        }
    }
    let _shut = Shut(stream.try_clone()?);
    let (dev, w, out) = (id.to_string(), waiting.clone(), tx.clone());
    std::thread::Builder::new().spawn(move || {
        loop {
            match crate::ws::read_client_frame(&mut reader, FRAME_MAX) {
                Ok((0x1, text)) => {
                    let v: Value = serde_json::from_slice(&text).unwrap_or(Value::Null);
                    match v["type"].as_str() {
                        Some("hello") => {
                            let tools = v["tools"].as_array().cloned().unwrap_or_default();
                            let build = v["build"].clone();
                            acks.store(v["ack"] == true, Ordering::SeqCst);
                            let _ = set(&dev, |d| {
                                d["tools"] = json!(tools);
                                d["build"] = build;
                                d["seen"] = json!(registry::now());
                            });
                        }
                        Some("away") => {
                            let now = v["away"] == true;
                            if away.swap(now, Ordering::SeqCst) != now {
                                events::emit(if now { "device_away" } else { "device_back" }, json!({"device": dev}));
                                crate::ws::nudge();
                            }
                        }
                        Some("ack") => {
                            let to = v["id"].as_u64().and_then(|n| w.lock().unwrap_or_else(|p| p.into_inner()).get(&n).cloned());
                            if let Some(to) = to {
                                let _ = to.send(Reply::Got);
                            }
                        }
                        Some("result") => {
                            let to = v["id"].as_u64().and_then(|n| w.lock().unwrap_or_else(|p| p.into_inner()).remove(&n));
                            if let Some(to) = to {
                                let _ = to.send(Reply::Answer(v["response"].clone()));
                            }
                        }
                        _ => {}
                    }
                }
                Ok((0x9, p)) => if out.send(Out::Pong(p)).is_err() { break },
                Ok((0x8, _)) | Err(_) => break,
                Ok(_) => {}
            }
        }
        let _ = out.send(Out::Close);
    })?;

    let mut pinged = Instant::now();
    let ended = loop {
        match rx.recv_timeout(PING.saturating_sub(pinged.elapsed())) {
            Ok(Out::Text(t)) => if let Err(e) = stream.write_all(&crate::ws::frame(0x1, t.as_bytes())) { break Err(e.into()) },
            Ok(Out::Pong(p)) => if let Err(e) = stream.write_all(&crate::ws::frame(0xA, &p)) { break Err(e.into()) },
            Ok(Out::Close) | Err(RecvTimeoutError::Disconnected) => {
                let _ = stream.write_all(&crate::ws::frame(0x8, &[]));
                break Ok(());
            }
            Err(RecvTimeoutError::Timeout) => {
                if let Err(e) = stream.write_all(&crate::ws::frame(0x9, b"midas")) {
                    break Err(e.into());
                }
                pinged = Instant::now();
            }
        }
    };
    // Gone: its calls fail now rather than at their timeout, and a newer link of the same device stays.
    {
        let mut links = LINKS.lock().unwrap_or_else(|p| p.into_inner());
        if links.get(id).is_some_and(|l| l.n == n) {
            links.remove(id);
        }
    }
    waiting.lock().unwrap_or_else(|p| p.into_inner()).clear();
    let _ = set(id, |d| d["seen"] = json!(registry::now()));
    events::emit("device_unlinked", json!({"device": id}));
    crate::ws::nudge();
    ended
}

/// Why a call could not be made, as the agent should read it.
pub fn offline_text(name: &str) -> String {
    format!("{name} is not connected, and did not link again within {} s of the person being told: \
        the app must be open on it, Developer tools ▸ Midas, with the link switched on. \
        Without the device, run the app on a build node instead (`midas take gpu`, then the project's own way of running \
        it headless and driving it, in Cartopolis the shots skill and `--mcp-headless`): that answers what needs no sensors \
        (state, views, screenshots); camera, motion, magnetometer and GNSS need the device itself", RETURN_WAIT.as_secs())
}

fn linked(id: &str) -> bool {
    LINKS.lock().unwrap_or_else(|p| p.into_inner()).contains_key(id)
}

/// Whether the device is linked by `until`: at once if it is, else after
/// telling the person a session wants it (a push, now) and waiting for it.
fn wait_linked(id: &str, session: &str, until: Instant) -> bool {
    if linked(id) {
        return true;
    }
    let want = want(id, session);
    while !linked(id) && Instant::now() < until {
        std::thread::sleep(Duration::from_millis(200));
    }
    unwant(&want);
    linked(id)
}

/// Tell the person a session wants their phone (a push, now), until [`unwant`].
fn want(id: &str, session: &str) -> (String, String, i64) {
    let want = (id.to_string(), session.to_string(), registry::now());
    WANTED.lock().unwrap_or_else(|p| p.into_inner()).push(want.clone());
    crate::push::nudge();
    events::emit("device_wanted", json!({"device": id, "session": session}));
    want
}

fn unwant(want: &(String, String, i64)) {
    WANTED.lock().unwrap_or_else(|p| p.into_inner()).retain(|w| w != want);
}

/// Drop link `n` of a device: it took a call and did not say so.
fn drop_link(id: &str, n: u64) {
    let mut links = LINKS.lock().unwrap_or_else(|p| p.into_inner());
    if links.get(id).is_some_and(|l| l.n == n) {
        if let Some(l) = links.remove(id) {
            let _ = l.out.send(Out::Close);
        }
    }
}

/// How one try at a call ended.
enum Try {
    Answer(Value),
    /// The device never had it: the link is dead, and the call can go again.
    Lost,
    Failed(anyhow::Error),
}

/// Send the call down the device's link and wait, by `deadline`, for its answer.
fn try_call(id: &str, name: &str, tool: &str, session: &str, request: &Value, deadline: Instant) -> Try {
    let (tx, rx) = mpsc::channel();
    let n = NEXT.fetch_add(1, Ordering::SeqCst);
    let (waiting, link, acks, away) = {
        let links = LINKS.lock().unwrap_or_else(|p| p.into_inner());
        let Some(l) = links.get(id) else { return Try::Lost };
        l.waiting.lock().unwrap_or_else(|p| p.into_inner()).insert(n, tx);
        let msg = json!({"type": "call", "id": n, "session": session, "request": request});
        if l.out.send(Out::Text(msg.to_string())).is_err() {
            return Try::Lost;
        }
        (l.waiting.clone(), l.n, l.acks.load(Ordering::SeqCst), l.away.clone())
    };
    let forget = || { waiting.lock().unwrap_or_else(|p| p.into_inner()).remove(&n); };
    let mut got = !acks;
    // Set while the phone holds the call off screen and the person has been told.
    let mut wanted = None;
    let r = loop {
        if got && wanted.is_none() && away.load(Ordering::SeqCst) {
            wanted = Some(want(id, session));
        }
        let left = deadline.saturating_duration_since(Instant::now());
        // Once it has the call, look each second whether it went off screen.
        let wait = if got { left.min(Duration::from_secs(1)) } else { left.min(ACK) };
        match rx.recv_timeout(wait) {
            Ok(Reply::Answer(v)) => break Try::Answer(v),
            Ok(Reply::Got) => got = true,
            Err(RecvTimeoutError::Timeout) if !got && wait == ACK => {
                forget();
                events::emit("device_no_ack", json!({"device": id, "tool": tool}));
                drop_link(id, link);
                break Try::Lost;
            }
            Err(RecvTimeoutError::Timeout) if Instant::now() < deadline => {}
            Err(RecvTimeoutError::Timeout) => {
                forget();
                break Try::Failed(if wanted.is_some() {
                    anyhow::anyhow!("{name} had {tool} but stayed off screen: the app answers once it is opened")
                } else {
                    anyhow::anyhow!("{name} did not answer {tool} in time")
                });
            }
            // The link went. Before the device had the call, it can go again.
            Err(RecvTimeoutError::Disconnected) if !got => break Try::Lost,
            Err(RecvTimeoutError::Disconnected) => {
                break Try::Failed(anyhow::anyhow!("{name} went while it worked on {tool}, which may have been done: \
                    look before asking again"));
            }
        }
    };
    if let Some(w) = wanted {
        unwant(&w);
    }
    r
}

/// Relay one MCP request (`tools/call`) to a device and wait for its answer:
/// the JSON-RPC response, as the device sent it.
///
/// A device that is not linked is waited for, up to [`RETURN_WAIT`], with the
/// person told their phone is wanted; one that does not acknowledge the call
/// within [`ACK`] is a dead link, dropped and waited for the same way, and the
/// call sent once more when it is back. All within `timeout`.
pub fn call(id: &str, session: &str, request: &Value, timeout: Duration, by: &str) -> Result<Value> {
    let dev = get(id).with_context(|| format!("no device {id}"))?;
    let name = dev["name"].as_str().unwrap_or(id).to_string();
    let tool = request["params"]["name"].as_str().unwrap_or("?").to_string();
    let deadline = Instant::now() + timeout.min(Duration::from_secs(CALL_MAX_S));
    events::emit("device_call", json!({"actor": by, "device": id, "session": session, "tool": tool}));
    // In the conversation too, where the person reads what the session took from their phone.
    let _ = crate::sessions::status_line(session, &format!("{tool} on {name}"));
    let started = Instant::now();
    let r = relay(id, &name, &tool, session, request, deadline);
    // How it went, which the log did not say: what a call costs, and where, was
    // pieced together from transcripts until this (2026-11-04).
    let (ok, bytes) = match &r {
        Ok(v) => (v.get("error").is_none_or(Value::is_null), v.to_string().len()),
        Err(_) => (false, 0),
    };
    events::emit("device_answer", json!({"device": id, "session": session, "tool": tool,
        "ms": started.elapsed().as_millis() as u64, "ok": ok, "bytes": bytes,
        "error": r.as_ref().err().map(|e| format!("{e:#}"))}));
    r
}

fn relay(id: &str, name: &str, tool: &str, session: &str, request: &Value, deadline: Instant) -> Result<Value> {
    for _ in 0..2 {
        if !wait_linked(id, session, deadline.min(Instant::now() + RETURN_WAIT)) {
            break;
        }
        match try_call(id, name, tool, session, request, deadline) {
            Try::Answer(v) => return Ok(v),
            Try::Failed(e) => return Err(e),
            Try::Lost => {}
        }
    }
    if linked(id) {
        bail!("{name} is linked but did not acknowledge {tool} within {} s, twice: it is not reachable now", ACK.as_secs());
    }
    bail!("{}", offline_text(&name))
}

/// What a device may push to: its person's sessions still open.
pub fn sessions_for(_device: &Value) -> Vec<Value> {
    crate::sessions::list().as_array().into_iter().flatten()
        .filter(|m| !matches!(m["status"].as_str(), Some("stopped" | "failed")) && m["archived"] != true && m["imported"].is_null())
        .map(|m| json!({"id": m["id"], "title": m["title"], "status": m["status"]}))
        .collect()
}

/// The largest push: a log and a few pictures.
pub const PUSH_MAX: usize = 24 << 20;

/// A message from a device to a session: words, and files (`{name, data}`, base64).
pub fn push(device_id: &str, device: &Value, body: &Value) -> Result<()> {
    let session = body["session"].as_str().context("which session?")?;
    if !sessions_for(device).iter().any(|s| s["id"] == session) {
        bail!("{session} is not an open session");
    }
    let name = device["name"].as_str().unwrap_or(device_id);
    let mut images = Vec::new();
    let mut files = Vec::new();
    for f in body["files"].as_array().into_iter().flatten() {
        let fname = f["name"].as_str().context("a file with no name")?;
        let bytes = data_encoding::BASE64.decode(f["data"].as_str().unwrap_or("").as_bytes()).context("a file's data is base64")?;
        if matches!(crate::sessions::mime_of(fname), "image/png" | "image/jpeg" | "image/gif" | "image/webp") {
            images.push(json!(crate::sessions::upload(fname, &bytes)?));
        } else {
            files.push(json!({"name": fname, "data": f["data"]}));
        }
    }
    let text = body["text"].as_str().unwrap_or("").trim();
    let text = if text.is_empty() { format!("From {name}.") } else { text.to_string() };
    crate::sessions::tell(session, "message", &json!({"text": text, "images": images, "files": files}), &format!("device:{name}"))?;
    let _ = set(device_id, |d| d["seen"] = json!(registry::now()));
    events::emit("device_push", json!({"device": device_id, "session": session}));
    Ok(())
}

// ── In a session: the device as an MCP server ───────────────────────────────

/// Where a session keeps what devices answered: out of the repository, so a
/// screenshot is never a file `git status` shows.
pub fn files_dir() -> PathBuf {
    let owner = std::env::var("MIDAS_OWNER").unwrap_or_else(|_| "local".into());
    let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
    PathBuf::from(home).join(".cache/midas/device").join(owner)
}

/// Text longer than this goes to a file, with its head inline.
const INLINE_TEXT: usize = 32 * 1024;

/// A device's answer, as the session takes it: pictures kept as files (and
/// shown on the page) and inline too; long text and blobs as files.
pub fn keep(result: &Value, tool: &str, device: &str, dir: &std::path::Path) -> Value {
    let mut out = result.clone();
    let Some(content) = out["content"].as_array_mut() else { return out };
    let mut extra = Vec::new();
    for c in content.iter_mut() {
        let n = std::fs::create_dir_all(dir).ok().and_then(|_| std::fs::read_dir(dir).ok()).map_or(0, |d| d.count()) + 1;
        match c["type"].as_str() {
            Some("image") => {
                let ext = match c["mimeType"].as_str() { Some("image/jpeg") => "jpg", Some("image/webp") => "webp", _ => "png" };
                let file = dir.join(format!("{n}-{tool}.{ext}"));
                if let Ok(bytes) = data_encoding::BASE64.decode(c["data"].as_str().unwrap_or("").as_bytes()) {
                    if std::fs::write(&file, bytes).is_ok() {
                        let path = file.display().to_string();
                        let _ = crate::sessions::show(&path, Some(&format!("{tool}, from {device}")), None);
                        extra.push(json!({"type": "text", "text": format!("saved as {path}")}));
                    }
                }
            }
            Some("text") => {
                let t = c["text"].as_str().unwrap_or("");
                if t.len() > INLINE_TEXT {
                    let file = dir.join(format!("{n}-{tool}.txt"));
                    if std::fs::write(&file, t).is_ok() {
                        let mut head: String = t.chars().take(2000).collect();
                        head.push_str("\n…");
                        *c = json!({"type": "text", "text": format!("{} bytes, saved as {}; it begins:\n{head}", t.len(), file.display())});
                    }
                }
            }
            Some("resource") => {
                let r = &c["resource"];
                let uri = r["uri"].as_str().unwrap_or("");
                let base = uri.rsplit('/').next().filter(|b| !b.is_empty() && crate::sessions::file_ok(b)).unwrap_or(tool);
                let file = dir.join(format!("{n}-{base}"));
                let bytes = match (r["text"].as_str(), r["blob"].as_str()) {
                    (Some(t), _) => Some(t.as_bytes().to_vec()),
                    (None, Some(b)) => data_encoding::BASE64.decode(b.as_bytes()).ok(),
                    _ => None,
                };
                if let Some(b) = bytes.filter(|b| std::fs::write(&file, b).is_ok()) {
                    *c = json!({"type": "text", "text": format!("{uri}: {} bytes, saved as {}", b.len(), file.display())});
                }
            }
            _ => {}
        }
    }
    content.extend(extra);
    out
}

/// How long a call may take on the device, in seconds: 60, and any time the
/// call itself asks to spend there (a recording's `seconds`, a view's `wait_s`)
/// on top. A view that waits 30 s for its tiles, after a teleport and before
/// its upload, ran out of a flat 60 with the phone linked (s598, 2026-11-04).
pub fn tool_time(args: &Value) -> u64 {
    60 + ["seconds", "wait_s"].iter().filter_map(|k| args[*k].as_f64()).fold(0.0, f64::max).ceil() as u64
}

/// One call from a session: the device's result, kept (`keep`), or an error to show the agent.
pub fn call_from_session(id: &str, tool: &str, args: &Value, timeout_s: u64) -> Result<Value> {
    let session = std::env::var("MIDAS_OWNER").unwrap_or_default();
    // The tool's own time, and the wait for a phone that is away on top of it.
    let timeout_s = timeout_s + RETURN_WAIT.as_secs();
    let request = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": args}});
    let v = crate::client::post_long("/v1/devices/call", &json!({"device": id, "session": session.strip_prefix("session-").unwrap_or(&session),
        "request": request, "timeout": timeout_s}), Duration::from_secs(timeout_s.min(CALL_MAX_S) + 15))?;
    if let Some(e) = v["response"].get("error").filter(|e| !e.is_null()) {
        bail!("{}", e["message"].as_str().unwrap_or("the device refused"));
    }
    Ok(keep(&v["response"]["result"], tool, v["name"].as_str().unwrap_or(id), &files_dir()))
}

/// `midas device mcp <id>`: one device as an MCP server on stdio.
pub fn serve_mcp(id: &str) -> Result<i32> {
    let stdin = std::io::stdin();
    let mut out = std::io::stdout();
    let dev = || crate::client::get(&format!("/v1/devices/{id}")).ok();
    for line in stdin.lock().lines() {
        let line = line?;
        let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
        let Some(rid) = msg.get("id").cloned() else { continue };
        let resp = match msg["method"].as_str().unwrap_or("") {
            "initialize" => {
                let d = dev().unwrap_or(Value::Null);
                let name = d["name"].as_str().unwrap_or(id);
                json!({"jsonrpc": "2.0", "id": rid, "result": {
                    "protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or(crate::mcp::PROTOCOL),
                    "capabilities": {"tools": {}},
                    "serverInfo": {"name": format!("device {name}"), "version": crate::VERSION},
                    "instructions": format!("{name}: a device paired to the Midas hub ({} {}), its tools relayed to it while its app is open. \
                        Pictures it answers are saved under {} and shown to the person; long text is saved there too. \
                        When it is not connected, a call tells the person their phone is wanted and waits up to {} s for it; \
                        it fails when the phone does not come back, or when its build has no such tool: then run the app on a build node \
                        (`midas take gpu`) with the session's own code. Sensor tools need the device.",
                        d["app"].as_str().unwrap_or("app"), d["build"]["version"].as_str().or(d["version"].as_str()).unwrap_or(""),
                        files_dir().display(), RETURN_WAIT.as_secs()),
                }})
            }
            "ping" => json!({"jsonrpc": "2.0", "id": rid, "result": {}}),
            "tools/list" => json!({"jsonrpc": "2.0", "id": rid, "result": {"tools": dev().map(|d| d["tools"].clone()).unwrap_or(json!([]))}}),
            "tools/call" => {
                let tool = msg["params"]["name"].as_str().unwrap_or("");
                let args = msg["params"]["arguments"].clone();
                let timeout = crate::device::tool_time(&args);
                match call_from_session(id, tool, &args, timeout) {
                    Ok(r) => json!({"jsonrpc": "2.0", "id": rid, "result": r}),
                    Err(e) => json!({"jsonrpc": "2.0", "id": rid, "result": {"content": [{"type": "text", "text": format!("{e:#}")}], "isError": true}}),
                }
            }
            m => json!({"jsonrpc": "2.0", "id": rid, "error": {"code": -32601, "message": format!("no method {m}")}}),
        };
        writeln!(out, "{resp}")?;
        out.flush()?;
    }
    Ok(0)
}

/// The devices as ACP `mcpServers` for a session the runner opens: one each,
/// by its name (two of one name told apart by id). None when the hub cannot say.
pub fn mcp_servers() -> Vec<Value> {
    let Ok(exe) = crate::util::exe() else { return vec![] };
    let Ok(v) = crate::client::get("/v1/devices") else { return vec![] };
    let mut seen = std::collections::HashSet::new();
    v["devices"].as_array().into_iter().flatten().filter_map(|d| {
        let id = d["id"].as_str()?;
        let mut name = d["server"].as_str().map_or_else(|| slug(""), str::to_string);
        if !seen.insert(name.clone()) {
            name = format!("{name}-{id}");
        }
        Some(json!({"name": name, "command": exe.display().to_string(), "args": ["device", "mcp", id], "env": []}))
    }).collect()
}

/// `midas device list|forget|code`: the devices from the command line.
pub fn cli_list() -> Result<i32> {
    let v = crate::client::get("/v1/devices")?;
    let all = v["devices"].as_array().cloned().unwrap_or_default();
    if all.is_empty() {
        println!("no devices paired: Settings ▸ This device ▸ Paired apps, on the page");
    }
    for d in all {
        let tools: Vec<&str> = d["tools"].as_array().into_iter().flatten().filter_map(|t| t["name"].as_str()).collect();
        println!("{}  {:<20} {} {}  {}  {}", d["id"].as_str().unwrap_or("?"), d["name"].as_str().unwrap_or("?"),
                 d["app"].as_str().unwrap_or(""), d["build"]["version"].as_str().or(d["version"].as_str()).unwrap_or(""),
                 if d["online"] == true { "online" } else { "offline" }, tools.join(", "));
    }
    Ok(0)
}

// ── A stand-in device, to try the link with no app ──────────────────────────

/// A client's frame: masked, as RFC 6455 §5.3 has every client's.
fn client_frame(opcode: u8, payload: &[u8]) -> Result<Vec<u8>> {
    let mut f = crate::ws::frame(opcode, payload);
    let at = match payload.len() { n if n < 126 => 2, n if n <= 0xffff => 4, _ => 10 };
    f[1] |= 0x80;
    let mask: [u8; 4] = crate::accounts::random(4)?.try_into().map_err(|_| anyhow::anyhow!("no mask"))?;
    let body: Vec<u8> = f[at..].iter().enumerate().map(|(i, b)| b ^ mask[i % 4]).collect();
    f.truncate(at);
    f.extend_from_slice(&mask);
    f.extend(body);
    Ok(f)
}

/// A server's frame: `(opcode, payload)`.
fn server_frame(r: &mut impl std::io::Read) -> Result<(u8, Vec<u8>)> {
    let mut h = [0u8; 2];
    r.read_exact(&mut h)?;
    let len = match h[1] & 0x7f {
        126 => { let mut b = [0u8; 2]; r.read_exact(&mut b)?; u16::from_be_bytes(b) as u64 }
        127 => { let mut b = [0u8; 8]; r.read_exact(&mut b)?; u64::from_be_bytes(b) }
        n => n as u64,
    };
    if len > FRAME_MAX {
        bail!("a {len}-byte frame");
    }
    let mut p = vec![0u8; len as usize];
    r.read_exact(&mut p)?;
    Ok((h[0] & 0x0f, p))
}

/// `midas device fake CODE --hub URL`: pair, link, and answer `echo` until stopped.
pub fn fake(code: &str, hub: &str, name: &str) -> Result<i32> {
    let base = hub.trim_end_matches('/');
    let (status, text) = crate::hub::request(base, "POST", "/v1/device/pair",
        Some(&json!({"code": code, "name": name, "app": "midas-fake", "version": crate::VERSION}).to_string()))?;
    let paired: Value = serde_json::from_str(&text).unwrap_or(Value::Null);
    if status != 200 {
        bail!("pairing refused ({status}): {}", paired["error"].as_str().unwrap_or(&text));
    }
    let token = paired["token"].as_str().context("no token")?;
    println!("paired as {} ({})", paired["name"], paired["id"]);
    stand_in(base.trim_start_matches("http://"), token, Stand::Answer)
}

/// How a stand-in device behaves.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Stand {
    Answer,
    /// Says it acknowledges calls and then takes them in silence, as a phone
    /// behind a dead socket does.
    Mute,
    /// Off screen: acknowledges a call, holds it a while as a phone does until
    /// it is opened, and then comes back and answers.
    Away,
}

/// Link as the device `token` is, at `addr`, and answer `echo` until the hub
/// closes the link.
pub(crate) fn stand_in(addr: &str, token: &str, how: Stand) -> Result<i32> {
    let mut s = TcpStream::connect(addr)?;
    let key = data_encoding::BASE64.encode(&crate::accounts::random(16)?);
    write!(s, "GET /v1/device/link HTTP/1.1\r\nHost: {addr}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\
               Sec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\nX-Midas-Device: {token}\r\n\r\n")?;
    let mut r = std::io::BufReader::new(s.try_clone()?);
    let mut line = String::new();
    r.read_line(&mut line)?;
    if !line.contains(" 101 ") {
        bail!("the hub would not link: {}", line.trim());
    }
    while { line.clear(); r.read_line(&mut line)? > 2 } {}
    let tools = json!([{"name": "echo", "description": "Answers with the text it was given.",
                        "inputSchema": {"type": "object", "properties": {"text": {"type": "string"}}, "required": ["text"]}}]);
    s.write_all(&client_frame(0x1, json!({"type": "hello", "tools": tools, "build": {"version": crate::VERSION}, "ack": true}).to_string().as_bytes())?)?;
    if how == Stand::Away {
        s.write_all(&client_frame(0x1, json!({"type": "away", "away": true}).to_string().as_bytes())?)?;
    }
    println!("linked; answering echo");
    loop {
        let (op, p) = server_frame(&mut r)?;
        match op {
            0x1 => {
                let v: Value = serde_json::from_slice(&p).unwrap_or(Value::Null);
                if v["type"] != "call" || how == Stand::Mute {
                    continue;
                }
                s.write_all(&client_frame(0x1, json!({"type": "ack", "id": v["id"]}).to_string().as_bytes())?)?;
                if how == Stand::Away {
                    std::thread::sleep(Duration::from_millis(2500));
                    s.write_all(&client_frame(0x1, json!({"type": "away", "away": false}).to_string().as_bytes())?)?;
                }
                let req = &v["request"];
                let response = if req["params"]["name"] == "echo" {
                    json!({"jsonrpc": "2.0", "id": req["id"], "result": {"content": [{"type": "text", "text": req["params"]["arguments"]["text"]}]}})
                } else {
                    json!({"jsonrpc": "2.0", "id": req["id"], "error": {"code": -32602, "message": format!("no tool {}", req["params"]["name"])}})
                };
                println!("{} from {}", req["params"]["name"], v["session"]);
                s.write_all(&client_frame(0x1, json!({"type": "result", "id": v["id"], "response": response}).to_string().as_bytes())?)?;
            }
            0x9 => s.write_all(&client_frame(0xA, &p)?)?,
            0x8 => {
                println!("the hub closed the link");
                return Ok(0);
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn codes_are_typed_as_they_are_read() {
        assert_eq!(normal("abcd-ef 23"), "ABCDEF23");
        assert!(!ALPHABET.iter().any(|c| b"01OIL".contains(c)));
        assert_eq!(slug("OnePlus 15"), "oneplus-15");
        assert_eq!(slug("  ¿?  "), "device");
    }

    #[test]
    fn a_call_gets_the_time_it_asks_to_spend() {
        assert_eq!(tool_time(&json!({})), 60);
        assert_eq!(tool_time(&json!({"seconds": 30})), 90);
        assert_eq!(tool_time(&json!({"wait_s": 29.5, "lat": 53.2})), 90);
    }

    #[test]
    fn long_text_and_pictures_go_to_files() {
        let dir = std::env::temp_dir().join(format!("midas-device-keep-{}", std::process::id()));
        let long = "x".repeat(INLINE_TEXT + 1);
        let r = keep(&json!({"content": [{"type": "text", "text": "short"}, {"type": "text", "text": long},
            {"type": "resource", "resource": {"uri": "cartopolis://log/precision.log", "text": "a log"}}]}), "precision_log", "phone", &dir);
        let c = r["content"].as_array().unwrap();
        assert_eq!(c[0]["text"], "short");
        assert!(c[1]["text"].as_str().unwrap().contains("saved as"), "{}", c[1]);
        assert!(c[2]["text"].as_str().unwrap().contains("precision.log"), "{}", c[2]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_paired_device_answers_a_call_through_the_hub_and_forgetting_it_ends_that() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner());
        crate::tests::scratch("device-link");
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap().to_string();
        std::thread::spawn(move || {
            for c in listener.incoming().flatten() {
                std::thread::spawn(move || { let _ = crate::hub::handle(c, "127.0.0.1"); });
            }
        });

        let code = code("sam", "hub.example").unwrap()["code"].as_str().unwrap().to_string();
        assert!(pair("WRONGONE", "Phone", "test", "1").is_err(), "a wrong code pairs nothing");
        let paired = pair(&code.to_lowercase(), "OnePlus 15", "cartopolis", "1").unwrap();
        assert!(pair(&code, "Again", "test", "1").is_err(), "a code is good once");
        let (id, token) = (paired["id"].as_str().unwrap().to_string(), paired["token"].as_str().unwrap().to_string());
        assert_eq!(by_token(&token).unwrap().1["account"], "sam");
        assert!(read().devices[&id]["token"] != json!(token), "kept hashed");

        let request = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "hi"}}});
        let err = call(&id, "s1", &request, Duration::from_secs(1), "test").unwrap_err();
        assert!(format!("{err:#}").contains("not connected"), "{err:#}");
        assert!(wanted().is_empty(), "a call that gave up wants the phone no longer");

        let until = |what: &str, ok: &dyn Fn() -> bool| {
            let deadline = Instant::now() + Duration::from_secs(10);
            while !ok() {
                assert!(Instant::now() < deadline, "{what}");
                std::thread::sleep(Duration::from_millis(50));
            }
        };
        let link = |how: Stand| {
            let (a, t) = (addr.clone(), token.clone());
            std::thread::spawn(move || stand_in(&a, &t, how))
        };

        // A call while the phone is away tells the person, and waits for it to come back.
        let (i, r) = (id.clone(), request.clone());
        let waiting = std::thread::spawn(move || call(&i, "s1", &r, Duration::from_secs(10), "test"));
        until("the call never said it wants the phone", &|| !wanted().is_empty());
        assert_eq!(wanted()[0]["title"], "s1 wants your phone");
        let device = link(Stand::Answer);
        assert_eq!(waiting.join().unwrap().unwrap()["result"]["content"][0]["text"], "hi");
        assert!(wanted().is_empty());
        assert_eq!(list()[0]["server"], "cartopolis", "named for its app, not the phone");
        // A second phone with the same app: both are told apart by their own names.
        let second = super::code("sam", "hub.example").unwrap()["code"].as_str().unwrap().to_string();
        pair(&second, "Pixel 9", "cartopolis", "1").unwrap();
        let mut servers: Vec<String> = list().iter().map(|d| d["server"].as_str().unwrap().to_string()).collect();
        servers.sort();
        assert_eq!(servers, ["cartopolis-oneplus-15", "cartopolis-pixel-9"]);
        assert!(get(&id).unwrap()["tools"].as_array().is_some_and(|t| !t.is_empty()), "it said its tools");

        // A link that takes a call and does not acknowledge it is dropped within
        // seconds, and the call goes again once the phone is back.
        let mute = link(Stand::Mute);
        assert_eq!(device.join().unwrap().unwrap(), 0, "a newer link replaces the old");
        // Its hello, which says it acknowledges calls, follows the upgrade at once.
        std::thread::sleep(Duration::from_millis(300));
        let (i, r) = (id.clone(), request.clone());
        let started = Instant::now();
        let waiting = std::thread::spawn(move || call(&i, "s1", &r, Duration::from_secs(30), "test"));
        assert_eq!(mute.join().unwrap().unwrap(), 0, "the silent link is closed");
        assert!(started.elapsed() < ACK + Duration::from_secs(3), "{:?}", started.elapsed());
        until("the call never said it wants the phone again", &|| !wanted().is_empty());
        let device = link(Stand::Answer);
        assert_eq!(waiting.join().unwrap().unwrap()["result"]["content"][0]["text"], "hi");

        // A phone off screen keeps its link and holds the call: the person is
        // told, and the answer comes when it is opened.
        let away = link(Stand::Away);
        assert_eq!(device.join().unwrap().unwrap(), 0);
        until("the away link never said so", &|| get(&id).is_some_and(|d| d["away"] == true));
        let (i, r) = (id.clone(), request.clone());
        let waiting = std::thread::spawn(move || call(&i, "s1", &r, Duration::from_secs(10), "test"));
        until("a call held off screen never said it wants the phone", &|| !wanted().is_empty());
        assert_eq!(waiting.join().unwrap().unwrap()["result"]["content"][0]["text"], "hi");
        assert!(wanted().is_empty(), "answered, the phone is wanted no longer");
        assert_eq!(get(&id).unwrap()["away"], false);
        let device = away;

        // Through the API, a session's machine calls and a page cannot.
        let (code_ok, _) = crate::hub::request(&format!("http://{addr}"), "GET", "/v1/devices", None).unwrap();
        assert_eq!(code_ok, 200);
        let (refused, _) = crate::hub::request(&format!("http://{addr}"), "GET", "/v1/device/sessions", None).unwrap();
        assert_eq!(refused, 401, "a device's paths take its token");

        forget(&id, "test").unwrap();
        assert!(by_token(&token).is_none());
        assert_eq!(device.join().unwrap().unwrap(), 0, "the link is closed at once");
    }
}