~ 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
955 lines · 36.3 KB Raw History
//! The themes the workspace is drawn in, and each person's choice of one.
//!
//! HUD's own themes are data, `themes/<key>.json` at the workspace's root,
//! each a `place.hud.defs#theme`: light and dark, HUD's own look in that
//! scheme, with no palette, as each platform draws it; and the rest, each a
//! palette drawn over its scheme's look. People make their own as
//! `place.hud.theme` records in their repositories, for anyone to choose,
//! as knotless's `dev.knotless.theme`: written through `create_record` and
//! `delete_record`, listed from their repositories, and everyone's found by
//! the relay `HUD_RELAY` names (`com.atproto.sync.listReposByCollection`).
//! A palette is held to its lexicon and to contrast (`problems`) wherever
//! it comes from: every text reads at 4.5:1 on what it is drawn on. The
//! workspace's page and the iOS app alike read them from the server, so
//! neither keeps a copy.
//!
//! A person's choice is kept as `<HUD_DATA_DIR>/theme/<sha256 of the
//! DID>.json`, mode 0600, written whole, and read as it is asked for: one
//! of HUD's by its key, drawn as it is now; a person's as it was when
//! chosen, so one changed or deleted since leaves the workspace as it was.
//! With none, or a key no longer HUD's, the system's light or dark.

use crate::Hud;
use crate::oauth::Account;
use crate::oauth::store::write_private;
use crate::tools::Refusal;
use crate::uri::AtUri;
use atproto::jose;
use atproto::lexicon::Lexicons;
use serde_json::{Value, json};
use std::path::PathBuf;
use std::sync::LazyLock;
use std::time::Duration;

include!(concat!(env!("OUT_DIR"), "/themes.rs"));

/// The collection people's themes are records of.
pub const COLLECTION: &str = "place.hud.theme";

/// The relay asked for the repositories holding themes, by default.
pub const RELAY: &str = "https://bsky.network";

/// The least contrast a text has on what it is drawn on (WCAG's AA).
const AA: f64 = 4.5;

/// A palette's colours, as `place.hud.defs#palette` names them.
pub const FIELDS: [&str; 21] = [
    "canvas",
    "background",
    "panel",
    "soft",
    "border",
    "borderStrong",
    "text",
    "textMuted",
    "textFaint",
    "primary",
    "onPrimary",
    "accent",
    "accentSoft",
    "success",
    "danger",
    "done",
    "attention",
    "neutral",
    "onSolid",
    "notice",
    "onNotice",
];

/// Each colour of a palette that is text, and what it is drawn on, as the
/// workspace draws them (web/workspace/tokens.css, by the token each is).
const PAIRS: &[(&[&str], &[&str])] = &[
    (
        &["text", "textMuted", "textFaint"],
        &["background", "panel", "soft", "canvas"],
    ),
    (&["accent"], &["background", "accentSoft"]),
    // A row the launcher or the palette picks.
    (&["text", "textMuted"], &["accentSoft"]),
    // A state in a tile, and on its pill.
    (
        &["success", "danger", "done", "neutral", "attention"],
        &["background"],
    ),
    (
        &["onSolid"],
        &["success", "danger", "done", "neutral", "attention"],
    ),
    (&["danger", "success"], &["panel"]),
    // A primary button.
    (&["onPrimary"], &["primary"]),
    // A notice, the toast that says what an agent did, and an agent's badge.
    (&["onNotice", "text"], &["notice"]),
];

/// How long the relay has to answer, and the most of its answer read.
const RELAY_WAIT: Duration = Duration::from_secs(10);
const RELAY_MAX: usize = 1024 * 1024;

/// Of each account in a listing of everyone's, its newest themes, at most.
const EACH: u32 = 10;
/// The most pages of a person's own themes read, 100 each.
const OWN_PAGES: usize = 20;

/// HUD's themes, in the order they are listed: light and dark, then the
/// palettes, light ones first, each by name.
static ALL: LazyLock<Vec<Value>> = LazyLock::new(|| {
    let mut all: Vec<Value> = THEMES
        .iter()
        .map(|(key, text)| {
            // A theme that is not JSON names itself as it fails.
            let doc: Value = serde_json::from_str(text).expect(key);
            assert_eq!(
                doc["key"], *key,
                "themes/{key}.json: its key is not its name"
            );
            doc
        })
        .collect();
    all.sort_by_key(|t| {
        (
            t.get("palette").is_some(),
            t["colorScheme"] == "dark",
            t["name"].as_str().unwrap_or_default().to_string(),
        )
    });
    all
});

/// The lexicons a person's theme is held to.
static RECORD: LazyLock<Lexicons> = LazyLock::new(|| {
    Lexicons::new([COLLECTION, "place.hud.defs"].map(|nsid| {
        (*crate::lexicon::bundled(nsid).expect("place.hud.theme and place.hud.defs are bundled"))
            .clone()
    }))
});

/// HUD's themes, as `place.hud.defs#theme`s, in the order they are listed.
pub fn all() -> &'static [Value] {
    &ALL
}

/// One of HUD's themes, by its key.
pub fn builtin(key: &str) -> Option<&'static Value> {
    ALL.iter().find(|t| t["key"] == key)
}

/// `given`'s colours as a palette: each of `FIELDS`, as `#rrggbb` in lower
/// case, and nothing else; else the first that is not.
pub fn palette(given: &Value) -> Result<Value, String> {
    let mut out = serde_json::Map::new();
    for field in FIELDS {
        let hex = given[field]
            .as_str()
            .filter(|c| {
                c.len() == 7 && c.starts_with('#') && c[1..].bytes().all(|b| b.is_ascii_hexdigit())
            })
            .ok_or_else(|| format!("{field} is not a colour as #rrggbb"))?;
        out.insert(field.into(), hex.to_ascii_lowercase().into());
    }
    Ok(Value::Object(out))
}

/// A colour's relative luminance, as WCAG reckons it.
fn luminance(hex: &str) -> f64 {
    let channel = |i: usize| {
        let c = f64::from(u8::from_str_radix(&hex[i..i + 2], 16).unwrap_or(0)) / 255.0;
        if c <= 0.03928 {
            c / 12.92
        } else {
            ((c + 0.055) / 1.055).powf(2.4)
        }
    };
    0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5)
}

/// How two colours read, one on the other: 1 to 21.
fn ratio(a: &str, b: &str) -> f64 {
    let (x, y) = (luminance(a), luminance(b));
    (x.max(y) + 0.05) / (x.min(y) + 0.05)
}

/// Each text of `palette` (as `palette` gives one) that reads at under
/// 4.5:1 on what it is drawn on, as `place.hud.defs#contrastProblem`s.
pub fn problems(palette: &Value) -> Vec<Value> {
    let colour = |f: &str| palette[f].as_str().unwrap_or("#000000").to_string();
    let mut out = Vec::new();
    for (texts, ons) in PAIRS {
        for text in *texts {
            for on in *ons {
                let r = ratio(&colour(text), &colour(on));
                if r < AA {
                    out.push(json!({ "text": text, "on": on, "ratio": format!("{:.2}", (r * 100.0).floor() / 100.0) }));
                }
            }
        }
    }
    out
}

/// A person's theme as it is shown (`place.hud.defs#theme`): `record`, at
/// `uri`, by `creator` (`{ did, handle? }`), if it is a `place.hud.theme`
/// that reads.
pub fn of_record(uri: &str, creator: Value, record: &Value) -> Option<Value> {
    RECORD.validate(COLLECTION, record).ok()?;
    let name = record["name"]
        .as_str()
        .map(str::trim)
        .filter(|n| !n.is_empty())?;
    let scheme = record["colorScheme"]
        .as_str()
        .filter(|s| *s == "light" || *s == "dark")?;
    let palette = palette(&record["palette"]).ok()?;
    if !problems(&palette).is_empty() {
        return None;
    }
    Some(
        json!({ "uri": uri, "creator": creator, "name": name, "colorScheme": scheme, "palette": palette }),
    )
}

/// Why a theme was not had.
#[derive(Debug)]
pub enum Refused {
    /// Not a theme that reads, or a write refused: what is wrong.
    Invalid(String),
    /// No such record or account.
    NotFound(String),
    /// The person's sign-in at their PDS ended: they sign in again.
    SignIn,
}

/// Each person's choice of theme, on disk.
pub struct Choices {
    dir: PathBuf,
}

impl Choices {
    /// The choices kept under `dir` (`<HUD_DATA_DIR>/theme/`).
    pub fn new(dir: PathBuf) -> Choices {
        Choices { dir }
    }

    fn path(&self, did: &str) -> PathBuf {
        self.dir.join(format!("{}.json", jose::sha256(did)))
    }

    /// Whether a person's choice is kept, whether it still reads or not.
    pub fn kept(&self, did: &str) -> bool {
        self.path(did).exists()
    }

    /// The theme a person chose, as it is drawn: one of HUD's as it is
    /// now, a person's as it was when chosen.
    pub fn get(&self, did: &str) -> Option<Value> {
        let doc: Value = serde_json::from_slice(&std::fs::read(self.path(did)).ok()?).ok()?;
        let theme = &doc["theme"];
        if let Some(key) = theme["key"].as_str() {
            return builtin(key).cloned();
        }
        theme["uri"].as_str()?;
        palette(&theme["palette"]).ok()?;
        Some(theme.clone())
    }

    /// Keep a person's choice: a theme as `get` gives it, or none, the
    /// system's.
    pub fn set(&self, did: &str, theme: Option<&Value>) -> Result<(), String> {
        let path = self.path(did);
        let done = match theme {
            Some(theme) => write_private(
                &path,
                json!({ "did": did, "theme": theme }).to_string().as_bytes(),
            ),
            None => match std::fs::remove_file(&path) {
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
                r => r,
            },
        };
        done.map_err(|e| format!("{}: {e}", path.display()))
    }
}

/// An account as a theme names its creator.
fn creator(did: &str, handle: Option<&str>) -> Value {
    match handle {
        Some(h) => json!({ "did": did, "handle": h }),
        None => json!({ "did": did }),
    }
}

impl Hud {
    /// The theme at `uri`, a person's `place.hud.theme`, read from their
    /// repository now.
    pub async fn person_theme(&self, uri: &str) -> Result<Value, Refused> {
        let u = AtUri::parse(uri).map_err(Refused::Invalid)?;
        if u.collection != COLLECTION || u.rkey.is_empty() {
            return Err(Refused::Invalid(format!("{uri} is not a {COLLECTION}")));
        }
        let who = self
            .resolve_actor(&u.authority)
            .await
            .map_err(Refused::NotFound)?;
        let record = self
            .get_record(&who.pds, &who.did, COLLECTION, &u.rkey)
            .await
            .map_err(Refused::NotFound)?;
        let uri = u.with_did(&who.did);
        of_record(
            &uri,
            creator(&who.did, who.handle.as_deref()),
            &record.value,
        )
        .ok_or_else(|| {
            Refused::Invalid(format!(
                "{uri} is not a {COLLECTION} whose every text reads at 4.5:1"
            ))
        })
    }

    /// People's themes, a page at a time: `actor`'s, at most `limit`, newest
    /// first; or everyone's, at most `limit` accounts', each with its
    /// newest, as the relay lists the repositories holding them. Those that
    /// do not read are left out; an account that cannot be read, passed
    /// over.
    pub async fn list_themes(
        &self,
        actor: Option<&str>,
        limit: u32,
        cursor: Option<&str>,
    ) -> Result<(Vec<Value>, Option<String>), Refused> {
        if let Some(actor) = actor {
            let who = self.resolve_actor(actor).await.map_err(Refused::NotFound)?;
            let (records, next) = self
                .list_records(&who.pds, &who.did, COLLECTION, limit, cursor)
                .await
                .map_err(Refused::NotFound)?;
            let by = creator(&who.did, who.handle.as_deref());
            let themes = records
                .iter()
                .filter_map(|r| of_record(&r.uri, by.clone(), &r.value))
                .collect();
            return Ok((themes, next));
        }
        let Some(relay) = self.config.relay.as_deref() else {
            return Ok((Vec::new(), None));
        };
        let (dids, next) = self.repos_with_themes(relay, limit, cursor).await?;
        let each = dids.iter().map(|did| async move {
            let who = self.resolve_actor(did).await.ok()?;
            let (records, _) = self
                .list_records(&who.pds, &who.did, COLLECTION, EACH, None)
                .await
                .ok()?;
            let by = creator(&who.did, who.handle.as_deref());
            Some(
                records
                    .iter()
                    .filter_map(|r| of_record(&r.uri, by.clone(), &r.value))
                    .collect::<Vec<_>>(),
            )
        });
        let themes = futures::future::join_all(each)
            .await
            .into_iter()
            .flatten()
            .flatten()
            .collect();
        Ok((themes, next))
    }

    /// A page of the repositories the relay says hold themes, by DID.
    async fn repos_with_themes(
        &self,
        relay: &str,
        limit: u32,
        cursor: Option<&str>,
    ) -> Result<(Vec<String>, Option<String>), Refused> {
        let unreachable = || Refused::Invalid("The relay did not list people's themes".into());
        let mut url = url::Url::parse(&format!(
            "{relay}/xrpc/com.atproto.sync.listReposByCollection"
        ))
        .map_err(|_| unreachable())?;
        url.query_pairs_mut()
            .append_pair("collection", COLLECTION)
            .append_pair("limit", &limit.to_string());
        if let Some(c) = cursor {
            url.query_pairs_mut().append_pair("cursor", c);
        }
        let got = self
            .net
            .fetch(&url, RELAY_WAIT, RELAY_MAX)
            .await
            .map_err(|_| unreachable())?;
        let v: Value = serde_json::from_slice(&got.body)
            .ok()
            .filter(|_| got.status == 200)
            .ok_or_else(unreachable)?;
        let dids = v["repos"]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|r| r["did"].as_str())
            .filter(|d| atproto::syntax::is_did(d))
            .map(str::to_string)
            .collect();
        let next = v["cursor"]
            .as_str()
            .filter(|c| !c.is_empty() && c.len() <= 512)
            .map(str::to_string);
        Ok((dids, next))
    }

    /// Write a theme in `account`'s own repository, its palette held to
    /// contrast first: the theme as shown.
    pub async fn create_theme(
        &self,
        account: &Account,
        name: &str,
        scheme: &str,
        given: &Value,
    ) -> Result<Value, Refused> {
        let name = name.trim();
        if name.is_empty() {
            return Err(Refused::Invalid("A theme needs a name".into()));
        }
        if scheme != "light" && scheme != "dark" {
            return Err(Refused::Invalid("A theme is light or dark".into()));
        }
        let palette = palette(given).map_err(Refused::Invalid)?;
        let short = problems(&palette);
        if let Some(p) = short.first() {
            return Err(Refused::Invalid(format!(
                "{} on {} reads at {}:1, under 4.5:1{}",
                p["text"].as_str().unwrap_or_default(),
                p["on"].as_str().unwrap_or_default(),
                p["ratio"].as_str().unwrap_or_default(),
                match short.len() {
                    1 => String::new(),
                    n => format!(", with {} more", n - 1),
                }
            )));
        }
        let record = json!({ "$type": COLLECTION, "name": name, "colorScheme": scheme,
                             "palette": palette, "createdAt": crate::canvas::iso_now() });
        let args = json!({ "collection": COLLECTION, "record": record });
        let made = self
            .create_record_tool(Some(&args), Some(account))
            .await
            .map_err(refused)?;
        let uri = made.structured["uri"].as_str().unwrap_or_default();
        // As `of_record` shows it: the PDS took it only as its lexicon has
        // it, and its name, scheme and palette are checked above.
        let by = creator(&account.did, account.handle.as_deref());
        Ok(
            json!({ "uri": uri, "creator": by, "name": name, "colorScheme": scheme,
                   "palette": palette }),
        )
    }

    /// Delete one of `account`'s own themes.
    pub async fn delete_theme(&self, account: &Account, uri: &str) -> Result<(), Refused> {
        let u = AtUri::parse(uri).map_err(Refused::Invalid)?;
        if u.collection != COLLECTION {
            return Err(Refused::Invalid(format!("{uri} is not a {COLLECTION}")));
        }
        self.delete_record_tool(Some(&json!({ "uri": uri })), Some(account))
            .await
            .map_err(refused)?;
        Ok(())
    }

    /// Every `place.hud.theme` record in a person's own repository, those
    /// that do not read too, as anyone reads them: their URIs.
    pub async fn own_themes(&self, did: &str) -> Result<Vec<String>, Refused> {
        let who = self.resolve_actor(did).await.map_err(Refused::NotFound)?;
        let mut out = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..OWN_PAGES {
            let (records, next) = self
                .list_records(&who.pds, &who.did, COLLECTION, 100, cursor.as_deref())
                .await
                .map_err(Refused::NotFound)?;
            let last = records.is_empty() || next.is_none() || next == cursor;
            out.extend(records.into_iter().map(|r| r.uri));
            if last {
                return Ok(out);
            }
            cursor = next;
        }
        Err(Refused::Invalid(format!(
            "Your repository holds more than {} themes",
            OWN_PAGES * 100
        )))
    }

    /// Delete every theme in `account`'s own repository, each as
    /// `delete_theme` does: how many went, and a line for each that did
    /// not.
    pub async fn forget_themes(&self, account: &Account) -> (usize, Vec<String>) {
        let uris = match self.own_themes(&account.did).await {
            Ok(uris) => uris,
            Err(r) => return (0, vec![format!("your themes were not listed: {}", why(r))]),
        };
        let mut deleted = 0;
        let mut failed = Vec::new();
        for uri in uris {
            match self.delete_theme(account, &uri).await {
                Ok(()) => deleted += 1,
                Err(r) => failed.push(format!("{uri} was not deleted: {}", why(r))),
            }
        }
        (deleted, failed)
    }
}

/// A refusal in a line.
fn why(r: Refused) -> String {
    match r {
        Refused::Invalid(w) | Refused::NotFound(w) => w,
        Refused::SignIn => "your sign-in at your PDS ended: sign in again".into(),
    }
}

/// A write's refusal, as a theme's.
fn refused(r: Refusal) -> Refused {
    match r {
        Refusal::SignIn => Refused::SignIn,
        Refusal::Error(e) => Refused::Invalid(e),
    }
}

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

    fn defs() -> Value {
        (*crate::lexicon::bundled("place.hud.defs").expect("place.hud.defs is bundled")).clone()
    }

    fn keys() -> Vec<&'static str> {
        all().iter().filter_map(|t| t["key"].as_str()).collect()
    }

    #[test]
    fn every_theme_is_as_its_lexicon_says_and_reads() {
        let lexicons = Lexicons::new([defs()]);
        for t in all() {
            let key = t["key"].as_str().unwrap();
            let checked = lexicons.validate("place.hud.defs#theme", t);
            assert_eq!(checked, Ok(()), "themes/{key}.json");
            // Light and dark are HUD's own look; every other theme is a palette.
            assert_eq!(
                t.get("palette").is_none(),
                key == "light" || key == "dark",
                "themes/{key}.json"
            );
            if t.get("palette").is_some() {
                let p = palette(&t["palette"]).expect(key);
                assert_eq!(
                    p, t["palette"],
                    "themes/{key}.json: lower case, nothing more"
                );
                assert_eq!(problems(&p), Vec::<Value>::new(), "themes/{key}.json");
            }
        }
    }

    #[test]
    fn the_lexicon_names_every_theme() {
        let defs = defs();
        let mut named: Vec<&str> = defs["defs"]["theme"]["properties"]["key"]["knownValues"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(Value::as_str)
            .collect();
        named.sort();
        let mut keys = keys();
        keys.sort();
        assert_eq!(named, keys);
        let fields: Vec<&str> = defs["defs"]["palette"]["required"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(Value::as_str)
            .collect();
        assert_eq!(fields, FIELDS);
    }

    #[test]
    fn listed_light_and_dark_first() {
        let keys = keys();
        assert_eq!(keys[..2], ["light", "dark"]);
        let dark = |key: &&str| {
            all()
                .iter()
                .any(|t| t["key"] == *key && t["colorScheme"] == "dark")
        };
        let first_dark = keys[2..].iter().position(dark).unwrap() + 2;
        assert!(keys[first_dark..].iter().all(dark), "{keys:?}");
    }

    fn paper() -> Value {
        builtin("paper").unwrap()["palette"].clone()
    }

    #[test]
    fn a_text_that_does_not_read_is_named() {
        let mut p = paper();
        p["textFaint"] = json!("#E8E2D4");
        let found = problems(&palette(&p).unwrap());
        assert!(
            found
                .iter()
                .any(|f| f["text"] == "textFaint" && f["on"] == "background"),
            "{found:?}"
        );
        assert!(found.iter().all(|f| f["text"] == "textFaint"), "{found:?}");
        p["canvas"] = json!("red");
        assert_eq!(
            palette(&p).unwrap_err(),
            "canvas is not a colour as #rrggbb"
        );
    }

    #[test]
    fn a_persons_theme_is_shown_only_if_it_reads() {
        let uri = "at://did:plc:aaaaaaaaaaaaaaaaaaaaaaaa/place.hud.theme/3lmno";
        let by = json!({ "did": "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa" });
        let mut record = json!({ "$type": COLLECTION, "name": " Sand ", "colorScheme": "light",
            "palette": paper(), "createdAt": "2026-11-17T00:00:00.000Z" });
        let shown = of_record(uri, by.clone(), &record).unwrap();
        assert_eq!(shown["name"], "Sand");
        assert_eq!(shown["uri"], uri);
        let lexicons = Lexicons::new([defs()]);
        lexicons.validate("place.hud.defs#theme", &shown).unwrap();
        record["palette"]["text"] = record["palette"]["background"].clone();
        assert_eq!(of_record(uri, by.clone(), &record), None);
        record["palette"] = paper();
        record["colorScheme"] = json!("sepia");
        assert_eq!(of_record(uri, by.clone(), &record), None);
        record["colorScheme"] = json!("light");
        record["name"] = json!("  ");
        assert_eq!(of_record(uri, by.clone(), &record), None);
        record.as_object_mut().unwrap().remove("name");
        assert_eq!(of_record(uri, by, &record), None);
        // An account with no verified handle is named by its DID alone.
        assert_eq!(creator("did:plc:x", None), json!({ "did": "did:plc:x" }));
    }

    #[test]
    fn a_choice_is_kept_and_taken_back() {
        let dir = std::env::temp_dir().join(format!("hud-theme-{}", jose::random(6)));
        let choices = Choices::new(dir.clone());
        let did = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
        assert_eq!(choices.get(did), None);
        choices.set(did, Some(&json!({ "key": "paper" }))).unwrap();
        assert_eq!(choices.get(did).as_ref(), builtin("paper"));
        // A person's, as it was when chosen.
        let theirs = json!({ "uri": "at://did:plc:bbbbbbbbbbbbbbbbbbbbbbbb/place.hud.theme/3lmno",
            "name": "Sand", "colorScheme": "light", "palette": paper() });
        choices.set(did, Some(&theirs)).unwrap();
        assert_eq!(Choices::new(dir.clone()).get(did), Some(theirs));
        choices.set(did, None).unwrap();
        assert_eq!(choices.get(did), None);
        choices.set(did, None).unwrap();
        // A key no longer HUD's is none.
        choices.set(did, Some(&json!({ "key": "gone" }))).unwrap();
        assert_eq!(choices.get(did), None);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn a_choice_the_disk_refuses_says_where() {
        let file = std::env::temp_dir().join(format!("hud-theme-{}", jose::random(6)));
        std::fs::write(&file, "").unwrap();
        let choices = Choices::new(file.join("theme"));
        let did = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
        let why = choices
            .set(did, Some(&json!({ "key": "paper" })))
            .unwrap_err();
        assert!(
            why.starts_with(&format!("{}: ", choices.path(did).display())),
            "{why}"
        );
        let _ = std::fs::remove_file(file);
    }

    use crate::tests::ALICE;
    use axum::extract::{Path, Query, State};
    use axum::http::StatusCode;
    use axum::response::{IntoResponse, Response};
    use std::collections::HashMap;
    use std::sync::Arc;

    const BOB: &str = "did:plc:bobbobbobbobbobbobbobbobb";
    /// Whose repository pages on and on.
    const CAROL: &str = "did:plc:carolcarolcarolcarolcaro";
    /// Whose themes are deleted, one refused, one past her sign-in.
    const ERIN: &str = "did:plc:erinerinerinerinerinerin";

    /// A theme record named `name`, of `palette`.
    fn theme(name: &str, palette: Value) -> Value {
        json!({ "$type": COLLECTION, "name": name, "colorScheme": "light",
                "palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" })
    }

    /// Why a theme was refused, as written for a test.
    fn why(r: Result<impl std::fmt::Debug, Refused>) -> String {
        format!("{:?}", r.err().unwrap())
    }

    /// A PLC directory, handle resolver, relay and PDS, as one fake: alice
    /// has two themes, one that does not read; bob's PDS cannot be reached;
    /// writes answer as their record's name or key says.
    async fn world(
        State(url): State<String>,
        Path(path): Path<String>,
        Query(q): Query<HashMap<String, String>>,
        body: String,
    ) -> Response {
        let doc = |did: &str, handle: &str, pds: &str| {
            axum::Json(
                json!({ "id": did, "alsoKnownAs": [format!("at://{handle}")],
                "service": [{ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer",
                              "serviceEndpoint": pds }] }),
            )
            .into_response()
        };
        let good = json!({ "uri": format!("at://{ALICE}/{COLLECTION}/good"), "cid": "c1",
                           "value": theme("Sand", paper()) });
        let mut dark = paper();
        dark["text"] = dark["background"].clone();
        let bad = json!({ "uri": format!("at://{ALICE}/{COLLECTION}/bad"), "cid": "c2",
                          "value": theme("Murk", dark) });
        let input: Value = serde_json::from_str(&body).unwrap_or_default();
        let refuse = |status: StatusCode, error: &str| {
            (status, json!({ "error": error }).to_string()).into_response()
        };
        match path.as_str() {
            ALICE => doc(ALICE, "alice.test", &url),
            BOB => doc(BOB, "bob.test", "http://127.0.0.1:1"),
            CAROL | ERIN => doc(&path, "x.test", &url),
            "com.atproto.identity.resolveHandle" => {
                axum::Json(json!({ "did": ALICE })).into_response()
            }
            "com.atproto.sync.listReposByCollection" => match q.get("cursor").map(String::as_str) {
                Some("busy") => StatusCode::BAD_GATEWAY.into_response(),
                _ => axum::Json(json!({ "cursor": "next", "repos": [
                    { "did": ALICE }, { "did": BOB }, { "did": "did:plc:gonegonegonegonegonegone" },
                    { "did": "not a did" },
                ] }))
                .into_response(),
            },
            "com.atproto.repo.listRecords" => match q["repo"].as_str() {
                CAROL => {
                    let cursor = format!("{}x", q.get("cursor").cloned().unwrap_or_default());
                    let record = json!({ "uri": format!("at://{CAROL}/{COLLECTION}/{cursor}"),
                                         "cid": "c5", "value": theme("Sand", paper()) });
                    axum::Json(json!({ "records": [record], "cursor": cursor })).into_response()
                }
                ERIN => {
                    let records: Vec<Value> = ["gone", "kept", "expired"]
                        .iter()
                        .map(|k| {
                            json!({ "uri": format!("at://{ERIN}/{COLLECTION}/{k}"), "cid": "c4",
                                          "value": theme("Sand", paper()) })
                        })
                        .collect();
                    axum::Json(json!({ "records": records })).into_response()
                }
                _ => axum::Json(json!({ "records": [good, bad] })).into_response(),
            },
            "com.atproto.repo.getRecord" => match q["rkey"].as_str() {
                "good" => axum::Json(good).into_response(),
                _ => axum::Json(bad).into_response(),
            },
            "com.atproto.repo.createRecord" => match input["record"]["name"].as_str() {
                Some("Refused") => refuse(StatusCode::BAD_REQUEST, "InvalidRecord"),
                Some("Expired") => refuse(StatusCode::UNAUTHORIZED, "InvalidToken"),
                _ => axum::Json(json!({ "uri": format!("at://{ALICE}/{COLLECTION}/made"),
                                        "cid": "c3" }))
                .into_response(),
            },
            _ => match input["rkey"].as_str() {
                Some("kept") => refuse(StatusCode::BAD_REQUEST, "InvalidSwap"),
                Some("expired") => refuse(StatusCode::UNAUTHORIZED, "InvalidToken"),
                _ => axum::Json(json!({})).into_response(),
            },
        }
    }

    /// A server, signed in as alice, whose PLC directory, handle resolver,
    /// relay and PDS are the fake; and the fake's URL.
    async fn served() -> (Arc<Hud>, crate::oauth::Account, String) {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let app = axum::Router::new()
            .route("/xrpc/{path}", axum::routing::get(world).post(world))
            .route("/{path}", axum::routing::get(world))
            .with_state(url.clone());
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let (mut hud, account) = crate::tests::signed_in(&url, &url);
        let config = &mut Arc::get_mut(&mut hud).unwrap().config;
        config.handle_resolver = Some(url.clone());
        config.relay = Some(url.clone());
        (hud, account, url)
    }

    #[tokio::test]
    async fn peoples_themes_read_from_their_repositories() {
        let (hud, _, url) = served().await;
        let shown = hud
            .person_theme(&format!("at://alice.test/{COLLECTION}/good"))
            .await
            .unwrap();
        assert_eq!(
            shown["creator"],
            json!({ "did": ALICE, "handle": "alice.test" })
        );
        assert_eq!(shown["uri"], format!("at://{ALICE}/{COLLECTION}/good"));
        let bad = format!("at://{ALICE}/{COLLECTION}/bad");
        assert_eq!(
            why(hud.person_theme(&bad).await),
            format!(
                "Invalid({:?})",
                format!("{bad} is not a {COLLECTION} whose every text reads at 4.5:1")
            )
        );
        // Everyone's, as the relay lists them: those that read, of the
        // accounts that can be read.
        let (themes, next) = hud.list_themes(None, 10, Some("c")).await.unwrap();
        let names: Vec<&str> = themes.iter().filter_map(|t| t["name"].as_str()).collect();
        assert_eq!((names, next.as_deref()), (vec!["Sand"], Some("next")));
        // One account's, from its repository.
        let (theirs, _) = hud.list_themes(Some("alice.test"), 10, None).await.unwrap();
        let names: Vec<&str> = theirs.iter().filter_map(|t| t["name"].as_str()).collect();
        assert_eq!(names, ["Sand"]);
        let unlisted = |relay: &str, cursor: Option<&'static str>| {
            let mut hud = crate::tests::hud_with(&url, |_| {});
            Arc::get_mut(&mut hud).unwrap().config.relay = Some(relay.into());
            async move { why(hud.list_themes(None, 10, cursor).await) }
        };
        let refused = r#"Invalid("The relay did not list people's themes")"#;
        assert_eq!(unlisted(&url, Some("busy")).await, refused);
        assert_eq!(unlisted("http://127.0.0.1:1", None).await, refused);
        assert_eq!(unlisted("no relay", None).await, refused);
        // With no relay, none.
        let quiet = crate::tests::hud_with(&url, |_| {});
        assert_eq!(
            quiet.list_themes(None, 10, None).await.unwrap(),
            (Vec::new(), None)
        );
    }

    #[tokio::test]
    async fn themes_written_only_if_they_read() {
        let (hud, account, _) = served().await;
        let create = |name: &'static str, scheme: &'static str, palette: Value| {
            let (hud, account) = (hud.clone(), account.clone());
            async move { why(hud.create_theme(&account, name, scheme, &palette).await) }
        };
        assert_eq!(
            create("Dim", "dim", paper()).await,
            r#"Invalid("A theme is light or dark")"#
        );
        assert_eq!(
            create("  ", "light", paper()).await,
            r#"Invalid("A theme needs a name")"#
        );
        let mut one = paper();
        one["onPrimary"] = one["primary"].clone();
        assert_eq!(
            create("Flat", "light", one).await,
            r#"Invalid("onPrimary on primary reads at 1.00:1, under 4.5:1")"#
        );
        let mut many = paper();
        many["textFaint"] = many["background"].clone();
        let n = problems(&palette(&many).unwrap()).len();
        let faint = create("Faint", "light", many).await;
        assert!(
            faint.ends_with(&format!(", with {} more\")", n - 1)),
            "{faint}"
        );
        // Written, it is shown as anyone would read it.
        let made = hud
            .create_theme(&account, " Sand ", "light", &paper())
            .await
            .unwrap();
        assert_eq!(
            made,
            json!({ "uri": format!("at://{ALICE}/{COLLECTION}/made"),
                    "creator": { "did": ALICE, "handle": "alice.test" },
                    "name": "Sand", "colorScheme": "light", "palette": palette(&paper()).unwrap() })
        );
        assert!(
            create("Refused", "light", paper())
                .await
                .contains("InvalidRecord")
        );
        hud.delete_theme(&account, &format!("at://{ALICE}/{COLLECTION}/made"))
            .await
            .unwrap();
        let post = format!("at://{ALICE}/app.bsky.feed.post/x");
        assert_eq!(
            why(hud.delete_theme(&account, &post).await),
            format!("Invalid({:?})", format!("{post} is not a {COLLECTION}"))
        );
        let kept = hud
            .delete_theme(&account, &format!("at://{ALICE}/{COLLECTION}/kept"))
            .await;
        assert!(why(kept).contains("InvalidSwap"));
        // A sign-in its PDS no longer takes, with none to refresh it: sign in.
        assert_eq!(create("Expired", "light", paper()).await, "SignIn");
    }

    #[tokio::test]
    async fn a_persons_themes_forgotten_as_their_pds_allows() {
        let (hud, _, url) = served().await;
        let auth = hud.auth().unwrap();
        let token = auth.signed_in_offline_at(ERIN, None, false, &url);
        let erin = auth.account(&token).unwrap();
        let (deleted, failed) = hud.forget_themes(&erin).await;
        assert_eq!(deleted, 1);
        let at = |k: &str| format!("at://{ERIN}/{COLLECTION}/{k}");
        assert_eq!(failed.len(), 2, "{failed:?}");
        assert!(
            failed[0].starts_with(&format!("{} was not deleted: ", at("kept")))
                && failed[0].contains("InvalidSwap"),
            "{failed:?}"
        );
        assert_eq!(
            failed[1],
            format!(
                "{} was not deleted: your sign-in at your PDS ended: sign in again",
                at("expired")
            )
        );
        // A repository that cannot be read: its themes not listed.
        let token = auth.signed_in_offline_at(BOB, None, false, &url);
        let (deleted, failed) = hud.forget_themes(&auth.account(&token).unwrap()).await;
        assert_eq!(deleted, 0);
        assert_eq!(failed.len(), 1);
        assert!(
            failed[0].starts_with("your themes were not listed: "),
            "{failed:?}"
        );
        // A repository listing more than HUD reads.
        assert_eq!(
            why(hud.own_themes(CAROL).await),
            r#"Invalid("Your repository holds more than 2000 themes")"#
        );
    }
}