~ 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
1370 lines · 47.4 KB Raw History
//! The workspace's canvases, with sign-in on: each person's own, and those
//! shared with them. A canvas has a name, an owner and members (editors and
//! viewers the owner invited), and tiles, which its members' pages
//! (`/workspace`) draw and any MCP client signed in as a member fills,
//! live. A canvas is a strip of columns, left to right: each column one
//! tile, or a stack of up to three, one above another. A tile names one of
//! HUD's read tools and its arguments, a title, its place (`order`), its
//! column's width and the column it is stacked in, and its author; never
//! its result, which the page calls the tool for.
//!
//! `engine` holds the directory of canvases and who is in which, each
//! person's open tabs, the canvases in use, and sends each change and who
//! is on each canvas to the members' streams. `strip` places tiles on the
//! strip. `store` keeps them, behind the `Store` trait: the server's own
//! files (`FileStore`), or with spaces on, people's own spaces
//! (`space::SpaceStore`). `tools` are the MCP canvas tools.

mod canonical;
mod engine;
pub mod space;
pub mod store;
mod strip;
mod tools;

pub use engine::{Canvases, Cause, Holding, Notice, Refused, Watch, Who};
pub use tools::definitions;

use crate::tools::is_me;
use crate::uri::AtUri;
use atproto::jose;
use serde_json::{Value, json};
use std::time::{SystemTime, UNIX_EPOCH};

/// The tools a tile may show: HUD's read tools.
pub const TOOLS: [&str; 7] = [
    "describe_repo",
    "describe_app",
    "describe_collection",
    "describe_method",
    "list_records",
    "get_record",
    "query",
];
/// The most tiles a canvas holds; the oldest goes past it.
pub const MAX_TILES: usize = 200;
/// The most tiles in one column: its head and those stacked under it.
pub const MAX_STACK: usize = 3;
/// The most of a tile's arguments, as JSON.
pub const ARGUMENTS_MAX: usize = 64 * 1024;
/// The longest title given, in characters.
const TITLE_MAX: usize = 200;
/// The longest title made from a tile's tool and arguments.
const DERIVED_MAX: usize = 60;
/// The longest `order` as text.
const ORDER_MAX: usize = 32;
/// The notices a person's streams may fall behind by before one is ended.
const NOTICES_MAX: usize = 256;
/// The longest canvas name, in characters.
const NAME_MAX: usize = 80;
/// The most canvases one person owns.
pub const MAX_CANVASES: usize = 50;
/// The most members of a canvas, its owner among them.
pub const MAX_MEMBERS: usize = 20;
/// The name of a person's first canvas.
pub const FIRST_NAME: &str = "My canvas";
/// The components a view draws wide things with: a tile drawn with one
/// starts half the strip wide.
const WIDE: [&str; 3] = ["Document", "Gallery", "Covers"];

/// Who made a tile, or a change.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum By {
    /// The person: on their workspace page, or a client of its methods.
    Person,
    /// An MCP client, through the canvas tools.
    Agent,
}

impl By {
    pub fn as_str(self) -> &'static str {
        match self {
            By::Person => "person",
            By::Agent => "agent",
        }
    }

    /// As kept: `you` is a person's, as tiles from before said.
    fn of(s: &str) -> Option<By> {
        match s {
            "person" | "you" => Some(By::Person),
            "agent" => Some(By::Agent),
            _ => None,
        }
    }
}

/// A member's role.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
    /// Everything: renames, deletes, invites and removes members.
    Owner,
    /// Changes the tiles.
    Editor,
    /// Reads alone.
    Viewer,
}

impl Role {
    pub fn as_str(self) -> &'static str {
        match self {
            Role::Owner => "owner",
            Role::Editor => "editor",
            Role::Viewer => "viewer",
        }
    }

    pub fn of(s: &str) -> Option<Role> {
        Some(match s {
            "owner" => Role::Owner,
            "editor" => Role::Editor,
            "viewer" => Role::Viewer,
            _ => return None,
        })
    }

    /// Whether it may change the tiles.
    pub fn edits(self) -> bool {
        self != Role::Viewer
    }
}

/// A column's width: a share of the strip's visible width.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Width {
    Third,
    Half,
    TwoThirds,
    Full,
}

impl Width {
    pub fn as_str(self) -> &'static str {
        match self {
            Width::Third => "third",
            Width::Half => "half",
            Width::TwoThirds => "two-thirds",
            Width::Full => "full",
        }
    }

    pub fn of(s: &str) -> Option<Width> {
        Some(match s {
            "third" => Width::Third,
            "half" => Width::Half,
            "two-thirds" => Width::TwoThirds,
            "full" => Width::Full,
            _ => return None,
        })
    }

    /// The width a tile placed in pixels, before columns, becomes.
    fn of_pixels(w: f64) -> Width {
        if w < 520.0 {
            Width::Third
        } else if w < 760.0 {
            Width::Half
        } else {
            Width::TwoThirds
        }
    }
}

/// A member of a canvas: its owner, or someone it invited, who is in it
/// (`joined`) once they accept or open it.
#[derive(Clone, Debug, PartialEq)]
pub struct Member {
    pub did: String,
    /// Their handle, verified when they were invited, or signed in.
    pub handle: Option<String>,
    pub role: Role,
    pub joined: bool,
    /// Who invited them; none for the owner.
    pub invited_by: Option<String>,
}

impl Member {
    /// As kept in a canvas's file.
    pub fn to_json(&self) -> Value {
        let mut m = json!({
            "did": self.did,
            "role": self.role.as_str(),
            "joined": self.joined,
        });
        if let Some(h) = &self.handle {
            m["handle"] = json!(h);
        }
        if let Some(by) = &self.invited_by {
            m["invitedBy"] = json!(by);
        }
        m
    }

    /// As `place.hud.defs#member`.
    pub fn view(&self) -> Value {
        let mut m = json!({ "did": self.did, "role": self.role.as_str() });
        if !self.joined {
            m["pending"] = json!(true);
        }
        if let Some(h) = &self.handle {
            m["handle"] = json!(h);
        }
        if let Some(by) = &self.invited_by {
            m["invitedBy"] = json!(by);
        }
        m
    }

    fn from_json(v: &Value) -> Option<Member> {
        Some(Member {
            did: v.get("did")?.as_str()?.to_string(),
            handle: v.get("handle").and_then(Value::as_str).map(str::to_string),
            role: Role::of(v.get("role")?.as_str()?)?,
            joined: v.get("joined")?.as_bool()?,
            invited_by: v
                .get("invitedBy")
                .and_then(Value::as_str)
                .map(str::to_string),
        })
    }
}

/// What a canvas is, apart from its tiles.
#[derive(Clone, Debug, PartialEq)]
pub struct CanvasInfo {
    /// 12 hex digits.
    pub id: String,
    /// 1 to 80 characters.
    pub name: String,
    /// The owner's DID; the owner is among the members, as `owner`.
    pub owner: String,
    pub members: Vec<Member>,
    pub created_at: String,
    pub updated_at: String,
}

impl CanvasInfo {
    pub fn to_json(&self) -> Value {
        json!({
            "id": self.id,
            "name": self.name,
            "owner": self.owner,
            "members": self.members.iter().map(Member::to_json).collect::<Vec<_>>(),
            "createdAt": self.created_at,
            "updatedAt": self.updated_at,
        })
    }

    /// Info as `to_json` wrote it; none if it is not one.
    pub(crate) fn from_json(v: &Value) -> Option<CanvasInfo> {
        let text = |k: &str| v.get(k)?.as_str().map(str::to_string);
        let info = CanvasInfo {
            id: text("id").filter(|i| checked_id(i).is_ok())?,
            name: text("name")?,
            owner: text("owner")?,
            members: v
                .get("members")?
                .as_array()?
                .iter()
                .map(Member::from_json)
                .collect::<Option<Vec<_>>>()?,
            created_at: text("createdAt")?,
            updated_at: text("updatedAt")?,
        };
        info.member(&info.owner)?;
        Some(info)
    }

    /// Its info as its `place.hud.canvas` record holds it.
    pub fn record(&self) -> Value {
        json!({ "$type": CANVAS_RECORD, "name": self.name, "createdAt": self.created_at,
                "updatedAt": self.updated_at })
    }

    /// A member, by DID.
    pub fn member(&self, did: &str) -> Option<&Member> {
        self.members.iter().find(|m| m.did == did)
    }

    /// The other members who are in it, as a tool names them: handles
    /// where known, else DIDs.
    pub fn others(&self, did: &str) -> Vec<String> {
        self.members
            .iter()
            .filter(|m| m.did != did && m.joined)
            .map(|m| m.handle.clone().unwrap_or_else(|| m.did.clone()))
            .collect()
    }
}

/// A tile: a read tool's call, drawn as a column of the strip, or in a
/// column's stack.
#[derive(Clone, Debug, PartialEq)]
pub struct Tile {
    /// 12 hex digits.
    pub id: String,
    pub tool: String,
    pub arguments: Value,
    pub title: String,
    /// Its place, ascending: a column head's on the strip, a stacked
    /// tile's within its stack. A move gives the tile moved a number
    /// between its new neighbours', so no other is rewritten.
    pub order: f64,
    /// Its column's width: a head's counts.
    pub width: Width,
    /// The column-head tile it is stacked under; none for a head.
    pub stack: Option<String>,
    /// Who added it: the person, or an agent.
    pub by: By,
    /// The DID of the member it was added as.
    pub author: String,
    /// When it was added, ISO 8601.
    pub at: String,
    /// The tile it was opened from, which the workspace joins it to; that
    /// tile may be gone since.
    pub from: Option<String>,
}

impl Tile {
    /// As kept in a canvas's file.
    pub fn to_json(&self) -> Value {
        let mut v = json!({
            "id": self.id,
            "tool": self.tool,
            "arguments": self.arguments,
            "title": self.title,
            "order": order_text(self.order),
            "width": self.width.as_str(),
            "by": self.by.as_str(),
            "author": self.author,
            "at": self.at,
        });
        if let Some(stack) = &self.stack {
            v["stack"] = json!(stack);
        }
        if let Some(from) = &self.from {
            v["from"] = json!(from);
        }
        v
    }

    /// A tile as `to_json` wrote it; none if it is not one. One kept before
    /// tiles had authors is `default_author`'s; one with a `from` or a
    /// `stack` that is not a tile's id was opened from none, or is a head.
    pub(crate) fn from_json(v: &Value, default_author: &str) -> Option<Tile> {
        let text = |k: &str| v.get(k)?.as_str().map(str::to_string);
        Some(Tile {
            id: text("id")?,
            tool: text("tool")?,
            arguments: v.get("arguments").filter(|a| a.is_object())?.clone(),
            title: text("title")?,
            order: checked_order(&text("order")?).ok()?,
            width: match text("width") {
                Some(w) => Width::of(&w)?,
                None => Width::Third,
            },
            stack: text("stack").and_then(|s| checked_id(&s).ok()),
            by: By::of(v.get("by")?.as_str()?)?,
            author: text("author").unwrap_or_else(|| default_author.to_string()),
            at: text("at")?,
            from: text("from").and_then(|f| checked_id(&f).ok()),
        })
    }

    /// As its `place.hud.tile` record holds it: its arguments as
    /// JSON text where a record cannot hold them.
    pub fn record(&self) -> Value {
        let mut r = json!({
            "$type": TILE_RECORD,
            "tool": self.tool,
            "title": self.title,
            "order": order_text(self.order),
            "width": self.width.as_str(),
            "by": self.by.as_str(),
            "createdAt": self.at,
        });
        if in_data_model(&self.arguments) {
            r["arguments"] = self.arguments.clone();
        } else {
            r["argumentsJson"] = json!(self.arguments.to_string());
        }
        if let Some(stack) = &self.stack {
            r["stack"] = json!(stack);
        }
        if let Some(from) = &self.from {
            r["from"] = json!(from);
        }
        r
    }

    /// A tile from its record, keyed `rkey`, `author`'s; none if it is not
    /// one HUD makes.
    pub(crate) fn from_record(rkey: &str, v: &Value, author: &str) -> Option<Tile> {
        let text = |k: &str| v.get(k)?.as_str().map(str::to_string);
        let arguments = match (v.get("arguments"), text("argumentsJson")) {
            (Some(a), _) => a.clone(),
            (None, Some(j)) if j.len() <= ARGUMENTS_MAX => serde_json::from_str(&j).ok()?,
            _ => return None,
        };
        Some(Tile {
            id: checked_id(rkey).ok().filter(|id| id == rkey)?,
            tool: checked_tool(&text("tool")?).ok()?,
            arguments: checked_arguments(Some(&arguments)).ok()?,
            title: checked_title(&text("title")?).ok()?,
            order: checked_order(&text("order")?).ok()?,
            width: match text("width") {
                Some(w) => Width::of(&w)?,
                None => Width::Third,
            },
            stack: text("stack").and_then(|s| checked_id(&s).ok()),
            by: By::of(&text("by")?)?,
            author: author.to_string(),
            at: text("createdAt")?,
            from: text("from").and_then(|f| checked_id(&f).ok()),
        })
    }

    /// As `place.hud.defs#tileView`: its key, its author, its
    /// record, the record's URI where its canvas is kept in a space
    /// (`space`), and its app's icon from the server at `origin`.
    pub fn view(&self, space: Option<&str>, origin: &str) -> Value {
        let mut v = json!({ "key": self.id, "author": self.author, "record": self.record() });
        if let Some(space) = space {
            v["uri"] = json!(format!("{space}/{}/{TILE_RECORD}/{}", self.author, self.id));
        }
        if let Some(domain) = self.app() {
            v["icon"] = json!(format!("{origin}/icon/{domain}"));
        }
        v
    }

    /// The domain of the app whose data it shows: the app an app's page
    /// names, else the one of the NSID it names, the collection of a record
    /// tile, the method of a query tile.
    pub fn app(&self) -> Option<String> {
        let field = |k: &str| self.arguments.get(k).and_then(Value::as_str);
        let nsid = match self.tool.as_str() {
            "describe_app" => return crate::icons::checked_domain(field("domain")?, true),
            "get_record" => AtUri::parse(field("uri")?).ok()?.collection,
            "list_records" | "describe_collection" => field("collection")?.to_string(),
            "query" | "describe_method" => field("method")?.to_string(),
            _ => return None,
        };
        crate::apps::domain(&nsid)
    }
}

/// A tile's record type (`schemas/place.hud.tile.json`).
pub const TILE_RECORD: &str = "place.hud.tile";
/// A canvas's info's record type (`schemas/place.hud.canvas.json`).
pub const CANVAS_RECORD: &str = "place.hud.canvas";

/// Whether a value is in atproto's data model as JSON writes it: no number
/// that is not an integer, no object a CID or bytes would be read as.
fn in_data_model(v: &Value) -> bool {
    match v {
        Value::Number(n) => n.is_i64() || n.is_u64(),
        Value::Array(items) => items.iter().all(in_data_model),
        Value::Object(map) => {
            !map.contains_key("$link")
                && !map.contains_key("$bytes")
                && map.values().all(in_data_model)
        }
        _ => true,
    }
}

/// A change to a tile, as the streams are told of it: `add`, `update`
/// (its place, width, stack, title or call) or `remove`; the tile as it now
/// is (none once removed), and its id.
#[derive(Clone, Debug, PartialEq)]
pub struct Event {
    pub op: &'static str,
    pub tile: Option<Tile>,
    pub id: String,
}

/// A change asked of a canvas's tiles, checked.
#[derive(Clone, Debug, PartialEq)]
pub enum Op {
    Add {
        tool: String,
        arguments: Value,
        /// Made from the tool and its arguments where none is given.
        title: Option<String>,
        /// The tile it is opened from, by id: it goes after the columns
        /// opened from that one already.
        from: Option<String>,
        /// The column it goes right of, where not opened from a tile.
        after: Option<String>,
        /// A tile whose column it is stacked into, at the end.
        stack: Option<String>,
        /// From what it shows where not given.
        width: Option<Width>,
    },
    Remove {
        id: String,
    },
    /// Put right before or after another tile.
    Place {
        id: String,
        to: Beside,
    },
    Width {
        id: String,
        width: Width,
    },
    Stack {
        id: String,
        into: String,
    },
    Unstack {
        id: String,
    },
    /// Its title, its call (a tool and arguments, made canonical), or both:
    /// the same tile, in the same place, drawing another call, as a tab
    /// chosen in it.
    Update {
        id: String,
        title: Option<String>,
        call: Option<(String, Value)>,
    },
}

/// Where a tile is placed: right before a tile, or right after one.
#[derive(Clone, Debug, PartialEq)]
pub enum Beside {
    Before(String),
    After(String),
}

impl Beside {
    /// One of `before` and `after`, each an id.
    pub fn of(before: Option<&str>, after: Option<&str>) -> Result<Beside, String> {
        match (before, after) {
            (Some(b), None) => Ok(Beside::Before(checked_id(b)?)),
            (None, Some(a)) => Ok(Beside::After(checked_id(a)?)),
            _ => Err("Give one of before and after".into()),
        }
    }
}

/// An `order` as text: a decimal number, shortest as it reads back.
pub fn order_text(order: f64) -> String {
    if order == 0.0 {
        return "0".into();
    }
    format!("{order}")
}

/// An `order` read: a decimal number, at most 32 characters.
pub fn checked_order(s: &str) -> Result<f64, String> {
    let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
    let body = s.strip_prefix('-').unwrap_or(s);
    let ok = s.len() <= ORDER_MAX
        && match body.split_once('.') {
            Some((whole, part)) => digits(whole) && digits(part),
            None => digits(body),
        };
    s.parse::<f64>()
        .ok()
        .filter(|n| ok && n.is_finite())
        .ok_or_else(|| format!("{s} is not an order (a decimal number)"))
}

/// A width given: third, half, twothirds or full.
pub fn checked_width(width: &str) -> Result<Width, String> {
    Width::of(width.trim())
        .ok_or_else(|| format!("{width} is not a width: third, half, twothirds or full"))
}

/// The width a tile's column starts at, from what it shows: half for
/// documents and galleries (drawn by a view with a `Document`, `Gallery` or
/// `Covers`, the one given inline or the bundled one; a record a bundled
/// method view draws as its query, by that view), else a third: feeds,
/// threads, lists.
pub fn default_width(tool: &str, arguments: &Value) -> Width {
    let field = |k: &str| arguments.get(k).and_then(Value::as_str);
    let (bundled, mode) = match tool {
        "get_record" => {
            let collection = field("uri")
                .and_then(|u| AtUri::parse(u).ok())
                .map(|u| u.collection);
            let routed = collection
                .as_deref()
                .filter(|_| arguments.get("view").is_none_or(Value::is_null))
                .and_then(crate::view::route);
            match routed {
                Some((v, _)) => (Some(v), "query"),
                None => (
                    collection.as_deref().and_then(crate::view::for_collection),
                    "record",
                ),
            }
        }
        "list_records" => (
            field("collection").and_then(crate::view::for_collection),
            "list",
        ),
        "query" => (field("method").and_then(crate::view::for_method), "query"),
        _ => return Width::Third,
    };
    let doc = match arguments.get("view").filter(|v| v.is_object()) {
        Some(inline) => inline,
        None => match bundled {
            Some(v) => &v.doc,
            None => return Width::Third,
        },
    };
    if wide(&doc[mode]["layout"]) {
        Width::Half
    } else {
        Width::Third
    }
}

/// Whether a layout draws with a component that wants room.
fn wide(node: &Value) -> bool {
    node["component"]
        .as_str()
        .is_some_and(|c| WIDE.contains(&c))
        || node["children"]
            .as_array()
            .is_some_and(|c| c.iter().any(wide))
}

/// Tiles kept as they were made before, brought up to date: made columns
/// (`columned`), and titled as a launcher names their call (`retitled`).
/// Whether any was.
pub(crate) fn migrated(tiles: &mut [Value]) -> bool {
    let columned = columned(tiles);
    retitled(tiles) || columned
}

/// A query tile still titled as HUD titled one it had no name for (`query
/// <method>`, as `default_title` did before launchers named calls), titled
/// as a trusted view's launcher names that very call ("Discover" for
/// Bluesky's feed). Whether any was.
fn retitled(tiles: &mut [Value]) -> bool {
    let mut any = false;
    for t in tiles.iter_mut() {
        let arguments = match &t["arguments"] {
            Value::Object(_) => t["arguments"].clone(),
            _ => t["argumentsJson"]
                .as_str()
                .and_then(|s| serde_json::from_str(s).ok())
                .unwrap_or(Value::Null),
        };
        let Some(method) = arguments["method"]
            .as_str()
            .filter(|_| t["tool"] == "query")
        else {
            continue;
        };
        if t["title"].as_str() != Some(&format!("query {method}")) {
            continue;
        }
        if let Some(named) = crate::view::launch_title(method, &arguments["params"]) {
            t["title"] = named.into();
            any = true;
        }
    }
    any
}

/// Tiles kept before canvases were strips of columns, made columns: each
/// without an `order` given one after those with one (1, 2, 3… where none
/// has), by where it was, rows top to bottom, each left to right; its
/// `width` from its width in pixels (under 520 a third, under 760 a half,
/// else two thirds); its `x`, `y`, `w` and `h` dropped. Whether any was.
fn columned(tiles: &mut [Value]) -> bool {
    let number = |t: &Value, k: &str| t[k].as_f64().filter(|n| n.is_finite()).unwrap_or(0.0);
    let mut old: Vec<usize> = (0..tiles.len())
        .filter(|&i| tiles[i].get("order").is_none())
        .collect();
    if old.is_empty() {
        return false;
    }
    old.sort_by(|&a, &b| {
        let (a, b) = (&tiles[a], &tiles[b]);
        number(a, "y")
            .total_cmp(&number(b, "y"))
            .then(number(a, "x").total_cmp(&number(b, "x")))
    });
    let last = tiles
        .iter()
        .filter_map(|t| t["order"].as_str().and_then(|o| checked_order(o).ok()))
        .fold(0.0, f64::max)
        .floor();
    for (n, &i) in old.iter().enumerate() {
        let t = &mut tiles[i];
        let width = Width::of_pixels(t["w"].as_f64().unwrap_or(0.0));
        if let Some(o) = t.as_object_mut() {
            for k in ["x", "y", "w", "h"] {
                o.remove(k);
            }
            o.insert("order".into(), json!(order_text(last + n as f64 + 1.0)));
            o.insert("width".into(), json!(width.as_str()));
        }
    }
    true
}

/// A tile's tool: one of HUD's read tools.
pub fn checked_tool(tool: &str) -> Result<String, String> {
    let tool = tool.trim();
    if TOOLS.contains(&tool) {
        return Ok(tool.to_string());
    }
    Err(format!(
        "A tile shows one of HUD's read tools ({}), not {tool}",
        TOOLS.join(", ")
    ))
}

/// A tile's arguments: an object (`{}` if left out), at most 64 KiB as JSON.
pub fn checked_arguments(v: Option<&Value>) -> Result<Value, String> {
    let arguments = match v {
        None | Some(Value::Null) => json!({}),
        Some(a @ Value::Object(_)) => a.clone(),
        Some(_) => return Err("arguments must be an object".into()),
    };
    if arguments.to_string().len() > ARGUMENTS_MAX {
        return Err(format!(
            "arguments are too large: at most {} KiB as JSON",
            ARGUMENTS_MAX / 1024
        ));
    }
    Ok(arguments)
}

/// One line, its spaces collapsed, 1 to `max` characters.
fn one_line(what: &str, s: &str, max: usize) -> Result<String, String> {
    let s = s.split_whitespace().collect::<Vec<_>>().join(" ");
    match s.chars().count() {
        0 => Err(format!("{what} must not be empty")),
        n if n > max => Err(format!("{what} must be at most {max} characters")),
        _ => Ok(s),
    }
}

/// A title given: one line, 1 to 200 characters.
pub fn checked_title(title: &str) -> Result<String, String> {
    one_line("title", title, TITLE_MAX)
}

/// A canvas name given: one line, 1 to 80 characters.
pub fn checked_name(name: &str) -> Result<String, String> {
    one_line("name", name, NAME_MAX)
}

/// A tile's or a canvas's id: 12 hex digits.
pub fn checked_id(id: &str) -> Result<String, String> {
    let id = id.trim();
    if id.len() == 12 && id.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
        Ok(id.to_string())
    } else {
        Err(format!("{id} is not an id (12 hex digits)"))
    }
}

/// `s`, at most `max` characters, an ellipsis ending what was cut.
fn shortened(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    let mut out: String = s.chars().take(max - 1).collect();
    out.push('…');
    out
}

/// A text's first clause: up to its first sentence's end, colon, semicolon
/// or line break.
fn first_clause(text: &str) -> &str {
    let end = [". ", ": ", "; ", "\n"]
        .iter()
        .filter_map(|p| text.find(p))
        .min()
        .unwrap_or(text.len());
    text[..end].trim().trim_end_matches('.')
}

/// A tile's title where none is given, at most 60 characters: what it
/// shows, as `app.bsky.feed.post · alice.test`, an app's name (`Bluesky ·
/// alice.test`), a saved feed's name, or `Following`; else the first
/// clause of the tool's text, if it was run; else the tool and what it is
/// about. `me` is the account an actor `me` names.
pub fn default_title(
    tool: &str,
    arguments: &Value,
    text: Option<&str>,
    me: Option<&str>,
) -> String {
    let field = |v: &Value, k: &str| {
        v.get(k)
            .and_then(Value::as_str)
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string)
    };
    let who = |actor: &str| {
        let actor = actor.trim_start_matches('@');
        match me {
            Some(m) if is_me(actor) => m.to_string(),
            _ => actor.to_string(),
        }
    };
    let of = |what: String, actor: Option<String>| match actor {
        Some(a) => format!("{what} · {}", who(&a)),
        None => what,
    };
    let shown = match tool {
        "describe_repo" => field(arguments, "actor").map(|a| who(&a)),
        // The app alone: whose page it is, the header's second line says.
        "describe_app" => {
            field(arguments, "domain").map(|d| crate::apps::name(&d.to_ascii_lowercase()))
        }
        "list_records" | "describe_collection" => {
            field(arguments, "collection").map(|c| of(c, field(arguments, "actor")))
        }
        "get_record" => field(arguments, "uri")
            .and_then(|u| AtUri::parse(&u).ok())
            .map(|u| of(u.collection, Some(u.authority))),
        "query" => {
            let params = &arguments["params"];
            let method = field(arguments, "method");
            // A trusted view's own name for this very call (Bluesky's
            // "Discover"), else HUD's for a few.
            let launched = method
                .as_deref()
                .and_then(|m| crate::view::launch_title(m, params));
            launched.or_else(|| match method.as_deref() {
                Some("app.bsky.feed.getTimeline") => Some("Following".to_string()),
                Some("app.bsky.feed.getFeed") => field(params, "feed")
                    .filter(|f| !f.starts_with("at://"))
                    .map(|f| match f.to_ascii_lowercase().as_str() {
                        "following" | "timeline" | "home" => "Following".to_string(),
                        _ => f,
                    }),
                Some("app.bsky.feed.getFeedGenerators") => {
                    match field(params, "feeds").as_deref() {
                        Some("saved") => Some("My feeds".to_string()),
                        Some("pinned") => Some("My pinned feeds".to_string()),
                        _ => None,
                    }
                }
                _ => None,
            })
        }
        _ => None,
    };
    let title = shown
        .or_else(|| {
            text.map(first_clause)
                .filter(|c| !c.is_empty())
                .map(str::to_string)
        })
        .or_else(|| {
            ["method", "collection", "actor", "uri"]
                .iter()
                .find_map(|k| field(arguments, k))
                .map(|about| format!("{tool} {about}"))
        })
        .unwrap_or_else(|| tool.to_string());
    shortened(
        &title.split_whitespace().collect::<Vec<_>>().join(" "),
        DERIVED_MAX,
    )
}

/// A tile's tool and arguments in brief, as `canvas_list` lists it:
/// `query(method: app.bsky.feed.getFeed, params: {"feed":"For You"})`.
pub fn call_summary(tool: &str, arguments: &Value) -> String {
    let parts: Vec<String> = arguments
        .as_object()
        .into_iter()
        .flatten()
        .map(|(k, v)| match (k.as_str(), v) {
            ("view", _) => "view: inline".to_string(),
            (_, Value::String(s)) => format!("{k}: {s}"),
            _ => format!("{k}: {v}"),
        })
        .collect();
    shortened(&format!("{tool}({})", parts.join(", ")), 160)
}

/// A new id: 6 random bytes, in hex.
fn new_id() -> String {
    let bytes = jose::unb64(&jose::random(6)).unwrap_or_default();
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Now, ISO 8601 in UTC, to the millisecond.
pub(crate) fn iso_now() -> String {
    let ms = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_millis() as i64);
    iso(ms)
}

/// A time in milliseconds since 1970, ISO 8601 in UTC.
fn iso(ms: i64) -> String {
    let (days, rest) = (ms.div_euclid(86_400_000), ms.rem_euclid(86_400_000));
    // Days to a civil date (Howard Hinnant's algorithm).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    format!(
        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        rest / 3_600_000,
        rest / 60_000 % 60,
        rest / 1000 % 60,
        rest % 1000
    )
}

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

    fn tile_json(order: Option<&str>) -> Value {
        let mut t = json!({ "id": "00000000000a", "tool": "describe_repo", "arguments": {},
            "title": "t", "width": "half", "by": "person", "at": "2026-11-14T00:00:00.000Z" });
        if let Some(o) = order {
            t["order"] = json!(o);
        }
        t
    }

    #[test]
    fn tiles_kept_and_read() {
        let tile = Tile::from_json(&tile_json(Some("2.5")), "did:plc:a").unwrap();
        assert_eq!(
            (tile.order, tile.width, tile.stack.as_deref(), tile.by),
            (2.5, Width::Half, None, By::Person)
        );
        assert_eq!(tile.author, "did:plc:a");
        assert!(tile.to_json().get("from").is_none() && tile.to_json().get("stack").is_none());
        let stacked = Tile {
            from: Some("00000000000b".into()),
            stack: Some("00000000000c".into()),
            ..tile
        };
        let v = stacked.to_json();
        assert_eq!(
            (&v["order"], &v["stack"], &v["from"]),
            (
                &json!("2.5"),
                &json!("00000000000c"),
                &json!("00000000000b")
            )
        );
        assert_eq!(Tile::from_json(&v, "did:plc:z"), Some(stacked.clone()));
        // Odd links are none; "you" from before is a person; no order is no tile.
        let mut odd = v.clone();
        odd["from"] = json!("not a tile");
        odd["stack"] = json!("nor this");
        odd["by"] = json!("you");
        let read = Tile::from_json(&odd, "did:plc:a").unwrap();
        assert_eq!((read.from, read.stack, read.by), (None, None, By::Person));
        assert!(Tile::from_json(&tile_json(None), "did:plc:a").is_none());
        assert!(Tile::from_json(&tile_json(Some("1e3")), "did:plc:a").is_none());
        // Made by neither a person nor an agent: no tile. No width: a third.
        let mut robot = tile_json(Some("1"));
        robot["by"] = json!("robot");
        assert!(Tile::from_json(&robot, "did:plc:a").is_none());
        let mut narrow = tile_json(Some("1"));
        narrow.as_object_mut().unwrap().remove("width");
        assert_eq!(
            Tile::from_json(&narrow, "did:plc:a").unwrap().width,
            Width::Third
        );
        // Arguments: an object, at most 64 KiB as JSON.
        assert_eq!(checked_arguments(None), Ok(json!({})));
        assert!(checked_arguments(Some(&json!([1]))).is_err());
        let big = json!({ "q": "x".repeat(ARGUMENTS_MAX) });
        assert_eq!(
            checked_arguments(Some(&big)),
            Err("arguments are too large: at most 64 KiB as JSON".into())
        );
        assert_eq!(checked_name("  Coast   trip "), Ok("Coast trip".into()));
        assert!(checked_name(&"n".repeat(81)).is_err());
        assert!(checked_name(" ").is_err());
    }

    #[test]
    fn orders_as_text() {
        for (n, s) in [
            (1.0, "1"),
            (2.5, "2.5"),
            (-1.0, "-1"),
            (0.0, "0"),
            (-0.0, "0"),
        ] {
            assert_eq!(order_text(n), s);
            assert_eq!(checked_order(s), Ok(n));
        }
        // Halving a gap fifty times stays short, and reads back exactly.
        let (mut lo, hi) = (1.0f64, 2.0f64);
        for _ in 0..50 {
            lo += (hi - lo) / 2.0;
            let text = order_text(lo);
            assert!(text.len() <= ORDER_MAX, "{text}");
            assert_eq!(checked_order(&text), Ok(lo));
        }
        for bad in [
            "",
            "-",
            "1.",
            ".5",
            "1e5",
            "NaN",
            "inf",
            "+1",
            "1,5",
            &"1".repeat(33),
        ] {
            assert!(checked_order(bad).is_err(), "{bad}");
        }
        assert_eq!(checked_width(" half "), Ok(Width::Half));
        assert!(checked_width("wide").is_err());
    }

    #[test]
    fn widths_from_what_a_tile_shows() {
        let w = |tool: &str, args: Value| default_width(tool, &args);
        assert_eq!(
            w(
                "query",
                json!({ "method": "app.bsky.feed.getFeed", "params": {} })
            ),
            Width::Third
        );
        assert_eq!(
            w(
                "query",
                json!({ "method": "app.bsky.feed.getPostThread", "params": {} })
            ),
            Width::Third
        );
        assert_eq!(
            w(
                "list_records",
                json!({ "actor": "me", "collection": "app.bsky.feed.post" })
            ),
            Width::Third
        );
        // A document, a gallery: half.
        assert_eq!(
            w(
                "get_record",
                json!({ "uri": "at://did:plc:a/site.standard.document/3k" })
            ),
            Width::Half
        );
        assert_eq!(
            w(
                "get_record",
                json!({ "uri": "at://did:plc:a/social.grain.gallery/3k" })
            ),
            Width::Half
        );
        // An inline view's layout counts.
        let view = json!({ "collection": "a.b.c", "record": { "layout": { "component": "Stack",
            "children": [{ "component": "Gallery", "props": {} }] } } });
        assert_eq!(
            w(
                "get_record",
                json!({ "uri": "at://did:plc:a/a.b.c/1", "view": view })
            ),
            Width::Half
        );
        assert_eq!(w("describe_repo", json!({ "actor": "me" })), Width::Third);
    }

    /// A feed tile titled as HUD titled one with no name, before launchers
    /// named calls, takes the name a launcher gives that very call, as kept
    /// on disk (`arguments`) or in a space (`argumentsJson`); a title a
    /// person gave, or a call no launcher names, stays.
    #[test]
    fn placeholder_titles_take_their_launchers_name() {
        let recent = json!({ "method": "social.grain.feed.getFeed",
            "params": { "feed": "at://did:web:grain.social/social.grain.feed.generator/recent" } });
        let tile = |title: &str, arguments: Value| json!({ "id": "t", "tool": "query", "arguments": arguments, "title": title, "order": "1" });
        let mut tiles = vec![
            tile("query social.grain.feed.getFeed", recent.clone()),
            json!({ "tool": "query", "argumentsJson": recent.to_string(),
                    "title": "query social.grain.feed.getFeed", "order": "2" }),
            tile("My recents", recent.clone()),
            tile(
                "query social.grain.feed.getFeed",
                json!({ "method": "social.grain.feed.getFeed",
                "params": { "feed": "at://did:web:grain.social/social.grain.feed.generator/other" } }),
            ),
        ];
        assert!(migrated(&mut tiles));
        let titles: Vec<&str> = tiles.iter().map(|t| t["title"].as_str().unwrap()).collect();
        assert_eq!(
            titles,
            [
                "Recent",
                "Recent",
                "My recents",
                "query social.grain.feed.getFeed"
            ]
        );
        assert!(!migrated(&mut tiles));
    }

    #[test]
    fn tiles_from_before_columns_migrated() {
        // Rows top to bottom, each left to right; widths from pixels.
        let old = |id: &str, x: f64, y: f64, w: f64| {
            json!({ "id": id, "tool": "describe_repo", "arguments": {}, "title": id,
                "x": x, "y": y, "w": w, "h": 560.0, "by": "you", "at": "2026-11-14T00:00:00.000Z" })
        };
        let mut tiles = vec![
            old("00000000000a", 900.0, 0.0, 420.0),
            old("00000000000b", 0.0, 600.0, 600.0),
            old("00000000000c", 0.0, 0.0, 900.0),
            old("00000000000d", 460.0, 0.0, 519.0),
        ];
        assert!(migrated(&mut tiles));
        let read: Vec<Tile> = tiles
            .iter()
            .map(|t| Tile::from_json(t, "did:plc:a").unwrap())
            .collect();
        let placed: Vec<(&str, f64, Width)> = read
            .iter()
            .map(|t| (t.id.as_str(), t.order, t.width))
            .collect();
        assert_eq!(
            placed,
            [
                ("00000000000a", 3.0, Width::Third),
                ("00000000000b", 4.0, Width::Half),
                ("00000000000c", 1.0, Width::TwoThirds),
                ("00000000000d", 2.0, Width::Third),
            ]
        );
        assert!(
            tiles
                .iter()
                .all(|t| t.get("x").is_none() && t.get("h").is_none())
        );
        // Done once: nothing more to do.
        assert!(!migrated(&mut tiles));
        // One from before among those with orders goes after them.
        tiles.push(old("00000000000e", 0.0, 0.0, 420.0));
        assert!(migrated(&mut tiles));
        assert_eq!(tiles[4]["order"], "5");
    }

    #[test]
    fn records_read_back() {
        let mut tile = Tile::from_json(&tile_json(Some("1")), "did:plc:a").unwrap();
        // Arrays in its arguments are as a record holds them.
        tile.arguments = json!({ "uris": ["at://did:plc:a/a.b.c/1"], "limit": 5 });
        let record = tile.record();
        assert_eq!(record["arguments"], tile.arguments);
        assert_eq!(
            Tile::from_record(&tile.id, &record, "did:plc:a"),
            Some(tile.clone())
        );
        // No width: a third. No arguments at all: no tile.
        let mut narrow = record.clone();
        narrow.as_object_mut().unwrap().remove("width");
        assert_eq!(
            Tile::from_record(&tile.id, &narrow, "did:plc:a").map(|t| t.width),
            Some(Width::Third)
        );
        let mut bare = record;
        bare.as_object_mut().unwrap().remove("arguments");
        assert_eq!(Tile::from_record(&tile.id, &bare, "did:plc:a"), None);
        // What is not a tile is left as it is as the rest are made columns.
        let mut tiles = vec![
            json!("not a tile"),
            json!({ "id": "00000000000a", "x": 0.0, "y": 0.0, "w": 420.0 }),
        ];
        assert!(migrated(&mut tiles));
        assert_eq!(tiles[0], "not a tile");
        assert_eq!(tiles[1]["order"], "2");
    }

    #[test]
    fn titles_made_and_summaries() {
        let t = |tool: &str, args: Value, text: Option<&str>| {
            default_title(tool, &args, text, Some("chadtmiller.com"))
        };
        assert_eq!(
            t(
                "list_records",
                json!({ "actor": "me", "collection": "app.bsky.feed.post" }),
                None
            ),
            "app.bsky.feed.post · chadtmiller.com"
        );
        let feed = |f: &str| json!({ "method": "app.bsky.feed.getFeed", "params": { "feed": f } });
        assert_eq!(t("query", feed("For You"), Some("20 posts")), "For You");
        assert_eq!(
            t(
                "describe_app",
                json!({ "domain": "BSKY.app", "actor": "me" }),
                Some("Bluesky (bsky.app).")
            ),
            "Bluesky"
        );
        // A call a bundled view launches takes the launcher's title.
        let grain = |f: &str| {
            json!({ "method": "social.grain.feed.getFeed",
                "params": { "feed": format!("at://did:web:grain.social/social.grain.feed.generator/{f}") } })
        };
        assert_eq!(t("query", grain("recent"), Some("12 galleries")), "Recent");
        // A launcher naming the person (`$me`) names the call for anyone.
        let mut theirs = grain("actor");
        theirs["params"]["actor"] = json!("did:plc:someone");
        assert_eq!(t("query", theirs, None), "Galleries");
        assert_eq!(
            t(
                "list_records",
                json!({ "collection": "app.bsky.feed.post" }),
                None
            ),
            "app.bsky.feed.post"
        );
        // Feeds as no launcher names the call: HUD's own names.
        let generators = |f: &str| json!({ "method": "app.bsky.feed.getFeedGenerators", "params": { "feeds": f, "limit": 5 } });
        assert_eq!(t("query", generators("saved"), None), "My feeds");
        assert_eq!(t("query", generators("pinned"), None), "My pinned feeds");
        assert_ne!(t("query", generators("other"), None), "My feeds");
        assert_eq!(
            t(
                "get_record",
                json!({ "uri": "at://did:plc:x/app.bsky.feed.post/1" }),
                None
            ),
            "app.bsky.feed.post · did:plc:x"
        );
        let call = |method: &str| json!({ "method": method, "params": { "limit": 5 } });
        assert_eq!(
            t("query", call("app.bsky.feed.getTimeline"), None),
            "Following"
        );
        assert_eq!(
            t("query", call("com.example.getThings"), Some("Things: 3")),
            "Things"
        );
        assert_eq!(
            t("describe_app", json!({ "domain": "plyr.fm" }), None),
            "plyr.fm"
        );
        let mut page = tile_json(Some("1"));
        page["tool"] = json!("describe_app");
        page["arguments"] = json!({ "domain": "bsky.app" });
        let page = Tile::from_json(&page, "did:plc:a").unwrap();
        assert_eq!(page.app().as_deref(), Some("bsky.app"));
        // The app of what a tile shows, by the NSID it names.
        let app = |tool: &str, arguments: Value| {
            Tile {
                tool: tool.into(),
                arguments,
                ..page.clone()
            }
            .app()
        };
        let bsky = crate::apps::domain("app.bsky.feed.post");
        assert!(bsky.is_some());
        assert_eq!(
            app(
                "get_record",
                json!({ "uri": "at://did:plc:x/app.bsky.feed.post/1" })
            ),
            bsky
        );
        assert_eq!(
            app(
                "list_records",
                json!({ "collection": "app.bsky.feed.post" })
            ),
            bsky
        );
        assert_eq!(
            app("query", json!({ "method": "app.bsky.feed.getFeed" })),
            bsky
        );
        assert_eq!(app("describe_repo", json!({ "actor": "me" })), None);
        assert_eq!(t("query", feed("following"), None), "Following");
        assert_eq!(
            t(
                "query",
                feed("at://did:plc:x/app.bsky.feed.generator/d"),
                Some("Discover: 20 posts. More")
            ),
            "Discover"
        );
        let long = t("describe_method", json!({}), Some(&"word ".repeat(40)));
        assert_eq!(long.chars().count(), 60);
        assert_eq!(
            call_summary(
                "query",
                &json!({ "method": "app.bsky.feed.getFeed", "params": { "feed": "For You" }, "view": {} })
            ),
            "query(method: app.bsky.feed.getFeed, params: {\"feed\":\"For You\"}, view: inline)"
        );
    }

    #[test]
    fn times_ids_and_infos() {
        assert_eq!(iso(0), "1970-01-01T00:00:00.000Z");
        assert_eq!(iso(1_794_700_800_123), "2026-11-15T00:00:00.123Z");
        assert_eq!(iso(951_782_400_000), "2000-02-29T00:00:00.000Z");
        assert!(checked_id(&new_id()).is_ok());
        let info = CanvasInfo {
            id: "0123456789ab".into(),
            name: "Coast trip".into(),
            owner: "did:plc:a".into(),
            members: vec![
                Member {
                    did: "did:plc:a".into(),
                    handle: Some("a.test".into()),
                    role: Role::Owner,
                    joined: true,
                    invited_by: None,
                },
                Member {
                    did: "did:plc:b".into(),
                    handle: None,
                    role: Role::Viewer,
                    joined: false,
                    invited_by: Some("did:plc:a".into()),
                },
            ],
            created_at: iso(0),
            updated_at: iso(1),
        };
        let mut bad = info.to_json();
        bad["members"] = json!({});
        assert_eq!(CanvasInfo::from_json(&bad), None);
        bad.as_object_mut().unwrap().remove("members");
        assert_eq!(CanvasInfo::from_json(&bad), None);
        bad["members"] = json!([{ "did": "did:plc:a", "role": "boss", "joined": true }]);
        assert_eq!(CanvasInfo::from_json(&bad), None);
        assert_eq!(CanvasInfo::from_json(&info.to_json()), Some(info.clone()));
        let mut ownerless = info.to_json();
        ownerless["owner"] = json!("did:plc:z");
        assert_eq!(CanvasInfo::from_json(&ownerless), None);
        // Others who are in it: an invite pending is not.
        assert!(info.others("did:plc:a").is_empty());
        assert_eq!(info.others("did:plc:b"), ["a.test"]);
        // One who joined with no handle known: by DID.
        let mut joined = info.clone();
        joined.members[1].joined = true;
        assert_eq!(joined.others("did:plc:a"), ["did:plc:b"]);
    }
}