~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/hud

A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts

0
0
3134 lines · 114.8 KB Raw History
//! The workspace's methods through the router whole, as a page and an app
//! call them: each method's happy path and its named errors, every answer
//! held to its lexicon's output (and every failure to `{error, message}`,
//! its error one the method names); the live stream across two canvases
//! and two people, and its end as the server stops; a file store from
//! before columns and tabs; apps' icons; images uploaded to a fake PDS.
//! With `HUD_ANSWERS` naming a directory, each answer is also kept there,
//! a JSON line `{path, status, body}`, for `harness/answers.mjs`.

use super::*;
use axum::http::Request;
use futures::StreamExt;
use hud_core::Config;
use hud_core::oauth::COOKIE;
use std::sync::Mutex;
use tower::ServiceExt;

const ORIGIN: &str = "https://hud.example";
const ALICE: &str = "did:plc:alice";
const BOB: &str = "did:plc:bob";
const CAROL: &str = "did:plc:carol";
/// The one account the server names as its operator.
const OPERATOR: &str = "did:plc:operator";

/// HUD's lexicons, each method's output schema a def of its own, `output`.
static OUTPUTS: LazyLock<atproto::lexicon::Lexicons> = LazyLock::new(|| {
    atproto::lexicon::Lexicons::new(
        hud_core::lexicon::all_bundled()
            .filter(|d| d["id"].as_str().is_some_and(|id| id.starts_with(NS)))
            .map(|d| {
                let mut d = (**d).clone();
                let schema = d["defs"]["main"]["output"]["schema"].clone();
                if schema.is_object() {
                    d["defs"]["output"] = schema;
                }
                d
            }),
    )
});

/// Keeps the answers' file whole, a line at a time.
static KEPT: Mutex<()> = Mutex::new(());

/// What a test double answers, and what it was asked: favicons, DID
/// documents as PLC serves them, as every account's PDS and the relay,
/// people's themes (`themes`: each repository's DID, record key and record),
/// a PDS's `uploadBlob`, `createRecord` and `deleteRecord`; and under
/// `/ended` a PDS that has ended every session, under `/broken` one that
/// refuses everything, under `/lacking` one that refuses for want of scope.
#[derive(Default)]
struct Double {
    asked: Vec<String>,
    themes: Vec<(&'static str, &'static str, Json)>,
    /// Each blob a PDS took: its content type, its bytes, and whether it
    /// came as the account (DPoP, with a proof).
    uploads: Vec<(String, Vec<u8>, bool)>,
    /// Whether the PDS has asked for a DPoP nonce yet.
    nonced: bool,
    /// Each record a PDS was asked to create or delete, as asked.
    writes: Vec<Json>,
}

/// A PNG's first bytes, as an icon begins.
const PNG: &[u8] = b"\x89PNG\r\n\x1a\nicon";

/// The double, listening: its origin, and what it was asked.
async fn double() -> (String, Arc<Mutex<Double>>) {
    use axum::extract::Query;
    use std::collections::HashMap;
    let state = Arc::new(Mutex::new(Double::default()));
    let favicons = {
        let state = state.clone();
        move |Query(q): Query<HashMap<String, String>>| {
            let state = state.clone();
            async move {
                let url = q.get("url").cloned().unwrap_or_default();
                let first = {
                    let mut s = state.lock().unwrap();
                    s.asked.push(url.clone());
                    s.asked.iter().filter(|u| **u == url).count() == 1
                };
                let png =
                    |body: Vec<u8>| ([(header::CONTENT_TYPE, "image/png")], body).into_response();
                match url.as_str() {
                    // Too busy to answer, the first time.
                    "https://busy.app" if first => StatusCode::SERVICE_UNAVAILABLE.into_response(),
                    "https://bsky.app" | "https://plyr.fm" | "https://busy.app" => {
                        png(PNG.to_vec())
                    }
                    "https://big.app" => png(vec![0; hud_core::icons::ICON_AT_MOST + 1]),
                    "https://html.app" => (
                        [(header::CONTENT_TYPE, "text/html")],
                        "<html></html>".to_string(),
                    )
                        .into_response(),
                    _ => StatusCode::NOT_FOUND.into_response(),
                }
            }
        }
    };
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let origin = format!("http://{}", listener.local_addr().unwrap());
    let pds = origin.clone();
    let plc = move |Path(did): Path<String>| {
        let pds = pds.clone();
        async move {
            axum::Json(
                json!({ "id": did, "alsoKnownAs": [], "verificationMethod": [],
                "service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer",
                              "serviceEndpoint": pds }] }),
            )
        }
    };
    // Handles as a PDS resolves its own: alice.test and bob.test.
    let handles = |Query(q): Query<HashMap<String, String>>| async move {
        match q.get("handle").map(String::as_str) {
            Some("alice.test") => axum::Json(json!({ "did": ALICE })).into_response(),
            Some("bob.test") => axum::Json(json!({ "did": BOB })).into_response(),
            _ => (
                StatusCode::BAD_REQUEST,
                axum::Json(
                    json!({ "error": "InvalidRequest", "message": "Unable to resolve handle" }),
                ),
            )
                .into_response(),
        }
    };
    // A PDS's uploadBlob: it asks for a DPoP nonce first, as a PDS does.
    let uploads = {
        let state = state.clone();
        move |headers: HeaderMap, body: axum::body::Bytes| {
            let state = state.clone();
            async move {
                let mut s = state.lock().unwrap();
                let said = |k: header::HeaderName| {
                    headers
                        .get(k)
                        .and_then(|v| v.to_str().ok())
                        .unwrap_or_default()
                        .to_string()
                };
                if !s.nonced {
                    s.nonced = true;
                    return (
                        StatusCode::UNAUTHORIZED,
                        [("dpop-nonce", "n1")],
                        axum::Json(json!({ "error": "use_dpop_nonce", "message": "nonce" })),
                    )
                        .into_response();
                }
                let kind = said(header::CONTENT_TYPE);
                let as_account = said(header::AUTHORIZATION).starts_with("DPoP ")
                    && headers.contains_key("dpop");
                let cid = atproto::Cid::of_raw(&body).to_string();
                let size = body.len();
                s.uploads.push((kind.clone(), body.to_vec(), as_account));
                axum::Json(json!({ "blob": { "$type": "blob", "ref": { "$link": cid },
                    "mimeType": kind, "size": size } }))
                .into_response()
            }
        }
    };
    // People's themes, as their PDS lists and reads them (a page of
    // `limit`, a cursor if there are more), and the relay lists the
    // repositories holding them.
    let records = {
        let state = state.clone();
        move |Query(q): Query<HashMap<String, String>>| {
            let state = state.clone();
            async move {
                let repo = q.get("repo").cloned().unwrap_or_default();
                let limit = q
                    .get("limit")
                    .and_then(|l| l.parse().ok())
                    .unwrap_or(usize::MAX);
                let s = state.lock().unwrap();
                let mut records: Vec<Json> = s
                    .themes
                    .iter()
                    .filter(|(did, _, _)| *did == repo)
                    .map(|(did, rkey, value)| json!({ "uri": format!("at://{did}/place.hud.theme/{rkey}"), "cid": "bafy", "value": value }))
                    .collect();
                let more = records.len() > limit;
                records.truncate(limit);
                let mut page = json!({ "records": records });
                if more {
                    page["cursor"] = json!("more");
                }
                axum::Json(page)
            }
        }
    };
    // A record written or deleted, kept as asked.
    let write = |created: bool| {
        let state = state.clone();
        move |axum::Json(asked): axum::Json<Json>| {
            let state = state.clone();
            async move {
                let answer = if created {
                    let uri = format!(
                        "at://{}/{}/3lmade",
                        asked["repo"].as_str().unwrap(),
                        asked["collection"].as_str().unwrap()
                    );
                    json!({ "uri": uri, "cid": "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm" })
                } else {
                    json!({})
                };
                state.lock().unwrap().writes.push(asked);
                axum::Json(answer)
            }
        }
    };
    let record = {
        let state = state.clone();
        move |Query(q): Query<HashMap<String, String>>| {
            let state = state.clone();
            async move {
                let (repo, rkey) = (q.get("repo").cloned(), q.get("rkey").cloned());
                let s = state.lock().unwrap();
                match s.themes.iter().find(|(did, key, _)| {
                    Some(did.to_string()) == repo && Some(key.to_string()) == rkey
                }) {
                    Some((did, key, value)) => axum::Json(json!({ "uri": format!("at://{did}/place.hud.theme/{key}"), "cid": "bafy", "value": value })).into_response(),
                    None => (StatusCode::BAD_REQUEST, axum::Json(json!({ "error": "RecordNotFound", "message": "Could not locate record" }))).into_response(),
                }
            }
        }
    };
    let repos = {
        let state = state.clone();
        move || {
            let state = state.clone();
            async move {
                let mut dids: Vec<&str> =
                    state.lock().unwrap().themes.iter().map(|t| t.0).collect();
                dids.dedup();
                axum::Json(
                    json!({ "repos": dids.iter().map(|did| json!({ "did": did })).collect::<Vec<_>>() }),
                )
            }
        }
    };
    let app = Router::new()
        .route("/favicon", axum::routing::get(favicons))
        .route(
            "/xrpc/com.atproto.identity.resolveHandle",
            axum::routing::get(handles),
        )
        .route(
            "/xrpc/com.atproto.repo.uploadBlob",
            axum::routing::post(uploads),
        )
        .route(
            "/xrpc/com.atproto.repo.createRecord",
            axum::routing::post(write(true)),
        )
        .route(
            "/xrpc/com.atproto.repo.deleteRecord",
            axum::routing::post(write(false)),
        )
        .route(
            "/xrpc/com.atproto.repo.listRecords",
            axum::routing::get(records),
        )
        .route(
            "/xrpc/com.atproto.repo.getRecord",
            axum::routing::get(record),
        )
        .route(
            "/xrpc/com.atproto.sync.listReposByCollection",
            axum::routing::get(repos),
        )
        .route(
            "/ended/xrpc/{method}",
            axum::routing::any(|| async {
                (
                    StatusCode::UNAUTHORIZED,
                    axum::Json(json!({ "error": "invalid_token", "message": "ended" })),
                )
            }),
        )
        .route(
            "/broken/xrpc/{method}",
            axum::routing::any(|| async {
                (
                    StatusCode::BAD_REQUEST,
                    axum::Json(json!({ "error": "InvalidRequest", "message": "no" })),
                )
            }),
        )
        .route(
            "/lacking/xrpc/{method}",
            axum::routing::any(|| async {
                (
                    StatusCode::FORBIDDEN,
                    axum::Json(json!({ "error": "ScopeMissingError", "message": "no" })),
                )
            }),
        )
        .route("/{did}", axum::routing::get(plc));
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (origin, state)
}

/// A server with sign-in on, its data in a directory of its own (or
/// `data_dir`), PLC and favicons at the double.
async fn server(data_dir: Option<std::path::PathBuf>) -> (Arc<Hud>, Arc<Mutex<Double>>) {
    let (double, asked) = double().await;
    let data_dir = data_dir.unwrap_or_else(|| {
        std::env::temp_dir().join(format!("hud-xrpc-{}", atproto::jose::random(6)))
    });
    let hud = Hud::new(Config {
        port: 0,
        bind: "::".parse().unwrap(),
        public_origin: ORIGIN.into(),
        cache_dir: data_dir.join("cache"),
        data_dir,
        oauth: true,
        oauth_scope: hud_core::scope::asked(hud_core::view::views(), true, false),
        oauth_include: None,
        workspace: true,
        spaces: false,
        plc_url: double.clone(),
        handle_resolver: Some(double.clone()),
        allow_private: true,
        blob_cache_bytes: 0,
        cache_memory_bytes: 1 << 24,
        backlinks: hud_core::backlinks::Backlinks::None,
        favicons: Some(format!("{double}/favicon?url=")),
        image_cdn: None,
        relay: Some(double.clone()),
        sign_up_pds: hud_core::config::SIGN_UP_PDS.into(),
        client: Default::default(),
        operators: vec![OPERATOR.into()],
        logs: true,
        logs_keep: hud_core::logs::KEEP,
    })
    .unwrap();
    (hud, asked)
}

/// How a request is signed in.
#[derive(Clone, Copy)]
enum As<'a> {
    /// The page: its cookie, `X-HUD: 1` and the server's own origin.
    Page(&'a str),
    /// The cookie alone, as a page of another site sends it.
    Cookie(&'a str),
    Bearer(&'a str),
    Nobody,
}

/// A web session's cookie, and an access token, of `did`.
fn sessions(hud: &Hud, did: &str, handle: &str) -> (String, String) {
    let auth = hud.auth().unwrap();
    (
        auth.signed_in_offline(did, Some(handle), true),
        auth.signed_in_offline(did, Some(handle), false),
    )
}

fn request(path: &str, who: As<'_>, body: Option<&Json>) -> Request<Body> {
    sent(
        path,
        who,
        body.map(|b| ("application/json", b.to_string().into_bytes())),
    )
}

/// A request of `path` as `who`: a POST of `body` (its content type and
/// bytes) if given, else a GET.
fn sent(path: &str, who: As<'_>, body: Option<(&str, Vec<u8>)>) -> Request<Body> {
    let mut r = Request::builder()
        .uri(path)
        .method(if body.is_some() { "POST" } else { "GET" });
    match who {
        As::Page(c) => {
            r = r
                .header("cookie", format!("theme=dark; {COOKIE}={c}"))
                .header("x-hud", "1")
                .header("origin", ORIGIN);
        }
        As::Cookie(c) => r = r.header("cookie", format!("{COOKIE}={c}")),
        As::Bearer(t) => r = r.header("authorization", format!("Bearer {t}")),
        As::Nobody => {}
    }
    match body {
        Some((kind, b)) => r.header("content-type", kind).body(Body::from(b)).unwrap(),
        None => r.body(Body::empty()).unwrap(),
    }
}

/// Keep an answer for harness/answers.mjs, where the run names a
/// directory for them.
fn keep(path: &str, status: StatusCode, body: &Json) {
    let Some(dir) = std::env::var_os("HUD_ANSWERS") else {
        return;
    };
    let _one = KEPT
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    std::fs::create_dir_all(&dir).unwrap();
    let file = std::path::Path::new(&dir).join(format!("hud-server-{}.jsonl", std::process::id()));
    let line = json!({ "path": path, "status": status.as_u16(), "body": body });
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(file)
        .unwrap();
    writeln!(f, "{line}").unwrap();
}

/// A method called: its status and answer, held to its lexicon: a
/// success valid for its output, a failure `{error, message}` naming an
/// error the method declares.
async fn ask(hud: &Arc<Hud>, path: &str, who: As<'_>, body: Option<Json>) -> (StatusCode, Json) {
    asked(hud, path, request(path, who, body.as_ref())).await
}

/// As `ask`, the request made already.
async fn asked(hud: &Arc<Hud>, path: &str, req: Request<Body>) -> (StatusCode, Json) {
    let (status, _, answer) = answered(hud, path, req).await;
    (status, answer)
}

/// As `asked`, with the answer's headers.
async fn answered(hud: &Arc<Hud>, path: &str, req: Request<Body>) -> (StatusCode, HeaderMap, Json) {
    let r = crate::router(hud.clone(), None).oneshot(req).await.unwrap();
    let status = r.status();
    let headers = r.headers().clone();
    let bytes = axum::body::to_bytes(r.into_body(), usize::MAX)
        .await
        .unwrap();
    let answer: Json = serde_json::from_slice(&bytes)
        .unwrap_or_else(|_| panic!("{path}: {}", String::from_utf8_lossy(&bytes)));
    keep(path, status, &answer);
    let method = path.trim_start_matches("/xrpc/").split('?').next().unwrap();
    if status == StatusCode::OK {
        OUTPUTS
            .validate(&format!("{method}#output"), &answer)
            .unwrap_or_else(|e| panic!("{path}: {e}: {answer}"));
    } else {
        let (Some(error), Some(_)) = (answer["error"].as_str(), answer["message"].as_str()) else {
            panic!("{path}: a failure is {{error, message}}: {answer}");
        };
        let declared: Vec<&str> = OUTPUTS
            .def(method)
            .and_then(|d| d["errors"].as_array())
            .into_iter()
            .flatten()
            .filter_map(|e| e["name"].as_str())
            .collect();
        assert!(
            declared.contains(&error) || error == "MethodNotImplemented",
            "{path}: {error} is not one of {declared:?}"
        );
    }
    (status, headers, answer)
}

fn get<'a>(hud: &'a Arc<Hud>, who: As<'a>) -> impl AsyncFn(&str) -> (StatusCode, Json) + 'a {
    async move |path: &str| ask(hud, &format!("/xrpc/{NS}{path}"), who, None).await
}

fn post<'a>(hud: &'a Arc<Hud>, who: As<'a>) -> impl AsyncFn(&str, Json) -> (StatusCode, Json) + 'a {
    async move |m: &str, body: Json| ask(hud, &format!("/xrpc/{NS}{m}"), who, Some(body)).await
}

/// A failure's status and error.
fn failed(got: (StatusCode, Json)) -> (StatusCode, String) {
    (
        got.0,
        got.1["error"].as_str().unwrap_or_default().to_string(),
    )
}

const OK: StatusCode = StatusCode::OK;

fn err(status: StatusCode, error: &str) -> (StatusCode, String) {
    (status, error.to_string())
}

#[tokio::test]
async fn signed_in_by_cookie_or_token() {
    let (hud, _) = server(None).await;
    let (cookie, token) = sessions(&hud, ALICE, "alice.test");
    // Signed out, every method asks for sign-in, but anyone's: a
    // sign-in's own suggestions and the playground's.
    let anyones = [
        "place.hud.searchActors",
        "place.hud.getPlayground",
        "place.hud.previewView",
    ];
    for doc in hud_core::lexicon::all_bundled() {
        let Some(id) = doc["id"]
            .as_str()
            .filter(|id| id.starts_with(NS) && !anyones.contains(id))
        else {
            continue;
        };
        let body = match doc["defs"]["main"]["type"].as_str() {
            Some("procedure") => Some(json!({})),
            Some("query") => None,
            _ => continue,
        };
        for who in [
            As::Nobody,
            As::Bearer("not-a-token"),
            As::Page("not-a-cookie"),
        ] {
            let got = ask(&hud, &format!("/xrpc/{id}"), who, body.clone()).await;
            assert_eq!(
                failed(got),
                err(StatusCode::UNAUTHORIZED, "AuthRequired"),
                "{id}"
            );
        }
    }
    // An MCP access token is no cookie, nor a cookie a token.
    let page = get(&hud, As::Page(&token));
    assert_eq!(
        failed(page("getWorkspace").await).0,
        StatusCode::UNAUTHORIZED
    );
    let r = crate::router(hud.clone(), None)
        .oneshot(request(
            &format!("/xrpc/{NS}getWorkspace"),
            As::Bearer(&cookie),
            None,
        ))
        .await
        .unwrap();
    assert_eq!(r.status(), StatusCode::UNAUTHORIZED);
    assert_eq!(r.headers()[header::WWW_AUTHENTICATE], "Bearer");
    // Either works.
    let (status, ws) = get(&hud, As::Page(&cookie))("getWorkspace").await;
    assert_eq!(status, OK);
    assert_eq!(ws["me"], json!({ "did": ALICE, "handle": "alice.test" }));
    // What the New tile offers beside collections: the bundled views'
    // launchers, by app, made the person's.
    let mine = ws["launchers"]
        .as_array()
        .unwrap()
        .iter()
        .find(|l| l["title"] == "Repositories")
        .unwrap();
    assert_eq!(
        mine,
        &json!({ "app": "knotless", "domain": "knotless.dev", "title": "Repositories",
                 "method": "dev.knotless.getActorRepos", "service": "did:web:knotless.dev#knotless_appview",
                 "params": { "actor": ALICE } })
    );
    // The other accounts the page's browser is signed in to: none here, and
    // none ever for a token, which is no browser's.
    assert_eq!(ws["accounts"], json!([]));
    let (status, same) = get(&hud, As::Bearer(&token))("getWorkspace").await;
    let mut by_page = ws.clone();
    by_page.as_object_mut().unwrap().remove("accounts");
    assert_eq!((status, &same), (OK, &by_page));
    // A procedure by cookie is the page's alone; a token needs none of it.
    let made = json!({ "name": "Coast trip" });
    assert_eq!(
        failed(post(&hud, As::Cookie(&cookie))("createCanvas", made.clone()).await),
        err(StatusCode::FORBIDDEN, "InvalidRequest")
    );
    let other = crate::router(hud.clone(), None)
        .oneshot(
            Request::post(format!("/xrpc/{NS}createCanvas"))
                .header("cookie", format!("{COOKIE}={cookie}"))
                .header("x-hud", "1")
                .header("origin", "https://evil.example")
                .body(Body::from(made.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(other.status(), StatusCode::FORBIDDEN);
    let (status, trip) = post(&hud, As::Bearer(&token))("createCanvas", made.clone()).await;
    assert_eq!(
        (status, &trip["canvas"]["record"]["name"]),
        (OK, &json!("Coast trip"))
    );
    // The verb each method is called by; no other method; nothing the
    // lexicon does not take; input as it says.
    let r = crate::router(hud.clone(), None)
        .oneshot(request(
            &format!("/xrpc/{NS}createCanvas"),
            As::Page(&cookie),
            None,
        ))
        .await
        .unwrap();
    assert_eq!(r.status(), StatusCode::METHOD_NOT_ALLOWED);
    for path in [
        format!("/xrpc/{NS}nothing"),
        "/xrpc/app.bsky.feed.getTimeline".into(),
    ] {
        let got = ask(&hud, &path, As::Page(&cookie), None).await;
        assert_eq!(
            failed(got),
            err(StatusCode::NOT_IMPLEMENTED, "MethodNotImplemented")
        );
    }
    let p = post(&hud, As::Page(&cookie));
    for bad in [
        json!({ "name": "x", "colour": "red" }),
        json!({ "name": 3 }),
        json!({}),
        json!({ "name": "" }),
        json!({ "name": "n".repeat(81) }),
    ] {
        assert_eq!(
            failed(p("createCanvas", bad.clone()).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{bad}"
        );
    }
    let g = get(&hud, As::Page(&cookie));
    assert_eq!(
        failed(g("listCanvases?limit=1&colour=red").await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(g("listCanvases?limit=0").await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    let big = json!({ "name": "y".repeat(MAX_BODY) });
    assert_eq!(
        failed(p("createCanvas", big).await).0,
        StatusCode::PAYLOAD_TOO_LARGE
    );
    let not_object = crate::router(hud.clone(), None)
        .oneshot(
            Request::post(format!("/xrpc/{NS}createCanvas"))
                .header("authorization", format!("Bearer {token}"))
                .body(Body::from("[1]"))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(not_object.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn sign_in_suggestions_and_other_accounts() {
    let (hud, asked_double) = server(None).await;
    // Suggestions are anyone's, whatever the request says of a session:
    // under two letters, none, the typeahead service not asked.
    for (q, who) in [
        ("a", As::Nobody),
        ("%40a", As::Bearer("not-a-token")),
        ("%20b%20", As::Page("not-a-cookie")),
    ] {
        let path = format!("/xrpc/{NS}searchActors?q={q}&limit=3");
        assert_eq!(
            ask(&hud, &path, who, None).await,
            (OK, json!({ "actors": [] })),
            "{q}"
        );
    }
    assert!(asked_double.lock().unwrap().asked.is_empty());
    // The page's other accounts, those of its cookies still live, the one
    // used last first; never the one in use.
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    let (carol, carol_token) = sessions(&hud, CAROL, "carol.test");
    let path = format!("/xrpc/{NS}getWorkspace");
    let jar = format!("{COOKIE}={alice}; hud_accounts={carol}~gone~{alice}~{bob}");
    let req = Request::get(&path)
        .header("cookie", jar)
        .body(Body::empty())
        .unwrap();
    let (status, ws) = asked(&hud, &path, req).await;
    assert_eq!(status, OK);
    assert_eq!(ws["me"]["did"], ALICE);
    assert_eq!(
        ws["accounts"],
        json!([
            { "did": CAROL, "handle": "carol.test" },
            { "did": BOB, "handle": "bob.test" },
        ])
    );
    let (_, ws) = ask(&hud, &path, As::Bearer(&carol_token), None).await;
    assert!(ws.get("accounts").is_none());
}

#[tokio::test]
async fn canvases_and_tabs() {
    let (hud, _) = server(None).await;
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    let (g, p) = (get(&hud, As::Page(&alice)), post(&hud, As::Page(&alice)));
    // The first use makes "My canvas", open and current.
    let (_, ws) = g("getWorkspace").await;
    let first = ws["current"].as_str().unwrap().to_string();
    assert_eq!(ws["open"][0]["canvas"]["key"], first.as_str());
    assert_eq!(ws["open"][0]["canvas"]["record"]["name"], "My canvas");
    assert_eq!(ws["open"][0]["canvas"]["viewer"]["role"], "owner");
    assert_eq!(
        ws["open"][0]["canvas"]["storage"],
        json!({ "kind": "file" })
    );
    // Made: open last, current.
    let (status, made) = p("createCanvas", json!({ "name": "  Coast   trip " })).await;
    assert_eq!(status, OK);
    let trip = made["canvas"]["key"].as_str().unwrap().to_string();
    assert_eq!(made["canvas"]["record"]["name"], "Coast trip");
    let (_, ws) = g("getWorkspace").await;
    let keys = |ws: &Json| -> Vec<String> {
        ws["open"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["canvas"]["key"].as_str().unwrap().to_string())
            .collect()
    };
    assert_eq!(
        (keys(&ws), ws["current"].clone()),
        (vec![first.clone(), trip.clone()], json!(trip))
    );
    // Renamed by its owner alone.
    let (status, renamed) = p("updateCanvas", json!({ "canvas": trip, "name": "Coast" })).await;
    assert_eq!(
        (status, &renamed["canvas"]["record"]["name"]),
        (OK, &json!("Coast"))
    );
    let bobs = post(&hud, As::Page(&bob));
    assert_eq!(
        failed(bobs("updateCanvas", json!({ "canvas": trip, "name": "Mine" })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    assert_eq!(
        failed(
            p(
                "updateCanvas",
                json!({ "canvas": "0123456789ab", "name": "x" })
            )
            .await
        ),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // Listed a page at a time: owned first, by when made.
    let (_, page) = g("listCanvases?limit=1").await;
    assert_eq!(page["canvases"][0]["key"], first.as_str());
    let cursor = page["cursor"].as_str().unwrap();
    let (_, rest) = g(&format!(
        "listCanvases?limit=1&cursor={}",
        url::form_urlencoded::byte_serialize(cursor.as_bytes()).collect::<String>()
    ))
    .await;
    assert_eq!(rest["canvases"][0]["key"], trip.as_str());
    assert!(rest.get("cursor").is_none());
    // Closed: put away, its neighbour current; listed still; the last
    // open tab is not closed.
    let (status, tabs) = p("closeCanvas", json!({ "canvas": trip })).await;
    assert_eq!(
        (status, keys(&tabs), tabs["current"].clone()),
        (OK, vec![first.clone()], json!(first))
    );
    assert_eq!(
        g("listCanvases").await.1["canvases"]
            .as_array()
            .unwrap()
            .len(),
        2
    );
    assert_eq!(
        failed(p("closeCanvas", json!({ "canvas": first })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(p("closeCanvas", json!({ "canvas": "0123456789ab" })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // Opened again: last, current.
    let (status, opened) = p("openCanvas", json!({ "canvas": trip })).await;
    assert_eq!(
        (status, keys(&opened)),
        (OK, vec![first.clone(), trip.clone()])
    );
    assert_eq!(
        (opened["current"].clone(), opened["canvas"]["key"].clone()),
        (json!(trip), json!(trip))
    );
    assert_eq!(
        failed(p("openCanvas", json!({ "canvas": "0123456789ab" })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    assert_eq!(
        failed(p("openCanvas", json!({ "canvas": "nope" })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    // Reordered.
    let (status, tabs) = p("setTabOrder", json!({ "tabs": [{ "canvas": trip }] })).await;
    assert_eq!(
        (status, keys(&tabs)),
        (OK, vec![trip.clone(), first.clone()])
    );
    for bad in [
        json!({ "tabs": [{ "canvas": trip }, { "canvas": trip }] }),
        json!({ "tabs": [{ "canvas": "0123456789ab" }] }),
        json!({ "tabs": [trip] }),
        json!({ "tabs": [{ "canvas": "not-an-id-12" }] }),
    ] {
        assert_eq!(
            failed(p("setTabOrder", bad.clone()).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{bad}"
        );
    }
    // Deleted by its owner alone: out of the tabs.
    assert_eq!(
        failed(bobs("deleteCanvas", json!({ "canvas": trip })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    let (status, gone) = p("deleteCanvas", json!({ "canvas": trip })).await;
    assert_eq!((status, gone), (OK, json!({})));
    assert_eq!(
        keys(&g("getWorkspace").await.1),
        std::slice::from_ref(&first)
    );
    assert_eq!(
        failed(p("deleteCanvas", json!({ "canvas": trip })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // At most 50 an owner.
    for i in 1..hud_core::canvas::MAX_CANVASES {
        hud.canvases
            .create(
                Who {
                    did: ALICE,
                    handle: None,
                },
                &format!("c{i}"),
                By::Person,
            )
            .await
            .unwrap();
    }
    assert_eq!(
        failed(p("createCanvas", json!({ "name": "One more" })).await),
        err(StatusCode::BAD_REQUEST, "LimitReached")
    );
}

#[tokio::test]
async fn members_invited_and_gone() {
    let (hud, _) = server(None).await;
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    let (p, bobs) = (post(&hud, As::Page(&alice)), post(&hud, As::Page(&bob)));
    let trip = p("createCanvas", json!({ "name": "Coast trip" })).await.1["canvas"]["key"]
        .as_str()
        .unwrap()
        .to_string();
    // Invited by DID (resolved at the double's PLC): a member pending.
    let (status, shared) = p(
        "inviteMember",
        json!({ "canvas": trip, "actor": BOB, "role": "viewer" }),
    )
    .await;
    assert_eq!(status, OK);
    assert_eq!(
        shared["canvas"]["members"][1],
        json!({ "did": BOB, "role": "viewer", "pending": true, "invitedBy": ALICE })
    );
    for (body, want) in [
        (
            json!({ "canvas": trip, "actor": BOB, "role": "viewer" }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": trip, "actor": "nobody.invalid", "role": "editor" }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": trip, "actor": CAROL, "role": "owner" }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": "0123456789ab", "actor": CAROL, "role": "editor" }),
            err(StatusCode::NOT_FOUND, "NotFound"),
        ),
    ] {
        assert_eq!(
            failed(p("inviteMember", body.clone()).await),
            want,
            "{body}"
        );
    }
    assert_eq!(
        failed(
            bobs(
                "inviteMember",
                json!({ "canvas": trip, "actor": CAROL, "role": "viewer" })
            )
            .await
        ),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    // His invitation shows; he sees the canvas, not yet in it.
    let (_, list) = get(&hud, As::Page(&bob))("listCanvases").await;
    let invite = list["canvases"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["key"] == trip.as_str())
        .unwrap()
        .clone();
    assert_eq!(
        invite["viewer"],
        json!({ "role": "viewer", "invitedBy": ALICE })
    );
    let (status, seen) = get(&hud, As::Page(&bob))(&format!("getCanvas?canvas={trip}")).await;
    assert_eq!((status, seen["tiles"].clone()), (OK, json!([])));
    // Declined: no longer a member.
    assert_eq!(
        bobs("declineInvite", json!({ "canvas": trip })).await,
        (OK, json!({}))
    );
    assert_eq!(
        failed(bobs("declineInvite", json!({ "canvas": trip })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // Invited again and opened: accepted, a tab; then he cannot decline.
    p(
        "inviteMember",
        json!({ "canvas": trip, "actor": BOB, "role": "viewer" }),
    )
    .await;
    let (status, opened) = bobs("openCanvas", json!({ "canvas": trip })).await;
    assert_eq!(status, OK);
    assert!(opened["canvas"]["viewer"].get("invitedBy").is_none());
    assert_eq!(
        failed(bobs("declineInvite", json!({ "canvas": trip })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    // Roles: the owner's to give, never their own.
    let (status, made) = p(
        "setMemberRole",
        json!({ "canvas": trip, "did": BOB, "role": "editor" }),
    )
    .await;
    assert_eq!(
        (status, &made["canvas"]["members"][1]["role"]),
        (OK, &json!("editor"))
    );
    for (body, want) in [
        (
            json!({ "canvas": trip, "did": ALICE, "role": "viewer" }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": trip, "did": CAROL, "role": "viewer" }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": "0123456789ab", "did": BOB, "role": "viewer" }),
            err(StatusCode::NOT_FOUND, "NotFound"),
        ),
    ] {
        assert_eq!(
            failed(p("setMemberRole", body.clone()).await),
            want,
            "{body}"
        );
    }
    assert_eq!(
        failed(
            bobs(
                "setMemberRole",
                json!({ "canvas": trip, "did": BOB, "role": "editor" })
            )
            .await
        ),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    // Removing: the owner's; a member leaves themself; the owner never.
    assert_eq!(
        failed(bobs("removeMember", json!({ "canvas": trip, "did": ALICE })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(bobs("removeMember", json!({ "canvas": trip, "did": CAROL })).await),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    assert_eq!(
        failed(p("removeMember", json!({ "canvas": trip, "did": ALICE })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(p("leaveCanvas", json!({ "canvas": trip })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        bobs("leaveCanvas", json!({ "canvas": trip })).await,
        (OK, json!({}))
    );
    assert_eq!(
        failed(bobs("leaveCanvas", json!({ "canvas": trip })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    p(
        "inviteMember",
        json!({ "canvas": trip, "actor": BOB, "role": "viewer" }),
    )
    .await;
    let (status, removed) = p("removeMember", json!({ "canvas": trip, "did": BOB })).await;
    assert_eq!(
        (
            status,
            removed["canvas"]["members"].as_array().unwrap().len()
        ),
        (OK, 1)
    );
    assert_eq!(
        failed(
            p(
                "removeMember",
                json!({ "canvas": "0123456789ab", "did": BOB })
            )
            .await
        ),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // At most 20 members.
    let me = Who {
        did: ALICE,
        handle: None,
    };
    for i in 0..(hud_core::canvas::MAX_MEMBERS - 1) {
        hud.canvases
            .invite(me, &trip, &format!("did:plc:m{i}"), None, Role::Viewer)
            .await
            .unwrap();
    }
    assert_eq!(
        failed(
            p(
                "inviteMember",
                json!({ "canvas": trip, "actor": CAROL, "role": "viewer" })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "LimitReached")
    );
}

#[tokio::test]
async fn the_same_call_written_otherwise_finds_its_tile() {
    let (hud, _) = server(None).await;
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (g, p) = (get(&hud, As::Page(&alice)), post(&hud, As::Page(&alice)));
    let canvas = g("getWorkspace").await.1["current"]
        .as_str()
        .unwrap()
        .to_string();
    let add = async |canvas: &str, tool: &str, arguments: Json| {
        let (status, t) = p(
            "addTile",
            json!({ "canvas": canvas, "tool": tool, "arguments": arguments }),
        )
        .await;
        assert_eq!(status, OK, "{t}");
        t
    };
    let count = async |canvas: &str| {
        g(&format!("getCanvas?canvas={canvas}")).await.1["tiles"]
            .as_array()
            .unwrap()
            .len()
    };
    let service = hud_core::view::for_method("app.bsky.feed.getAuthorFeed")
        .and_then(|v| v.service.clone())
        .unwrap();
    // Kept canonical: keys sorted, empties dropped, handles as DIDs.
    let feed = add(
        &canvas,
        "query",
        json!({ "params": { "filter": "", "actor": "@Alice.test", "cursor": null },
                "method": "app.bsky.feed.getAuthorFeed" }),
    )
    .await;
    assert!(feed.get("existing").is_none(), "{feed}");
    assert_eq!(
        serde_json::to_string(&feed["tile"]["record"]["arguments"]).unwrap(),
        format!(
            r#"{{"method":"app.bsky.feed.getAuthorFeed","params":{{"actor":"{ALICE}"}},"service":"{service}"}}"#
        )
    );
    let key = feed["tile"]["key"].clone();
    // The same by DID, its keys otherwise, naming the service it calls
    // anyway: that tile, none added.
    let again = add(
        &canvas,
        "query",
        json!({ "service": service, "method": "app.bsky.feed.getAuthorFeed",
                "params": { "actor": ALICE }, "view": null }),
    )
    .await;
    assert_eq!(
        (&again["tile"]["key"], &again["existing"]),
        (&key, &json!(true))
    );
    // At-uris: a handle's against its DID's, either way round.
    let thread = add(
        &canvas,
        "query",
        json!({ "method": "app.bsky.feed.getPostThread",
                "params": { "uri": format!("at://{ALICE}/app.bsky.feed.post/3k") } }),
    )
    .await;
    let found = add(
        &canvas,
        "query",
        json!({ "method": "app.bsky.feed.getPostThread",
                "params": { "uri": "at://alice.test/app.bsky.feed.post/3k" } }),
    )
    .await;
    assert_eq!(
        (&found["tile"]["key"], &found["existing"]),
        (&thread["tile"]["key"], &json!(true))
    );
    // A post opened by its at-uri is the thread opened as a query: one tile.
    let opened = add(
        &canvas,
        "get_record",
        json!({ "uri": "at://alice.test/app.bsky.feed.post/3k" }),
    )
    .await;
    assert_eq!(
        (&opened["tile"]["key"], &opened["existing"]),
        (&thread["tile"]["key"], &json!(true))
    );
    let record = add(
        &canvas,
        "get_record",
        json!({ "uri": "at://alice.test/dev.knotless.repo/knotless" }),
    )
    .await;
    assert_eq!(
        record["tile"]["record"]["arguments"]["uri"],
        format!("at://{ALICE}/dev.knotless.repo/knotless")
    );
    let found = add(
        &canvas,
        "get_record",
        json!({ "uri": format!("at://{ALICE}/dev.knotless.repo/knotless") }),
    )
    .await;
    assert_eq!(
        (&found["tile"]["key"], &found["existing"]),
        (&record["tile"]["key"], &json!(true))
    );
    for tool in ["describe_repo", "list_records"] {
        let mut by_handle = json!({ "actor": "alice.test" });
        if tool == "list_records" {
            by_handle["collection"] = json!("app.bsky.feed.post");
        }
        let first = add(&canvas, tool, by_handle.clone()).await;
        let mut by_did = by_handle.clone();
        by_did["actor"] = json!(ALICE);
        let found = add(&canvas, tool, by_did).await;
        assert_eq!(
            (&found["tile"]["key"], &found["existing"]),
            (&first["tile"]["key"], &json!(true)),
            "{tool}"
        );
    }
    // A handle that resolves nowhere: kept as given, never refused.
    let nobody = add(&canvas, "describe_repo", json!({ "actor": "Nobody.test" })).await;
    assert_eq!(
        nobody["tile"]["record"]["arguments"]["actor"],
        "nobody.test"
    );
    // A tile kept before calls were canonical is found all the same.
    let who = hud_core::canvas::Who {
        did: ALICE,
        handle: Some("alice.test"),
    };
    let old = hud
        .canvases
        .apply(
            who,
            &canvas,
            Op::Add {
                tool: "describe_repo".into(),
                arguments: json!({ "actor": "bob.test" }),
                title: None,
                from: None,
                after: None,
                stack: None,
                width: None,
            },
            By::Person,
        )
        .await
        .unwrap();
    let found = add(&canvas, "describe_repo", json!({ "actor": BOB })).await;
    assert_eq!(
        (&found["tile"]["key"], &found["existing"]),
        (&json!(old.id), &json!(true))
    );
    let before = count(&canvas).await;
    assert_eq!(before, 7);
    // On another canvas, the same call is a tile of its own there.
    let other = p("createCanvas", json!({ "name": "Coast trip" })).await.1["canvas"]["key"]
        .as_str()
        .unwrap()
        .to_string();
    let there = add(&other, "describe_repo", json!({ "actor": "alice.test" })).await;
    assert!(there.get("existing").is_none(), "{there}");
    assert_eq!((count(&other).await, count(&canvas).await), (1, before));
}

#[tokio::test]
async fn tiles_placed_by_the_server() {
    let (hud, _) = server(None).await;
    let (alice, token) = sessions(&hud, ALICE, "alice.test");
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    let (g, p) = (get(&hud, As::Page(&alice)), post(&hud, As::Page(&alice)));
    let canvas = g("getWorkspace").await.1["current"]
        .as_str()
        .unwrap()
        .to_string();
    // Each a call of its own: the same call again adds nothing.
    let n = std::cell::Cell::new(0);
    let add = async |extra: Json| {
        n.set(n.get() + 1);
        let params = if n.get() == 1 {
            json!({})
        } else {
            json!({ "limit": n.get() })
        };
        let mut body = json!({ "canvas": canvas, "tool": "query",
            "arguments": { "method": "app.bsky.feed.getTimeline", "params": params } });
        for (k, v) in extra.as_object().unwrap() {
            body[k] = v.clone();
        }
        let (status, t) = p("addTile", body).await;
        assert_eq!(status, OK, "{t}");
        t["tile"]["key"].as_str().unwrap().to_string()
    };
    let order = async || -> Vec<String> {
        g(&format!("getCanvas?canvas={canvas}")).await.1["tiles"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["key"].as_str().unwrap().to_string())
            .collect()
    };
    // Following | A | B, then A's child between A and B.
    let following = add(json!({})).await;
    let a = add(json!({ "from": following })).await;
    let b = add(json!({ "from": following })).await;
    let child = add(json!({ "from": a })).await;
    assert_eq!(
        order().await,
        [&following, &a, &child, &b].map(String::clone)
    );
    // With after, right of that column.
    let next = add(json!({ "after": following })).await;
    assert_eq!(order().await[1], next);
    // The tile as kept: its record, its icon, its title made.
    let (_, c) = g(&format!("getCanvas?canvas={canvas}")).await;
    let t = &c["tiles"][0];
    assert_eq!(
        (
            &t["record"]["title"],
            &t["record"]["width"],
            &t["record"]["by"],
            &t["author"]
        ),
        (
            &json!("Following"),
            &json!("third"),
            &json!("person"),
            &json!(ALICE)
        )
    );
    assert_eq!(t["icon"], format!("{ORIGIN}/icon/bsky.app"));
    assert!(t.get("uri").is_none());
    // Stacked: at most three a column.
    let (status, s) = p(
        "stackTile",
        json!({ "canvas": canvas, "tile": b, "into": a }),
    )
    .await;
    assert_eq!((status, &s["tile"]["record"]["stack"]), (OK, &json!(a)));
    let under = add(json!({ "stack": a })).await;
    assert_eq!(
        order().await,
        [&following, &next, &a, &b, &under, &child].map(String::clone)
    );
    assert_eq!(
        failed(
            p(
                "addTile",
                json!({ "canvas": canvas, "tool": "query", "arguments": {}, "stack": a })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "LimitReached")
    );
    assert_eq!(
        failed(
            p(
                "stackTile",
                json!({ "canvas": canvas, "tile": child, "into": a })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "LimitReached")
    );
    assert_eq!(
        failed(
            p(
                "stackTile",
                json!({ "canvas": canvas, "tile": b, "into": a })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(p("addTile", json!({ "canvas": canvas, "tool": "query", "arguments": {}, "stack": "0000000000ff" })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // A stacked tile's width is its column's head's.
    let (status, w) = p(
        "setTileWidth",
        json!({ "canvas": canvas, "tile": under, "width": "two-thirds" }),
    )
    .await;
    assert_eq!(
        (status, &w["tile"]["key"], &w["tile"]["record"]["width"]),
        (OK, &json!(a), &json!("two-thirds"))
    );
    assert_eq!(
        failed(
            p(
                "setTileWidth",
                json!({ "canvas": canvas, "tile": a, "width": "wide" })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    // Unstacked: right after its column.
    let (status, u) = p("unstackTile", json!({ "canvas": canvas, "tile": under })).await;
    assert_eq!((status, u["tile"]["record"].get("stack")), (OK, None));
    assert_eq!(
        order().await,
        [&following, &next, &a, &b, &under, &child].map(String::clone)
    );
    assert_eq!(
        failed(p("unstackTile", json!({ "canvas": canvas, "tile": under })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    // Placed: a column moves whole.
    let (status, _) = p(
        "placeTile",
        json!({ "canvas": canvas, "tile": a, "before": following }),
    )
    .await;
    assert_eq!(status, OK);
    assert_eq!(
        order().await,
        [&a, &b, &following, &next, &under, &child].map(String::clone)
    );
    for (body, want) in [
        (
            json!({ "canvas": canvas, "tile": a, "before": next, "after": next }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": canvas, "tile": a }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "canvas": canvas, "tile": a, "after": "0000000000ff" }),
            err(StatusCode::NOT_FOUND, "NotFound"),
        ),
        (
            json!({ "canvas": "0123456789ab", "tile": a, "after": next }),
            err(StatusCode::NOT_FOUND, "NotFound"),
        ),
    ] {
        assert_eq!(failed(p("placeTile", body.clone()).await), want, "{body}");
    }
    // Retitled.
    let (status, r) = p(
        "updateTile",
        json!({ "canvas": canvas, "tile": next, "title": "Mine" }),
    )
    .await;
    assert_eq!(
        (status, &r["tile"]["record"]["title"]),
        (OK, &json!("Mine"))
    );
    assert_eq!(
        failed(
            p(
                "updateTile",
                json!({ "canvas": canvas, "tile": "0000000000ff", "title": "x" })
            )
            .await
        ),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // Neither a title nor a call; arguments without their tool; a tool no
    // tile shows.
    for body in [
        json!({ "canvas": canvas, "tile": next }),
        json!({ "canvas": canvas, "tile": next, "arguments": {} }),
        json!({ "canvas": canvas, "tile": next, "tool": "create_record", "arguments": {} }),
        json!({ "canvas": canvas, "tile": next, "tool": "query", "arguments": [] }),
    ] {
        assert_eq!(
            failed(p("updateTile", body.clone()).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{body}"
        );
    }
    // Removed: a head taken off, the next in its stack heads the column.
    assert_eq!(
        p("removeTile", json!({ "canvas": canvas, "tile": a })).await,
        (OK, json!({}))
    );
    assert_eq!(
        order().await,
        [&b, &following, &next, &under, &child].map(String::clone)
    );
    assert_eq!(
        failed(p("removeTile", json!({ "canvas": canvas, "tile": a })).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // A tool no tile shows, or arguments no tile takes.
    for body in [
        json!({ "canvas": canvas, "tool": "create_record", "arguments": {} }),
        json!({ "canvas": canvas, "tool": "query", "arguments": [] }),
        json!({ "canvas": canvas, "tool": "query", "width": "wide" }),
        json!({ "canvas": canvas, "tool": "query", "from": "tile" }),
    ] {
        assert_eq!(
            failed(p("addTile", body.clone()).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{body}"
        );
    }
    // Icons by what a tile shows: a record's collection's app, a query's
    // method's; none for an account.
    let shown = async |tool: &str, arguments: Json| {
        let (_, t) = p(
            "addTile",
            json!({ "canvas": canvas, "tool": tool, "arguments": arguments }),
        )
        .await;
        t["tile"]["icon"].clone()
    };
    assert_eq!(
        shown(
            "get_record",
            json!({ "uri": "at://did:plc:x/site.standard.document/3k" })
        )
        .await,
        json!(format!("{ORIGIN}/icon/standard.site"))
    );
    assert_eq!(
        shown(
            "query",
            json!({ "method": "fm.plyr.getLikes", "params": {} })
        )
        .await,
        json!(format!("{ORIGIN}/icon/plyr.fm"))
    );
    assert_eq!(
        shown("describe_repo", json!({ "actor": "me" })).await,
        Json::Null
    );
    // A viewer changes nothing; one not in it sees nothing.
    let me = Who {
        did: ALICE,
        handle: Some("alice.test"),
    };
    hud.canvases
        .invite(me, &canvas, BOB, Some("bob.test"), Role::Viewer)
        .await
        .unwrap();
    let bobs = post(&hud, As::Page(&bob));
    let bobs_add = json!({ "canvas": canvas, "tool": "describe_repo", "arguments": {} });
    assert_eq!(
        failed(bobs("addTile", bobs_add.clone()).await),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    bobs("openCanvas", json!({ "canvas": canvas })).await;
    assert_eq!(
        failed(bobs("addTile", bobs_add.clone()).await),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    for m in [
        "placeTile",
        "setTileWidth",
        "stackTile",
        "unstackTile",
        "updateTile",
        "removeTile",
    ] {
        let body = json!({ "canvas": canvas, "tile": b, "after": next, "width": "full", "into": next, "title": "x" });
        let declared =
            OUTPUTS.def(&format!("{NS}{m}")).unwrap()["input"]["schema"]["properties"].clone();
        let body: Map<String, Json> = body
            .as_object()
            .unwrap()
            .iter()
            .filter(|(k, _)| declared.get(k.as_str()).is_some())
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();
        assert_eq!(
            failed(bobs(m, Json::Object(body)).await),
            err(StatusCode::FORBIDDEN, "Forbidden"),
            "{m}"
        );
    }
    let (_, carol) = sessions(&hud, CAROL, "carol.test");
    assert_eq!(
        failed(get(&hud, As::Bearer(&carol))(&format!("getCanvas?canvas={canvas}")).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    assert_eq!(
        failed(g("getCanvas?canvas=0123").await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    let _ = token;
}

#[tokio::test]
async fn tools_called_as_the_mcp_endpoint_answers() {
    let (hud, _) = server(None).await;
    let (cookie, token) = sessions(&hud, ALICE, "alice.test");
    let p = post(&hud, As::Page(&cookie));
    let describe =
        json!({ "name": "describe_method", "arguments": { "method": "app.bsky.feed.getFeed" } });
    let (status, called) = p("callTool", describe.clone()).await;
    assert_eq!(status, OK);
    let body = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                       "params": { "name": "describe_method", "arguments": describe["arguments"] } });
    let r = crate::router(hud.clone(), None)
        .oneshot(
            Request::post("/mcp")
                .header("authorization", format!("Bearer {token}"))
                .header("content-type", "application/json")
                .header("accept", "application/json, text/event-stream")
                .header("mcp-protocol-version", "2025-06-18")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    let mcp: Json = serde_json::from_slice(
        &axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap(),
    )
    .unwrap();
    assert_eq!(called["result"], mcp["result"]);
    assert_eq!(
        called["result"]["_meta"]["viewer"],
        json!({ "did": ALICE, "handle": "alice.test" })
    );
    // A tool's error is its result's.
    let (status, broken) = p(
        "callTool",
        json!({ "name": "get_record", "arguments": { "uri": "nope" } }),
    )
    .await;
    assert_eq!((status, &broken["result"]["isError"]), (OK, &json!(true)));
    // Unknown tools, and the canvas's, are not called here.
    for name in ["paint", "canvas_add"] {
        assert_eq!(
            failed(p("callTool", json!({ "name": name, "arguments": {} })).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{name}"
        );
    }
}

/// A view's gates on the kit resolve for each call's own kit: through
/// `callTool`, the kit a Bearer call says, the oldest where it says none,
/// the page's as current as HUD; through `/mcp`, the kit its client
/// capabilities say, the oldest where they say none, a legacy host's as
/// current as HUD (it draws HUD's view).
#[tokio::test]
async fn a_view_gated_on_the_kit_draws_for_each_callers_kit() {
    let (hud, double) = server(None).await;
    let palette = hud_core::theme::builtin("paper").unwrap()["palette"].clone();
    double.lock().unwrap().themes = vec![(
        BOB,
        "3lsand",
        json!({ "$type": "place.hud.theme", "name": "Sand", "colorScheme": "light",
                "palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" }),
    )];
    let (cookie, token) = sessions(&hud, ALICE, "alice.test");
    let said = |word: &str, gate: Json| {
        json!({ "component": "Stack", "props": { "when": { "$kit": gate } }, "children": [
            { "component": "Text", "props": { "value": word } }] })
    };
    let this = format!("={}", env!("CARGO_PKG_VERSION"));
    let oldest = json!({ "component": "Stack", "props": { "unless": { "$kit": ">0.2.0" } },
                         "children": [{ "component": "Text", "props": { "value": "oldest" } }] });
    let view = json!({ "collection": "place.hud.theme", "description": "Themes", "list": {
        "layout": { "component": "Stack", "children": [
            said("nine", json!(">=9.0.0")), said("this", json!(this)), oldest] } } });
    let arguments = json!({ "actor": BOB, "collection": "place.hud.theme", "view": view });
    let words = |result: &Json| -> Vec<String> {
        ["nine", "this", "oldest"]
            .into_iter()
            .filter(|w| {
                result["_meta"]["ui"]
                    .to_string()
                    .contains(&format!("\"{w}\""))
            })
            .map(str::to_string)
            .collect()
    };
    let call = json!({ "name": "list_records", "arguments": arguments });
    let mut ios = call.clone();
    ios["kit"] = json!({ "platform": "ios", "version": "9.0.1" });
    let (status, by_ios) = post(&hud, As::Bearer(&token))("callTool", ios).await;
    assert_eq!(status, OK);
    assert_eq!(words(&by_ios["result"]), ["nine"]);
    // No kit said: the oldest; and nothing marked reaches a client.
    let (_, unsaid) = post(&hud, As::Bearer(&token))("callTool", call.clone()).await;
    assert!(words(&unsaid["result"]).contains(&"oldest".to_string()));
    assert!(!words(&unsaid["result"]).contains(&"nine".to_string()));
    assert!(!unsaid["result"].to_string().contains("$kit"));
    let (_, paged) = post(&hud, As::Page(&cookie))("callTool", call.clone()).await;
    assert!(words(&paged["result"]).contains(&"this".to_string()));
    assert!(!words(&paged["result"]).contains(&"nine".to_string()));
    // Through /mcp.
    let mcp = async |version: &str, meta: Option<Json>| -> Json {
        let mut params = call.clone();
        if let Some(meta) = meta {
            params["_meta"] = meta;
        }
        let body = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": params });
        let r = crate::router(hud.clone(), None)
            .oneshot(
                Request::post("/mcp")
                    .header("authorization", format!("Bearer {token}"))
                    .header("content-type", "application/json")
                    .header("accept", "application/json, text/event-stream")
                    .header("mcp-protocol-version", version)
                    .header("mcp-method", "tools/call")
                    .header("mcp-name", "list_records")
                    .body(Body::from(body.to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        let bytes = axum::body::to_bytes(r.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice::<Json>(&bytes).unwrap()["result"].take()
    };
    let meta = |capabilities: Json| {
        json!({ "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientInfo": { "name": "hud-kit-android", "version": "9.0.0" },
                "io.modelcontextprotocol/clientCapabilities": capabilities })
    };
    let kit =
        json!({ "extensions": { "place.hud/kit": { "platform": "android", "version": "9.0.0" } } });
    assert_eq!(words(&mcp("2026-07-28", Some(meta(kit))).await), ["nine"]);
    let none = mcp("2026-07-28", Some(meta(json!({})))).await;
    assert!(words(&none).contains(&"oldest".to_string()));
    assert!(!words(&none).contains(&"nine".to_string()));
    let legacy = mcp("2025-06-18", None).await;
    assert!(words(&legacy).contains(&"this".to_string()));
    assert!(!words(&legacy).contains(&"nine".to_string()));
}

/// The playground's methods, anyone's: what it starts from; a view's
/// problems, every one, nothing read; a view read afresh, as no one or as
/// the page's account, then drawn again over that answer; and what is
/// refused.
#[tokio::test]
async fn the_playground_draws_a_view() {
    let (hud, double) = server(None).await;
    let palette = hud_core::theme::builtin("paper").unwrap()["palette"].clone();
    double.lock().unwrap().themes = vec![(
        BOB,
        "3lsand",
        json!({ "$type": "place.hud.theme", "name": "Sand", "colorScheme": "light",
                "palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" }),
    )];
    let (status, started) = get(&hud, As::Nobody)("getPlayground").await;
    assert_eq!(status, OK);
    let ids: Vec<&str> = started["views"]
        .as_array()
        .unwrap()
        .iter()
        .map(|v| v["name"].as_str().unwrap())
        .collect();
    assert!(ids.contains(&"standard-document"), "{ids:?}");
    // Each as a view given inline may be, with its app; no app pages.
    assert!(!ids.contains(&"bsky-app"), "{ids:?}");
    let document = started["views"]
        .as_array()
        .unwrap()
        .iter()
        .find(|v| v["name"] == "standard-document")
        .unwrap();
    assert_eq!(document["app"], "standard.site");
    assert!(document["view"].get("app").is_none());
    assert_eq!(
        document["view"]["origins"],
        json!([
            "https://cdn.bsky.app",
            "https://video.bsky.app",
            "https://video.cdn.bsky.app"
        ])
    );
    assert!(hud_core::view::parse(&document["view"], false).is_ok());
    assert_eq!(started["themes"], json!(hud_core::theme::all()));
    assert!(started["catalog"].is_object());
    let view = |path: &str| {
        json!({ "collection": "place.hud.theme", "description": "Themes", "list": {
            "layout": { "component": "Text", "props": { "value": { "$": path } } } } })
    };
    let call = |view: Json| {
        json!({ "tool": "list_records",
                "arguments": { "actor": BOB, "collection": "place.hud.theme", "view": view } })
    };
    let anyone = post(&hud, As::Nobody);
    let (status, read) = anyone("previewView", call(view("records.0.value.name"))).await;
    assert_eq!(status, OK);
    let result = &read["result"];
    assert_eq!(result["isError"], false, "{result}");
    assert!(result["_meta"]["ui"].to_string().contains("Sand"));
    assert!(result["_meta"].get("viewer").is_none());
    // Drawn again over that answer, by another layout.
    let mut again = call(view("records.0.value.colorScheme"));
    again["answer"] = result["structuredContent"].clone();
    let (status, drawn) = anyone("previewView", again.clone()).await;
    assert_eq!(status, OK);
    assert!(drawn["ui"].to_string().contains("light"), "{drawn}");
    assert!(drawn.get("result").is_none());
    // A view that is not valid: its problems, by where, nothing read.
    let mut bad = view("x");
    bad["list"]["layout"]["component"] = json!("Nope");
    let (status, checked) = anyone("previewView", call(bad)).await;
    assert_eq!(status, OK);
    assert_eq!(checked["problems"][0]["at"], "list.layout.component");
    assert!(checked.get("result").is_none());
    // As the page's account, its result says whose.
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (status, mine) = post(&hud, As::Page(&alice))("previewView", call(view("did"))).await;
    assert_eq!(status, OK);
    assert_eq!(mine["result"]["_meta"]["viewer"]["did"], ALICE);
    // A tool's error is its result's.
    let (status, broken) = anyone(
        "previewView",
        json!({ "tool": "get_record", "arguments": { "uri": "nope", "view": view("did") } }),
    )
    .await;
    assert_eq!((status, &broken["result"]["isError"]), (OK, &json!(true)));
    // Signed out, a call that needs an account is the result's error.
    let (_, me) = anyone(
        "previewView",
        json!({ "tool": "list_records", "arguments": { "actor": "me",
                "collection": "place.hud.theme", "view": view("did") } }),
    )
    .await;
    assert_eq!(
        (
            &me["result"]["isError"],
            &me["result"]["content"][0]["text"]
        ),
        (&json!(true), &json!("Sign in to HUD to read this"))
    );
    // Refused: the cookie from another site's page, a tool that draws no
    // view, no view, an answer not of the call, and too much.
    assert_eq!(
        failed(post(&hud, As::Cookie(&alice))("previewView", call(view("did"))).await),
        err(StatusCode::FORBIDDEN, "InvalidRequest")
    );
    let mut other = again.clone();
    other["answer"] = json!({ "response": {} });
    let huge = json!({ "tool": "query", "arguments": { "x": "a".repeat(5 << 20) } });
    for (input, status) in [
        (
            json!({ "tool": "describe_repo", "arguments": { "actor": BOB, "view": view("did") } }),
            StatusCode::BAD_REQUEST,
        ),
        (
            json!({ "tool": "list_records", "arguments": { "actor": BOB } }),
            StatusCode::BAD_REQUEST,
        ),
        (other, StatusCode::BAD_REQUEST),
        (huge, StatusCode::PAYLOAD_TOO_LARGE),
    ] {
        assert_eq!(
            failed(anyone("previewView", input).await),
            err(status, "InvalidRequest")
        );
    }
}

#[tokio::test]
async fn a_theme_chosen_follows_the_person() {
    let (hud, _) = server(None).await;
    let (alice, token) = sessions(&hud, ALICE, "alice.test");
    let (_, bob) = sessions(&hud, BOB, "bob.test");
    let (page, app) = (post(&hud, As::Page(&alice)), get(&hud, As::Bearer(&token)));
    // None chosen: the system's, with every theme to choose from.
    let (status, ws) = get(&hud, As::Page(&alice))("getWorkspace").await;
    assert_eq!((status, ws.get("theme")), (OK, None));
    let keys: Vec<&str> = ws["themes"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|t| t["key"].as_str())
        .collect();
    assert_eq!(keys[..2], ["light", "dark"]);
    assert!(keys.contains(&"paper"), "{keys:?}");
    let events = format!("/xrpc/{NS}getWorkspaceEvents");
    let r = crate::router(hud.clone(), None)
        .oneshot(request(&events, As::Bearer(&token), None))
        .await
        .unwrap();
    let mut stream = r.into_body().into_data_stream();
    next_events(&mut stream).await;
    // Chosen on the page: the app is told, and reads it; Bob's is his own.
    let paper = hud_core::theme::builtin("paper").unwrap().clone();
    assert_eq!(
        page("setTheme", json!({ "key": "paper" })).await,
        (OK, json!({ "theme": paper }))
    );
    let heard = next_events(&mut stream).await;
    assert!(
        heard
            .iter()
            .any(|e| e["$type"] == "place.hud.defs#canvasesEvent"),
        "{heard:?}"
    );
    assert_eq!(app("getWorkspace").await.1["theme"], paper);
    assert_eq!(
        get(&hud, As::Bearer(&bob))("getWorkspace")
            .await
            .1
            .get("theme"),
        None
    );
    // One HUD has not is refused, and what was chosen stays.
    assert_eq!(
        failed(page("setTheme", json!({ "key": "nope" })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(app("getWorkspace").await.1["theme"]["key"], "paper");
    // None: the system's again.
    assert_eq!(page("setTheme", json!({})).await, (OK, json!({})));
    assert_eq!(app("getWorkspace").await.1.get("theme"), None);
}

#[tokio::test]
async fn peoples_themes_listed_checked_and_chosen() {
    let (hud, double) = server(None).await;
    let palette = |key: &str| hud_core::theme::builtin(key).unwrap()["palette"].clone();
    let theme = |name: &str, scheme: &str, palette: Json| {
        json!({ "$type": "place.hud.theme", "name": name, "colorScheme": scheme,
                "palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" })
    };
    let mut faint = palette("paper");
    faint["textFaint"] = json!("#e8e2d4");
    double.lock().unwrap().themes = vec![
        (BOB, "3lsand", theme("Sand", "light", palette("paper"))),
        (BOB, "3lfaint", theme("Faint", "light", faint.clone())),
        (
            CAROL,
            "3lnight",
            theme("Night", "dark", palette("blueprint")),
        ),
    ];
    let (alice, token) = sessions(&hud, ALICE, "alice.test");
    let (g, p) = (get(&hud, As::Page(&alice)), post(&hud, As::Page(&alice)));
    let names = |v: &Json| -> Vec<String> {
        let mut n: Vec<String> = v["themes"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap().to_string())
            .collect();
        n.sort();
        n
    };
    // Bob's, by his handle: the one that reads, by its uri and its maker.
    let sand = format!("at://{BOB}/place.hud.theme/3lsand");
    let (status, bobs) = g("listThemes?actor=bob.test").await;
    assert_eq!((status, names(&bobs)), (OK, vec!["Sand".to_string()]));
    assert_eq!(
        (
            &bobs["themes"][0]["uri"],
            &bobs["themes"][0]["creator"]["did"]
        ),
        (&json!(sand), &json!(BOB))
    );
    // Everyone's, as the relay lists those who have themes.
    let (status, all) = g("listThemes").await;
    assert_eq!(
        (status, names(&all)),
        (OK, vec!["Night".into(), "Sand".into()])
    );
    assert_eq!(
        failed(g("listThemes?actor=nobody.test").await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    // Chosen by its uri: drawn wherever Alice is, as it was then, so Bob's
    // deleting it changes nothing.
    let (status, chosen) = p("setTheme", json!({ "uri": sand })).await;
    assert_eq!(
        (status, &chosen["theme"]["uri"], &chosen["theme"]["name"]),
        (OK, &json!(sand), &json!("Sand"))
    );
    double.lock().unwrap().themes.retain(|t| t.1 != "3lsand");
    let app = get(&hud, As::Bearer(&token));
    assert_eq!(app("getWorkspace").await.1["theme"], chosen["theme"]);
    // What is not a theme that reads is refused, and what was chosen stays.
    for (bad, why) in [
        (
            json!({ "uri": format!("at://{BOB}/place.hud.theme/3lfaint") }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "uri": sand }),
            err(StatusCode::NOT_FOUND, "NotFound"),
        ),
        (
            json!({ "uri": format!("at://{BOB}/app.bsky.feed.post/3lsand") }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
        (
            json!({ "key": "paper", "uri": sand }),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
        ),
    ] {
        assert_eq!(failed(p("setTheme", bad.clone()).await), why, "{bad}");
    }
    assert_eq!(app("getWorkspace").await.1["theme"]["name"], "Sand");
    // A palette's contrast, checked: each text that falls short, by its
    // fields; a colour not as #rrggbb refused.
    let (status, checked) = p("checkTheme", json!({ "palette": faint })).await;
    assert_eq!(status, OK);
    assert!(
        checked["problems"]
            .as_array()
            .unwrap()
            .iter()
            .any(|f| f["text"] == "textFaint" && f["on"] == "background"),
        "{checked}"
    );
    assert_eq!(
        p("checkTheme", json!({ "palette": palette("paper") })).await,
        (OK, json!({ "problems": [] }))
    );
    let mut red = palette("paper");
    red["canvas"] = json!("red");
    assert_eq!(
        failed(p("checkTheme", json!({ "palette": red })).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    // One that falls short, or has no name, is never written.
    for (name, palette) in [("Faint", faint), ("  ", palette("paper"))] {
        assert_eq!(
            failed(
                p(
                    "createTheme",
                    json!({ "name": name, "colorScheme": "light", "palette": palette })
                )
                .await
            ),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{name}"
        );
    }
    // Only a theme is deleted as one.
    assert_eq!(
        failed(
            p(
                "deleteTheme",
                json!({ "uri": format!("at://{ALICE}/app.bsky.feed.post/1") })
            )
            .await
        ),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
}

/// The events a stream sends next, within a moment each: their data, each
/// held to its `$type`.
async fn next_events(
    stream: &mut (impl futures::Stream<Item = Result<axum::body::Bytes, axum::Error>> + Unpin),
) -> Vec<Json> {
    let mut out = Vec::new();
    while let Ok(Some(Ok(bytes))) =
        tokio::time::timeout(Duration::from_millis(300), stream.next()).await
    {
        let text = String::from_utf8(bytes.to_vec()).unwrap();
        for data in text.lines().filter_map(|l| l.strip_prefix("data: ")) {
            let event: Json = serde_json::from_str(data).unwrap();
            let kind = event["$type"].as_str().unwrap();
            OUTPUTS
                .validate(kind, &event)
                .unwrap_or_else(|e| panic!("{kind}: {e}: {event}"));
            out.push(event);
        }
    }
    out
}

#[tokio::test]
async fn one_stream_across_canvases_and_people() {
    let (hud, _) = server(None).await;
    let (alice, token) = sessions(&hud, ALICE, "alice.test");
    let (_, bob) = sessions(&hud, BOB, "bob.test");
    let (ga, pa) = (get(&hud, As::Page(&alice)), post(&hud, As::Page(&alice)));
    let pb = post(&hud, As::Bearer(&bob));
    let mine = ga("getWorkspace").await.1["current"]
        .as_str()
        .unwrap()
        .to_string();
    let trip = pa("createCanvas", json!({ "name": "Coast trip" })).await.1["canvas"]["key"]
        .as_str()
        .unwrap()
        .to_string();
    pa(
        "inviteMember",
        json!({ "canvas": trip, "actor": BOB, "role": "editor" }),
    )
    .await;
    pb("openCanvas", json!({ "canvas": trip })).await;
    let events = format!("/xrpc/{NS}getWorkspaceEvents");
    let open = |asked: Request<Body>| {
        let hud = hud.clone();
        async move {
            let r = crate::router(hud, None).oneshot(asked).await.unwrap();
            assert_eq!(r.status(), OK);
            assert_eq!(r.headers()[header::CONTENT_TYPE], "text/event-stream");
            r.into_body().into_data_stream()
        }
    };
    let mut a = open(request(&events, As::Cookie(&alice), None)).await;
    // Alice's stream opens with who is on each of her tabs.
    let first = next_events(&mut a).await;
    let canvases: Vec<&str> = first
        .iter()
        .filter(|e| e["$type"] == "place.hud.defs#presenceEvent")
        .map(|e| e["canvas"].as_str().unwrap())
        .collect();
    assert!(
        canvases.contains(&mine.as_str()) && canvases.contains(&trip.as_str()),
        "{first:?}"
    );
    // Bob's stream (a token's) comes on the shared canvas: Alice is told.
    let mut b = open(request(&events, As::Bearer(&bob), None)).await;
    next_events(&mut b).await;
    let here = next_events(&mut a).await;
    assert!(
        here.iter().any(|e| e["canvas"] == trip.as_str()
            && e["present"].as_array().unwrap().len() == 2
            && e["by"]["did"] == BOB),
        "{here:?}"
    );
    // An agent's tile on her own canvas: hers alone, as the agent's.
    let mcp = json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "canvas_add",
        "arguments": { "tool": "describe_method", "arguments": { "method": "app.bsky.feed.getFeed" }, "canvas": mine } } });
    let r = crate::router(hud.clone(), None)
        .oneshot(
            Request::post("/mcp")
                .header("authorization", format!("Bearer {token}"))
                .header("content-type", "application/json")
                .header("accept", "application/json, text/event-stream")
                .header("mcp-protocol-version", "2025-06-18")
                .body(Body::from(mcp.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(r.status(), OK);
    let heard = next_events(&mut a).await;
    let added = heard
        .iter()
        .find(|e| e["$type"] == "place.hud.defs#tileEvent")
        .unwrap_or_else(|| panic!("{heard:?}"));
    assert_eq!(
        (
            &added["canvas"],
            &added["op"],
            &added["by"]["kind"],
            &added["by"]["did"]
        ),
        (&json!(mine), &json!("add"), &json!("agent"), &json!(ALICE))
    );
    assert_eq!(added["tile"]["record"]["tool"], "describe_method");
    assert!(next_events(&mut b).await.is_empty(), "not Bob's");
    // Bob's tile on the shared canvas: both hear it, as his.
    let (_, t) = pb(
        "addTile",
        json!({ "canvas": trip, "tool": "describe_repo", "arguments": { "actor": "bob.test" } }),
    )
    .await;
    for s in [&mut a, &mut b] {
        let heard = next_events(s).await;
        assert!(
            heard.iter().any(|e| e["canvas"] == trip.as_str()
                && e["op"] == "add"
                && e["key"] == t["tile"]["key"]
                && e["by"] == json!({ "did": BOB, "handle": "bob.test", "kind": "person" })),
            "{heard:?}"
        );
    }
    // Bob chooses a tab in his tile: the same tile, in its place, drawing
    // the tab's call made canonical, its title made from the call
    // following it; both hear it.
    let service = hud_core::view::for_method("app.bsky.feed.getAuthorFeed")
        .and_then(|v| v.service.clone())
        .unwrap();
    let canonical = json!({ "method": "app.bsky.feed.getAuthorFeed",
        "params": { "actor": BOB }, "service": service });
    let (status, updated) = pb(
        "updateTile",
        json!({ "canvas": trip, "tile": t["tile"]["key"], "tool": "query",
                "arguments": { "params": { "filter": "", "actor": BOB }, "method": "app.bsky.feed.getAuthorFeed" } }),
    )
    .await;
    assert_eq!(status, OK, "{updated}");
    let (was, now) = (&t["tile"]["record"], &updated["tile"]["record"]);
    assert_eq!(updated["tile"]["key"], t["tile"]["key"]);
    assert_eq!(
        (
            &now["order"],
            &now["width"],
            &now["tool"],
            &now["arguments"]
        ),
        (&was["order"], &was["width"], &json!("query"), &canonical)
    );
    assert_eq!(now["title"], "query app.bsky.feed.getAuthorFeed");
    for s in [&mut a, &mut b] {
        let heard = next_events(s).await;
        assert!(
            heard.iter().any(|e| e["canvas"] == trip.as_str()
                && e["op"] == "update"
                && e["key"] == t["tile"]["key"]
                && e["tile"]["record"]["arguments"] == canonical),
            "{heard:?}"
        );
    }
    // Alice puts it away: her stream is told, and leaves it, Bob told who
    // is left; its changes reach her no more.
    pa("closeCanvas", json!({ "canvas": trip })).await;
    let heard = next_events(&mut a).await;
    assert!(
        heard
            .iter()
            .any(|e| e["$type"] == "place.hud.defs#canvasesEvent" && e["canvas"] == trip.as_str()),
        "{heard:?}"
    );
    let left = next_events(&mut b).await;
    assert!(
        left.iter().any(|e| e["canvas"] == trip.as_str()
            && e["present"].as_array().is_some_and(|p| p.len() == 1)
            && e["by"]["did"] == ALICE),
        "{left:?}"
    );
    pb(
        "removeTile",
        json!({ "canvas": trip, "tile": t["tile"]["key"] }),
    )
    .await;
    assert!(
        next_events(&mut b)
            .await
            .iter()
            .any(|e| e["op"] == "remove")
    );
    assert!(
        next_events(&mut a)
            .await
            .iter()
            .all(|e| e["$type"] != "place.hud.defs#tileEvent"),
        "not on her tabs"
    );
    // Opened again: followed again.
    pa("openCanvas", json!({ "canvas": trip })).await;
    next_events(&mut a).await;
    pb(
        "updateTile",
        json!({ "canvas": trip, "tile": added["key"], "title": "x" }),
    )
    .await;
    pb(
        "addTile",
        json!({ "canvas": trip, "tool": "describe_repo", "arguments": {} }),
    )
    .await;
    assert!(
        next_events(&mut a)
            .await
            .iter()
            .any(|e| e["canvas"] == trip.as_str() && e["op"] == "add")
    );
}

#[tokio::test]
async fn a_file_store_from_before_columns_and_tabs() {
    // As HUD kept them before: canvases with tiles at x, y, w, h, by
    // "you" or "agent", and indexes with no tabs.
    let data = std::env::temp_dir().join(format!("hud-xrpc-before-{}", atproto::jose::random(6)));
    let dir = data.join("canvas");
    std::fs::create_dir_all(dir.join("by-did")).unwrap();
    let member = |did: &str, role: &str, joined: bool, by: Option<&str>| {
        let mut m = json!({ "did": did, "handle": format!("{}.test", &did[8..]), "role": role, "joined": joined });
        if let Some(by) = by {
            m["invitedBy"] = json!(by);
        }
        m
    };
    let tile = |id: &str, x: f64, y: f64, w: f64, by: &str, author: &str, from: Option<&str>| {
        let mut t = json!({ "id": id, "tool": "query", "arguments": { "method": "app.bsky.feed.getTimeline", "params": {} },
            "title": id, "x": x, "y": y, "w": w, "h": 560.0, "by": by, "author": author,
            "at": "2026-11-01T10:00:00.000Z" });
        if let Some(f) = from {
            t["from"] = json!(f);
        }
        t
    };
    let canvas = |id: &str, name: &str, owner: &str, members: Json, created: &str, tiles: Json| {
        let doc = json!({ "id": id, "name": name, "owner": owner, "members": members,
            "createdAt": created, "updatedAt": created, "tiles": tiles });
        std::fs::write(dir.join(format!("{id}.json")), doc.to_string()).unwrap();
    };
    canvas(
        "aaaaaaaaaaaa",
        "My canvas",
        ALICE,
        json!([
            member(ALICE, "owner", true, None),
            member(BOB, "editor", true, Some(ALICE))
        ]),
        "2026-10-01T09:00:00.000Z",
        json!([
            tile(
                "00000000000a",
                468.0,
                0.0,
                420.0,
                "agent",
                ALICE,
                Some("00000000000c")
            ),
            tile("00000000000b", 0.0, 600.0, 640.0, "you", BOB, None),
            tile("00000000000c", 0.0, 0.0, 420.0, "you", ALICE, None),
            tile("00000000000d", 936.0, 0.0, 900.0, "you", ALICE, None),
        ]),
    );
    canvas(
        "bbbbbbbbbbbb",
        "Coast trip",
        ALICE,
        json!([member(ALICE, "owner", true, None)]),
        "2026-10-05T09:00:00.000Z",
        json!([]),
    );
    canvas(
        "cccccccccccc",
        "Bob's",
        BOB,
        json!([
            member(BOB, "owner", true, None),
            member(ALICE, "viewer", false, Some(BOB))
        ]),
        "2026-10-03T09:00:00.000Z",
        json!([tile("00000000000e", 0.0, 0.0, 300.0, "you", BOB, None)]),
    );
    let index = |did: &str, canvases: Json, current: &str| {
        std::fs::write(
            dir.join("by-did")
                .join(format!("{}.json", atproto::jose::sha256(did))),
            json!({ "did": did, "canvases": canvases, "current": current }).to_string(),
        )
        .unwrap();
    };
    index(
        ALICE,
        json!(["aaaaaaaaaaaa", "cccccccccccc", "bbbbbbbbbbbb"]),
        "bbbbbbbbbbbb",
    );
    index(BOB, json!(["aaaaaaaaaaaa", "cccccccccccc"]), "cccccccccccc");
    // A canvas from before there were many, moved already.
    std::fs::write(
        dir.join(format!("{}.json.moved", atproto::jose::sha256(ALICE))),
        "{}",
    )
    .unwrap();

    let (hud, _) = server(Some(data.clone())).await;
    let (alice, _) = sessions(&hud, ALICE, "alice.test");
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    // Every canvas each has joined is a tab, by when it was made; the
    // invitation is none.
    let keys = |ws: &Json| -> Vec<String> {
        ws["open"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["canvas"]["key"].as_str().unwrap().to_string())
            .collect()
    };
    let (_, ws) = get(&hud, As::Page(&alice))("getWorkspace").await;
    assert_eq!(
        (keys(&ws), ws["current"].clone()),
        (
            vec!["aaaaaaaaaaaa".into(), "bbbbbbbbbbbb".into()],
            json!("bbbbbbbbbbbb")
        )
    );
    let (_, ws) = get(&hud, As::Page(&bob))("getWorkspace").await;
    assert_eq!(keys(&ws), ["aaaaaaaaaaaa", "cccccccccccc"]);
    // Tiles made columns: rows top to bottom, left to right; widths from
    // pixels; links kept; "you" a person.
    let (_, c) = get(&hud, As::Page(&alice))("getCanvas?canvas=aaaaaaaaaaaa").await;
    let placed: Vec<(String, String, String, String)> = c["tiles"]
        .as_array()
        .unwrap()
        .iter()
        .map(|t| {
            let r = &t["record"];
            (
                t["key"].as_str().unwrap().into(),
                r["order"].as_str().unwrap().into(),
                r["width"].as_str().unwrap().into(),
                r["by"].as_str().unwrap().into(),
            )
        })
        .collect();
    let row = |k: &str, o: &str, w: &str, b: &str| {
        (k.to_string(), o.to_string(), w.to_string(), b.to_string())
    };
    assert_eq!(
        placed,
        [
            row("00000000000c", "1", "third", "person"),
            row("00000000000a", "2", "third", "agent"),
            row("00000000000d", "3", "two-thirds", "person"),
            row("00000000000b", "4", "half", "person"),
        ]
    );
    assert_eq!(c["tiles"][1]["record"]["from"], "00000000000c");
    assert_eq!(c["tiles"][3]["author"], BOB);
    // Written back: the files hold columns now, the indexes tabs.
    let kept: Json =
        serde_json::from_slice(&std::fs::read(dir.join("aaaaaaaaaaaa.json")).unwrap()).unwrap();
    assert!(
        kept["tiles"]
            .as_array()
            .unwrap()
            .iter()
            .all(|t| t.get("x").is_none() && t["order"].is_string())
    );
    let index: Json = serde_json::from_slice(
        &std::fs::read(
            dir.join("by-did")
                .join(format!("{}.json", atproto::jose::sha256(ALICE))),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(index["open"], json!(["aaaaaaaaaaaa", "bbbbbbbbbbbb"]));
    // Read again by a server started over: as it was left.
    let (again, _) = server(Some(data.clone())).await;
    let (alice2, _) = sessions(&again, ALICE, "alice.test");
    let (_, c2) = get(&again, As::Page(&alice2))("getCanvas?canvas=aaaaaaaaaaaa").await;
    assert_eq!(c2["tiles"], c["tiles"]);
    std::fs::remove_dir_all(&data).unwrap();
}

#[tokio::test]
async fn icons_of_apps() {
    let (hud, double) = server(None).await;
    let fetch = |path: &str, etag: Option<&str>| {
        let hud = hud.clone();
        let mut r = Request::get(path.to_string());
        if let Some(e) = etag {
            r = r.header(header::IF_NONE_MATCH, e);
        }
        let r = r.body(Body::empty()).unwrap();
        async move {
            let r = crate::router(hud, None).oneshot(r).await.unwrap();
            let (status, headers) = (r.status(), r.headers().clone());
            let body = axum::body::to_bytes(r.into_body(), usize::MAX)
                .await
                .unwrap();
            (status, headers, body.to_vec())
        }
    };
    let asked = || double.lock().unwrap().asked.clone();
    // A hit: the PNG, kept a week, with an ETag; asked once.
    let (status, h, body) = fetch("/icon/bsky.app", None).await;
    assert_eq!((status, body.as_slice()), (OK, PNG));
    assert_eq!(h[header::CONTENT_TYPE], "image/png");
    assert_eq!(h[header::CACHE_CONTROL], "public, max-age=604800");
    let etag = h[header::ETAG].to_str().unwrap().to_string();
    let (status, _, body) = fetch("/icon/BSKY.app", Some(&etag)).await;
    assert_eq!((status, body.len()), (StatusCode::NOT_MODIFIED, 0));
    assert_eq!(asked(), ["https://bsky.app"]);
    // Misses, kept a day: none asked again.
    for domain in ["gone.app", "big.app", "html.app"] {
        for _ in 0..2 {
            let (status, h, _) = fetch(&format!("/icon/{domain}"), None).await;
            assert_eq!(status, StatusCode::NOT_FOUND, "{domain}");
            assert_eq!(h[header::CACHE_CONTROL], "public, max-age=86400");
        }
    }
    assert_eq!(
        asked(),
        [
            "https://bsky.app",
            "https://gone.app",
            "https://big.app",
            "https://html.app"
        ]
    );
    assert!(hud.config.cache_dir.join("icons/gone.app.miss").exists());
    // No hostname, or an address: refused, never asked.
    for bad in ["127.0.0.1", "nodots", "a%20b.com", "x..y"] {
        assert_eq!(
            fetch(&format!("/icon/{bad}"), None).await.0,
            StatusCode::NOT_FOUND,
            "{bad}"
        );
    }
    assert_eq!(asked().len(), 4);
    // Asking nowhere: none.
    let mut quiet = hud.config.clone();
    quiet.favicons = None;
    quiet.cache_dir = quiet.cache_dir.join("quiet");
    let quiet = Hud::new(quiet).unwrap();
    let r = crate::router(quiet, None)
        .oneshot(Request::get("/icon/plyr.fm").body(Body::empty()).unwrap())
        .await
        .unwrap();
    assert_eq!(r.status(), StatusCode::NOT_FOUND);
    assert_eq!(asked().len(), 4);
    // A service with no answer now: a 502 no one keeps, and nothing kept
    // here either, so the next ask has the icon.
    let (status, h, _) = fetch("/icon/busy.app", None).await;
    assert_eq!(status, StatusCode::BAD_GATEWAY);
    assert_eq!(h[header::CACHE_CONTROL], "no-store");
    let (status, _, body) = fetch("/icon/busy.app", None).await;
    assert_eq!((status, body.as_slice()), (OK, PNG));
    assert_eq!(asked().len(), 6);
}

#[tokio::test]
async fn stopping_ends_the_event_streams() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let (hud, _) = server(None).await;
    let (_, token) = sessions(&hud, ALICE, "alice.test");
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
    let served = tokio::spawn(crate::serve(listener, hud, None, async move {
        let _ = stopped.await;
    }));
    // A page's stream, open.
    let mut page = tokio::net::TcpStream::connect(addr).await.unwrap();
    let asked = format!(
        "GET /xrpc/{NS}getWorkspaceEvents HTTP/1.1\r\nhost: hud.example\r\nauthorization: Bearer {token}\r\n\r\n"
    );
    page.write_all(asked.as_bytes()).await.unwrap();
    let mut head = [0; 64];
    let n = page.read(&mut head).await.unwrap();
    assert!(head[..n].starts_with(b"HTTP/1.1 200 OK"));
    // Stopping: the stream ends, and with it the server, at once, rather
    // than waiting on the page forever, refusing all the while.
    stop.send(()).unwrap();
    tokio::time::timeout(std::time::Duration::from_secs(5), served)
        .await
        .expect("the server stopped")
        .unwrap()
        .unwrap();
    let mut rest = Vec::new();
    page.read_to_end(&mut rest).await.unwrap();
}

#[tokio::test]
async fn images_uploaded_to_the_pds() {
    use hud_core::pds::BLOB_MAX;
    let (hud, double) = server(None).await;
    let pds = hud.config.plc_url.clone();
    let auth = hud.auth().unwrap();
    let cookie = auth.signed_in_offline_at(ALICE, Some("alice.test"), true, &pds);
    let token = auth.signed_in_offline_at(ALICE, Some("alice.test"), false, &pds);
    let path = format!("/xrpc/{NS}uploadBlob");
    let upload = async |who: As<'_>, kind: &str, bytes: &[u8]| {
        asked(&hud, &path, sent(&path, who, Some((kind, bytes.to_vec())))).await
    };
    let jpeg = [b"\xff\xd8\xff\xe0".as_slice(), &[7; 1000]].concat();
    // Signed out, or a page of another site.
    assert_eq!(
        failed(upload(As::Nobody, "image/jpeg", &jpeg).await),
        err(StatusCode::UNAUTHORIZED, "AuthRequired")
    );
    assert_eq!(
        failed(upload(As::Cookie(&cookie), "image/jpeg", &jpeg).await),
        err(StatusCode::FORBIDDEN, "InvalidRequest")
    );
    // Over 2,000,000 bytes.
    let big = [b"\xff\xd8\xff".as_slice(), &vec![0; BLOB_MAX]].concat();
    assert_eq!(
        failed(upload(As::Page(&cookie), "image/jpeg", &big).await),
        err(StatusCode::PAYLOAD_TOO_LARGE, "BlobTooLarge")
    );
    // Not an image, whatever it says; nor an image sent as something else.
    assert_eq!(
        failed(upload(As::Page(&cookie), "image/jpeg", b"<html></html>").await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert_eq!(
        failed(upload(As::Page(&cookie), "text/plain", &jpeg).await),
        err(StatusCode::BAD_REQUEST, "InvalidRequest")
    );
    assert!(double.lock().unwrap().uploads.is_empty());
    // The page's, then an app's: each sent on as the account, the blob
    // answered as the PDS made it.
    let (status, v) = upload(As::Page(&cookie), "image/jpeg", &jpeg).await;
    assert_eq!(status, OK, "{v}");
    let cid = atproto::Cid::of_raw(&jpeg).to_string();
    assert_eq!(
        v,
        json!({ "blob": { "$type": "blob", "ref": { "$link": cid },
                          "mimeType": "image/jpeg", "size": 1004 } })
    );
    let png = [b"\x89PNG\r\n\x1a\n".as_slice(), &[1; 10]].concat();
    let (status, v) = upload(As::Bearer(&token), "image/png", &png).await;
    assert_eq!(status, OK, "{v}");
    assert_eq!(v["blob"]["mimeType"], "image/png");
    let uploads = &double.lock().unwrap().uploads;
    assert_eq!(
        uploads,
        &vec![
            ("image/jpeg".to_string(), jpeg, true),
            ("image/png".to_string(), png, true),
        ]
    );
}

#[tokio::test]
async fn themes_written_deleted_and_paged() {
    let (hud, double) = server(None).await;
    let pds = hud.config.plc_url.clone();
    let token = hud
        .auth()
        .unwrap()
        .signed_in_offline_at(ALICE, Some("alice.test"), false, &pds);
    let (g, p) = (
        get(&hud, As::Bearer(&token)),
        post(&hud, As::Bearer(&token)),
    );
    let palette = hud_core::theme::builtin("paper").unwrap()["palette"].clone();
    // Written to Alice's own repository, and answered as shown.
    let (status, made) = p(
        "createTheme",
        json!({ "name": "Sand", "colorScheme": "light", "palette": palette }),
    )
    .await;
    assert_eq!(status, OK, "{made}");
    let uri = format!("at://{ALICE}/place.hud.theme/3lmade");
    assert_eq!(
        (&made["theme"]["uri"], &made["theme"]["name"]),
        (&json!(uri), &json!("Sand"))
    );
    let (status, gone) = p("deleteTheme", json!({ "uri": uri })).await;
    assert_eq!((status, gone), (OK, json!({})));
    let writes = double.lock().unwrap().writes.clone();
    assert_eq!(
        (&writes[0]["repo"], &writes[0]["record"]["name"]),
        (&json!(ALICE), &json!("Sand"))
    );
    assert_eq!(
        writes[1],
        json!({ "repo": ALICE, "collection": "place.hud.theme", "rkey": "3lmade" })
    );
    // A page of an account's themes, with the cursor to the next.
    let theme = |name: &str| {
        json!({ "$type": "place.hud.theme", "name": name, "colorScheme": "light",
                "palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" })
    };
    double.lock().unwrap().themes =
        vec![(BOB, "3lsand", theme("Sand")), (BOB, "3lsea", theme("Sea"))];
    let (status, page) = g("listThemes?actor=bob.test&limit=1").await;
    assert_eq!(status, OK);
    assert_eq!(
        (page["themes"].as_array().unwrap().len(), &page["cursor"]),
        (1, &json!("more"))
    );
}

#[tokio::test]
async fn what_the_pds_refuses_or_ended() {
    let (hud, double) = server(None).await;
    let pds = hud.config.plc_url.clone();
    let auth = hud.auth().unwrap();
    let at = |path: &str| {
        auth.signed_in_offline_at(ALICE, Some("alice.test"), false, &format!("{pds}{path}"))
    };
    let path = format!("/xrpc/{NS}uploadBlob");
    let jpeg = [b"\xff\xd8\xff\xe0".as_slice(), &[7; 10]].concat();
    let upload = async |token: &str| {
        let image = Some(("image/jpeg", jpeg.clone()));
        asked(&hud, &path, sent(&path, As::Bearer(token), image)).await
    };
    // An image the PDS refuses: the failure is upstream.
    assert_eq!(
        failed(upload(&at("/broken")).await),
        err(StatusCode::BAD_GATEWAY, "UpstreamFailure")
    );
    // A PDS that ended the session, wherever it is met: sign in again,
    // and the HUD session is over too.
    let ended = at("/ended");
    assert_eq!(
        failed(upload(&ended).await),
        err(StatusCode::UNAUTHORIZED, "AuthRequired")
    );
    assert_eq!(
        failed(get(&hud, As::Bearer(&ended))("getWorkspace").await),
        err(StatusCode::UNAUTHORIZED, "AuthRequired")
    );
    let palette = hud_core::theme::builtin("paper").unwrap()["palette"].clone();
    let ended = at("/ended");
    assert_eq!(
        failed(
            post(&hud, As::Bearer(&ended))(
                "createTheme",
                json!({ "name": "Sand", "colorScheme": "light", "palette": palette })
            )
            .await
        ),
        err(StatusCode::UNAUTHORIZED, "AuthRequired")
    );
    let ended = at("/ended");
    let like = format!("at://{ALICE}/app.bsky.feed.like/3lliked");
    assert_eq!(
        failed(
            post(&hud, As::Bearer(&ended))(
                "callTool",
                json!({ "name": "delete_record", "arguments": { "uri": like } })
            )
            .await
        ),
        err(StatusCode::UNAUTHORIZED, "AuthRequired")
    );
    // Refused for want of scope, signed in before HUD asked for what it asks
    // now: the page and the app offer signing in again, the session kept.
    let behind = auth.signed_in_offline_asking(
        ALICE,
        Some("alice.test"),
        false,
        &format!("{pds}/lacking"),
        "atproto",
    );
    assert_eq!(
        failed(upload(&behind).await),
        err(StatusCode::BAD_GATEWAY, "UpstreamFailure")
    );
    let (status, v) = post(&hud, As::Bearer(&behind))(
        "callTool",
        json!({ "name": "delete_record", "arguments": { "uri": like } }),
    )
    .await;
    assert_eq!(status, OK, "{v}");
    assert_eq!(
        v["result"]["content"][0]["text"],
        hud_core::oauth::SIGN_IN_AGAIN
    );
    let d = double.lock().unwrap();
    assert!(d.uploads.is_empty() && d.writes.is_empty());
}

#[tokio::test]
async fn an_account_with_no_handle() {
    let (hud, _) = server(None).await;
    let token = hud.auth().unwrap().signed_in_offline(CAROL, None, false);
    let (g, p) = (
        get(&hud, As::Bearer(&token)),
        post(&hud, As::Bearer(&token)),
    );
    let (status, ws) = g("getWorkspace").await;
    assert_eq!((status, &ws["me"]), (OK, &json!({ "did": CAROL })));
    // A tile given its title keeps it.
    let canvas = ws["current"].as_str().unwrap();
    let (status, t) = p(
        "addTile",
        json!({ "canvas": canvas, "tool": "query", "title": "Mine",
                "arguments": { "method": "app.bsky.feed.getTimeline", "params": {} } }),
    )
    .await;
    assert_eq!(
        (status, &t["tile"]["record"]["title"]),
        (OK, &json!("Mine"))
    );
    // A method named with its def's fragment is none of HUD's.
    assert_eq!(
        failed(g("getWorkspace%23main").await),
        err(StatusCode::NOT_IMPLEMENTED, "MethodNotImplemented")
    );
}

#[tokio::test]
async fn a_stream_ends_with_its_session() {
    let (hud, _) = server(None).await;
    let auth = hud.auth().unwrap();
    let cookie = auth.signed_in_offline(ALICE, Some("alice.test"), true);
    let token = auth.signed_in_offline(BOB, Some("bob.test"), false);
    let events = format!("/xrpc/{NS}getWorkspaceEvents");
    let mut streams = Vec::new();
    for who in [As::Page(&cookie), As::Bearer(&token)] {
        let r = crate::router(hud.clone(), None)
            .oneshot(request(&events, who, None))
            .await
            .unwrap();
        assert_eq!(r.status(), OK);
        let mut stream = r.into_body().into_data_stream();
        next_events(&mut stream).await;
        streams.push(stream);
    }
    // Live a minute and more: each stream goes on, saying it is there.
    tokio::time::pause();
    let start = tokio::time::Instant::now();
    for stream in &mut streams {
        while start.elapsed() < Duration::from_secs(90) {
            let chunk = stream.next().await.unwrap().unwrap();
            assert!(chunk.starts_with(b":"), "only pings");
        }
    }
    // The web session signed out, the app's token revoked: within a
    // minute each stream finds it so, and ends.
    hud.sign_out(&cookie).await;
    hud.revoke(&[("token".into(), token.clone())])
        .await
        .unwrap();
    for mut stream in streams {
        while let Some(chunk) = stream.next().await {
            let text = String::from_utf8(chunk.unwrap().to_vec()).unwrap();
            assert!(text.starts_with(':'), "only pings: {text}");
        }
    }
}

#[tokio::test]
async fn a_persons_data_deleted() {
    let (hud, double) = server(None).await;
    let pds = hud.config.plc_url.clone();
    let auth = hud.auth().unwrap();
    // Alice in two browsers and HUD's app, at the double as her PDS.
    let alice = auth.signed_in_offline_at(ALICE, Some("alice.test"), true, &pds);
    let elsewhere = auth.signed_in_offline_at(ALICE, Some("alice.test"), true, &pds);
    let app = auth.signed_in_offline_app(ALICE, Some("alice.test"), &pds);
    let (bob, _) = sessions(&hud, BOB, "bob.test");
    // Carol in a browser, another MCP client, and HUD's app.
    let (carol, carols_mcp) = sessions(&hud, CAROL, "carol.test");
    let carols_app = auth.signed_in_offline_app(CAROL, Some("carol.test"), "https://pds.invalid");
    let theme = json!({ "$type": "place.hud.theme", "name": "Sand", "colorScheme": "light",
        "palette": hud_core::theme::builtin("paper").unwrap()["palette"].clone(),
        "createdAt": "2026-11-17T00:00:00.000Z" });
    double.lock().unwrap().themes = vec![(ALICE, "3lmine", theme.clone()), (BOB, "3lbobs", theme)];
    let key = |v: &Json| v["canvas"]["key"].as_str().unwrap().to_string();
    let (a, b, c) = (
        post(&hud, As::Page(&alice)),
        post(&hud, As::Page(&bob)),
        post(&hud, As::Page(&carol)),
    );
    // Hers, shared with Bob, who puts a tile there.
    let mine = key(&a("createCanvas", json!({ "name": "Mine" })).await.1);
    a(
        "inviteMember",
        json!({ "canvas": mine, "actor": BOB, "role": "editor" }),
    )
    .await;
    b("openCanvas", json!({ "canvas": mine })).await;
    let tile = |canvas: &str, actor: &str| json!({ "canvas": canvas, "tool": "describe_repo", "arguments": { "actor": actor } });
    assert_eq!(b("addTile", tile(&mine, "bob.test")).await.0, OK);
    // Bob's, which she is in, a tile hers and one his.
    let bobs = key(&b("createCanvas", json!({ "name": "Bob's" })).await.1);
    b(
        "inviteMember",
        json!({ "canvas": bobs, "actor": ALICE, "role": "editor" }),
    )
    .await;
    a("openCanvas", json!({ "canvas": bobs })).await;
    let (status, hers) = a("addTile", tile(&bobs, "alice.test")).await;
    assert_eq!(status, OK, "{hers}");
    assert_eq!(b("addTile", tile(&bobs, "bob.test")).await.0, OK);
    // Carol's, to which she is invited; and a theme chosen.
    let carols = key(&c("createCanvas", json!({ "name": "Carol's" })).await.1);
    c(
        "inviteMember",
        json!({ "canvas": carols, "actor": ALICE, "role": "viewer" }),
    )
    .await;
    a("setTheme", json!({ "key": "paper" })).await;
    // What she has, as the app reads it.
    let (status, data) = get(&hud, As::Bearer(&app))("getAccountData").await;
    assert_eq!(status, OK);
    assert_eq!(
        (&data["did"], &data["canvases"][1]),
        (
            &json!(ALICE),
            &json!({ "canvas": mine, "name": "Mine", "members": 1 })
        )
    );
    assert_eq!(
        (
            data["canvases"].as_array().unwrap().len(),
            &data["shared"],
            &data["invitations"],
            &data["themes"],
            &data["chosenTheme"]
        ),
        (2, &json!(1), &json!(1), &json!(1), &json!(true))
    );
    // Only her own: refused for another's DID, by anyone.
    let path = format!("/xrpc/{NS}deleteAccountData");
    assert_eq!(
        failed(b("deleteAccountData", json!({ "did": ALICE })).await),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    assert_eq!(
        failed(ask(&hud, &path, As::Bearer(&app), Some(json!({ "did": BOB }))).await),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    // Bob listening, as his page does.
    let r = crate::router(hud.clone(), None)
        .oneshot(request(
            &format!("/xrpc/{NS}getWorkspaceEvents"),
            As::Page(&bob),
            None,
        ))
        .await
        .unwrap();
    let mut stream = r.into_body().into_data_stream();
    next_events(&mut stream).await;
    // Deleted from her page, which holds Carol's session too: it goes on
    // as Carol's.
    let req = Request::builder()
        .uri(&path)
        .method("POST")
        .header("cookie", format!("{COOKIE}={alice}; hud_accounts={carol}"))
        .header("x-hud", "1")
        .header("origin", ORIGIN)
        .header("content-type", "application/json")
        .body(Body::from(json!({ "did": ALICE }).to_string()))
        .unwrap();
    let (status, headers, body) = answered(&hud, &path, req).await;
    // Two canvases, a tile, a canvas left, an invitation declined, a
    // theme and the choice of one.
    assert_eq!((status, body), (OK, json!({ "deleted": 7 })));
    let set: Vec<&str> = headers
        .get_all(header::SET_COOKIE)
        .iter()
        .map(|v| v.to_str().unwrap())
        .collect();
    assert!(
        set.iter()
            .any(|c| c.starts_with(&format!("{COOKIE}={carol};"))),
        "{set:?}"
    );
    assert!(
        set.iter().any(|c| c.starts_with("hud_accounts=;")),
        "{set:?}"
    );
    // Every session of hers ended: no cookie or token of hers works.
    for who in [As::Page(&alice), As::Page(&elsewhere), As::Bearer(&app)] {
        assert_eq!(
            failed(get(&hud, who)("getWorkspace").await),
            err(StatusCode::UNAUTHORIZED, "AuthRequired")
        );
    }
    // Hers gone for Bob too; in his, her tile gone and she with it.
    assert_eq!(
        failed(get(&hud, As::Page(&bob))(&format!("getCanvas?canvas={mine}")).await),
        err(StatusCode::NOT_FOUND, "NotFound")
    );
    let (_, seen) = get(&hud, As::Page(&bob))(&format!("getCanvas?canvas={bobs}")).await;
    let tiles = seen["tiles"].as_array().unwrap();
    assert_eq!(tiles.len(), 1);
    assert_ne!(tiles[0]["key"], hers["tile"]["key"]);
    let members = |v: &Json| -> Vec<String> {
        v["canvas"]["members"]
            .as_array()
            .unwrap()
            .iter()
            .map(|m| m["did"].as_str().unwrap().to_string())
            .collect()
    };
    assert_eq!(members(&seen), [BOB]);
    let (_, theirs) = get(&hud, As::Page(&carol))(&format!("getCanvas?canvas={carols}")).await;
    assert_eq!(members(&theirs), [CAROL]);
    // Bob's page was told her tile went.
    let heard = next_events(&mut stream).await;
    assert!(
        heard
            .iter()
            .any(|e| e["$type"] == "place.hud.defs#tileEvent"
                && e["op"] == "remove"
                && e["key"] == hers["tile"]["key"]),
        "{heard:?}"
    );
    // Her theme record deleted as her, nothing else written.
    assert_eq!(
        double.lock().unwrap().writes,
        [json!({ "repo": ALICE, "collection": "place.hud.theme", "rkey": "3lmine" })]
    );
    assert!(!hud.themes.kept(ALICE));
    let index = hud
        .config
        .data_dir
        .join("canvas/by-did")
        .join(format!("{}.json", atproto::jose::sha256(ALICE)));
    assert!(!index.exists(), "{}", index.display());
    // From another MCP client of hers: refused, nothing deleted.
    assert_eq!(
        failed(
            ask(
                &hud,
                &path,
                As::Bearer(&carols_mcp),
                Some(json!({ "did": CAROL }))
            )
            .await
        ),
        err(StatusCode::FORBIDDEN, "Forbidden")
    );
    let (status, _) = get(&hud, As::Page(&carol))(&format!("getCanvas?canvas={carols}")).await;
    assert_eq!(status, OK);
    // From HUD's app: its answer plain, its token over.
    let (status, headers, body) = answered(
        &hud,
        &path,
        request(
            &path,
            As::Bearer(&carols_app),
            Some(&json!({ "did": CAROL })),
        ),
    )
    .await;
    assert_eq!(status, OK, "{body}");
    assert!(headers.get(header::SET_COOKIE).is_none());
    for who in [As::Bearer(&carols_app), As::Page(&carol)] {
        assert_eq!(
            failed(get(&hud, who)("getWorkspace").await),
            err(StatusCode::UNAUTHORIZED, "AuthRequired")
        );
    }
}

#[tokio::test]
async fn a_persons_data_not_all_deleted() {
    let (hud, _) = server(None).await;
    // An account whose repository cannot be reached: its themes neither
    // counted nor deleted.
    let did = "did:web:nowhere.invalid";
    let (cookie, _) = sessions(&hud, did, "nowhere.invalid");
    let a = post(&hud, As::Page(&cookie));
    assert_eq!(a("setTheme", json!({ "key": "paper" })).await.0, OK);
    let (status, data) = get(&hud, As::Page(&cookie))("getAccountData").await;
    assert_eq!(status, OK, "{data}");
    assert_eq!(
        (&data["themes"], &data["chosenTheme"]),
        (&json!(0), &json!(true))
    );
    // Where its choice of theme and its index of canvases are kept,
    // directories, which deleting a file cannot take away.
    let sha = atproto::jose::sha256(did);
    let data_dir = &hud.config.data_dir;
    let choice = data_dir.join("theme").join(format!("{sha}.json"));
    let index = data_dir.join("canvas/by-did").join(format!("{sha}.json"));
    for path in [&choice, &index] {
        let _ = std::fs::remove_file(path);
        std::fs::create_dir_all(path.join("x")).unwrap();
    }
    let (status, body) = a("deleteAccountData", json!({ "did": did })).await;
    assert_eq!(
        (status, &body["error"]),
        (StatusCode::BAD_GATEWAY, &json!("UpstreamFailure"))
    );
    let why = body["message"].as_str().unwrap();
    assert!(
        why.starts_with("Not everything was deleted; ask again to carry on: "),
        "{why}"
    );
    for part in [
        format!("{}: ", index.display()),
        "your themes were not listed: ".to_string(),
        format!("your theme choice: {}: ", choice.display()),
    ] {
        assert!(why.contains(&part), "{part} in {why}");
    }
    // Still signed in, to ask again.
    assert_eq!(get(&hud, As::Page(&cookie))("getWorkspace").await.0, OK);
}

/// `getLogs`: the operators' alone, by token or the page's cookie; the
/// lines kept, as asked; a store that can't be read, said so.
#[tokio::test]
async fn the_operators_read_the_logs() {
    let (hud, _) = server(None).await;
    let (op_cookie, operator) = sessions(&hud, OPERATOR, "operator.test");
    let (cookie, token) = sessions(&hud, ALICE, "alice.test");
    let logs = hud.logs.as_ref().unwrap();
    for line in [
        json!({ "level": "INFO", "message": "request", "trace_id": "t1", "duration_ms": 3 }),
        json!({ "level": "WARN", "message": "outgoing", "trace_id": "t1", "duration_ms": 2000 }),
        json!({ "level": "INFO", "message": "request", "trace_id": "t2", "duration_ms": 1 }),
    ] {
        logs.keep(line.to_string().as_bytes());
    }
    let messages = |got: &Json| -> Vec<String> {
        let lines = got["lines"].as_array().unwrap().iter();
        lines
            .map(|l| l["line"]["message"].as_str().unwrap().to_string())
            .collect()
    };
    let g = get(&hud, As::Bearer(&operator));
    let (status, got) = g("getLogs?trace=t1").await;
    assert_eq!(status, OK);
    assert_eq!(messages(&got), ["request", "outgoing"]);
    let (_, slow) = g("getLogs?minMs=1000").await;
    assert_eq!(messages(&slow), ["outgoing"]);
    let (status, page) = get(&hud, As::Page(&op_cookie))("getLogs?level=warn&limit=5").await;
    assert_eq!(
        (status, messages(&page)),
        (OK, vec!["outgoing".to_string()])
    );
    // Anyone else is refused, whatever they ask.
    for who in [As::Bearer(&token), As::Page(&cookie)] {
        assert_eq!(
            failed(get(&hud, who)("getLogs?level=warn").await),
            err(StatusCode::FORBIDDEN, "Forbidden")
        );
    }
    // Nothing asked, or more than it answers.
    for path in ["getLogs", "getLogs?limit=5", "getLogs?level=warn&limit=501"] {
        assert_eq!(
            failed(g(path).await),
            err(StatusCode::BAD_REQUEST, "InvalidRequest"),
            "{path}"
        );
    }
    // A store that can't be read.
    let db = rusqlite::Connection::open(hud.config.data_dir.join("logs.db")).unwrap();
    db.execute_batch("ALTER TABLE line RENAME TO away").unwrap();
    assert_eq!(
        failed(g("getLogs?level=warn").await),
        err(StatusCode::INTERNAL_SERVER_ERROR, "LogsUnreadable")
    );
    // A server keeping none answers so.
    let none = Failure::from(hud_core::logs::Unread::NotKept);
    assert_eq!(
        (none.status, none.error),
        (StatusCode::NOT_FOUND, "NotFound")
    );
}

/// Each of HUD's methods is logged and counted by its own path; any other
/// path by the route's template.
#[test]
fn methods_are_routes_of_their_own() {
    let named = route("/xrpc/{method}", "/xrpc/place.hud.getCanvas");
    assert_eq!(named, "/xrpc/place.hud.getCanvas");
    for path in [
        "/xrpc/place.hud.nothing",
        "/xrpc/place.hud.canvas",
        "/xrpc/app.bsky.feed.getTimeline",
    ] {
        assert_eq!(route("/xrpc/{method}", path), "/xrpc/{method}", "{path}");
    }
    assert_eq!(
        route("/blob/{did}/{cid}", "/blob/did:plc:a/b"),
        "/blob/{did}/{cid}"
    );
}

/// An instance serving its operator's apps alone (`HUD_WORKSPACE=off`):
/// none of the workspace's methods, nor the playground's, nor its page,
/// the playground or `/`; what an app's own pages call (a composer's
/// pictures, a sign-in's suggestions, what HUD keeps of a person) there
/// still.
#[tokio::test]
async fn an_apps_instance_serves_no_workspace() {
    let (full, _) = server(None).await;
    let mut config = full.config.clone();
    config.workspace = false;
    let hud = Hud::new(config).unwrap();
    let (_, token) = sessions(&hud, ALICE, "alice.test");
    let missing = err(StatusCode::NOT_IMPLEMENTED, "MethodNotImplemented");
    for m in [
        "getWorkspace",
        "listCanvases",
        "listThemes",
        "getPlayground",
    ] {
        assert_eq!(
            failed(get(&hud, As::Bearer(&token))(m).await),
            missing,
            "{m}"
        );
    }
    let preview = post(&hud, As::Nobody)("previewView", json!({})).await;
    assert_eq!(failed(preview), missing);
    let (status, _) = get(&hud, As::Bearer(&token))("getAccountData").await;
    assert_eq!(status, OK);
    for path in ["/workspace", "/playground", "/"] {
        let req = Request::get(path).body(Body::empty()).unwrap();
        let r = crate::router(hud.clone(), None).oneshot(req).await.unwrap();
        assert_eq!(r.status(), StatusCode::NOT_FOUND, "{path}");
    }
    // The workspace served, `/` is it.
    let req = Request::get("/").body(Body::empty()).unwrap();
    let r = crate::router(full, None).oneshot(req).await.unwrap();
    assert_eq!(r.status(), StatusCode::SEE_OTHER);
}