~ 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
886 lines · 34.8 KB Raw History
//! The MCP canvas tools, with sign-in on: `canvas_list`, `canvas_add` (runs
//! the tool once, as the person, to check it works), `canvas_place`,
//! `canvas_remove` and `canvas_create`. Each needs an account; each but
//! `canvas_create` takes `canvas`, a canvas the person is in by id or name,
//! by default their current one. A change made by one is the agent's.

use super::{
    Beside, By, Op, Refused, TITLE_MAX, TOOLS, Tile, Who, call_summary, checked_arguments,
    checked_id, checked_name, checked_title, checked_tool, checked_width, default_title,
};
use crate::Hud;
use crate::oauth::Account;
use crate::tools::{Args, Output, Refusal};
use serde_json::{Value, json};

/// The canvas tools' definitions, listed with sign-in on after the writes.
pub fn definitions() -> Vec<Value> {
    let schema = |properties: Value, required: &[&str]| {
        json!({ "type": "object", "properties": properties, "required": required,
                "additionalProperties": false })
    };
    let annotations =
        |title: &str, read_only: bool, destructive: bool, idempotent: bool, open: bool| {
            json!({ "title": title, "readOnlyHint": read_only, "destructiveHint": destructive,
                "idempotentHint": idempotent, "openWorldHint": open })
        };
    let canvas = json!({ "type": "string",
        "description": "The canvas, by its id or its name (exactly, case aside), of those the person is in; by default their current one, the one they last opened in the workspace." });
    let id = json!({ "type": "string", "pattern": "^[0-9a-f]{12}$",
                     "description": "The tile's id, as canvas_list lists it." });
    let width = json!({ "type": "string", "enum": ["third", "half", "two-thirds", "full"],
        "description": "Its column's width, as a share of the strip's visible width: third, half, two-thirds or full." });
    vec![
        json!({
            "name": "canvas_list",
            "title": "List canvases",
            "description": "List the signed-in person's HUD canvases, their workspace (/workspace on this server): with no canvas, every canvas they own, are shared, or are invited to, then their current canvas's tiles; with canvas, that canvas's tiles. A canvas is a strip of columns, left to right, each one tile or a stack of up to three: tiles are listed in strip order, each with its id, title, column width, the tile it is stacked under, and the read tool and arguments it shows. Needs sign-in.",
            "inputSchema": schema(json!({ "canvas": canvas }), &[]),
            "annotations": annotations("List canvases", true, false, true, false),
        }),
        json!({
            "name": "canvas_add",
            "title": "Add to canvas",
            "description": "Put a read tool's result on one of the signed-in person's HUD canvases, as a tile they, and those it is shared with, see live in their workspace (/workspace on this server): any of describe_repo, describe_app, describe_collection, describe_method, list_records, get_record or query, with the arguments you would call it with (an inline view too). The tool is run once first, as the person, to check it works: an error adds nothing. The page calls the tool itself to draw the tile. E.g. tool query, arguments { method: \"app.bsky.feed.getFeed\", params: { feed: \"For You\" } }. The canvas is a strip of columns: the tile goes as a column of its own at the end; with from, opened from another tile, right after the columns opened from that one already; with after, right of that tile's column. The same call on that canvas already, its handles as DIDs or its keys in another order, adds nothing: that tile is answered, existing true. Needs sign-in, and to be the canvas's owner or an editor.",
            "inputSchema": schema(json!({
                "tool": { "type": "string", "enum": TOOLS, "description": "The read tool whose result the tile shows." },
                "arguments": { "type": "object", "description": "The tool's arguments, as you would call it with them; at most 64 KiB as JSON." },
                "title": { "type": "string", "maxLength": TITLE_MAX, "description": "The tile's title: what it shows, not whose, as \"Posts\", \"Open issues\" or a feed's name (its header names the account and the app beside it); by default HUD names it." },
                "from": { "type": "string", "pattern": "^[0-9a-f]{12}$", "description": "The id of a tile on the same canvas this one is opened from, as canvas_list lists it: as a post opened from a feed's tile. It goes after the columns opened from that one, joined to it." },
                "after": { "type": "string", "pattern": "^[0-9a-f]{12}$", "description": "The id of a tile whose column it goes right of, where not opened from one." },
                "width": width.clone(),
                "canvas": canvas,
            }), &["tool", "arguments"]),
            "annotations": annotations("Add to canvas", false, false, false, true),
        }),
        json!({
            "name": "canvas_place",
            "title": "Place tile",
            "description": "Move a tile on one of the signed-in person's HUD canvases, a strip of columns, right before or after another tile (one of before and after), and set its column's width; either or both. A column moves whole; a tile placed beside another in its own stack moves within it. Needs sign-in, and to be the canvas's owner or an editor.",
            "inputSchema": schema(json!({
                "id": id,
                "before": { "type": "string", "pattern": "^[0-9a-f]{12}$", "description": "The id of the tile it goes before." },
                "after": { "type": "string", "pattern": "^[0-9a-f]{12}$", "description": "The id of the tile it goes after." },
                "width": width,
                "canvas": canvas,
            }), &["id"]),
            "annotations": annotations("Place tile", false, false, true, false),
        }),
        json!({
            "name": "canvas_remove",
            "title": "Remove tile",
            "description": "Take a tile off one of the signed-in person's HUD canvases. Needs sign-in.",
            "inputSchema": schema(json!({ "id": id, "canvas": canvas }), &["id"]),
            "annotations": annotations("Remove tile", false, true, true, false),
        }),
        json!({
            "name": "canvas_create",
            "title": "Create canvas",
            "description": "Make a new HUD canvas for the signed-in person, which becomes their current one: canvas_add then puts tiles on it. Sharing it is the person's, in their workspace. Needs sign-in.",
            "inputSchema": schema(json!({
                "name": { "type": "string", "maxLength": 80, "description": "Its name, as \"Coast trip\"." },
            }), &["name"]),
            "annotations": annotations("Create canvas", false, false, false, false),
        }),
    ]
}

/// A refusal, as a canvas tool's error.
fn tool_error(r: Refused) -> Refusal {
    Refusal::Error(match r {
        Refused::Invalid(why) | Refused::Forbidden(why) | Refused::Limit(why) => why,
        Refused::NoCanvas(why) if why.len() == 12 => {
            format!("You have no canvas {why}; canvas_list lists them")
        }
        Refused::NoCanvas(why) => why,
        Refused::NoTile(id) => {
            format!("There is no tile {id} on that canvas; canvas_list lists them")
        }
    })
}

fn who(account: &Account) -> Who<'_> {
    Who {
        did: &account.did,
        handle: account.handle.as_deref(),
    }
}

/// A canvas as a tool's text names it: `"Coast trip" (shared with
/// mara.photos)`.
fn named(name: &str, others: &[String]) -> String {
    if others.is_empty() {
        format!("\"{name}\"")
    } else {
        format!("\"{name}\" (shared with {})", others.join(", "))
    }
}

/// A canvas's tiles in strip order, a line each: a column's head with its
/// width, a stacked one with the head it is under; one opened from another
/// names it.
fn tile_lines(tiles: &[Tile]) -> String {
    tiles
        .iter()
        .map(|t| {
            let place = match &t.stack {
                Some(head) => format!("stacked under {head}"),
                None => t.width.as_str().to_string(),
            };
            let from = t
                .from
                .as_ref()
                .map(|f| format!(" · from {f}"))
                .unwrap_or_default();
            format!(
                "\n{} · {} · {place}{from} · {}",
                t.id,
                t.title,
                call_summary(&t.tool, &t.arguments)
            )
        })
        .collect()
}

/// Where a canvas is kept, as a sentence: its `storage`.
fn kept(storage: &Value) -> String {
    match (
        storage["kind"].as_str(),
        storage["uri"].as_str(),
        storage["reason"].as_str(),
    ) {
        (Some("space"), Some(uri), _) => format!(" It is kept in your space at {uri}."),
        (_, _, Some(reason)) => format!(" It is kept on this HUD server: {reason}."),
        _ => " It is kept on this HUD server.".to_string(),
    }
}

impl Hud {
    /// The canvas a tool's `canvas` argument names, and its name as the
    /// tool's text gives it.
    async fn tool_canvas(
        &self,
        account: &Account,
        args: &Args<'_>,
    ) -> Result<(String, String), Refusal> {
        let info = self
            .canvases
            .resolve_info(who(account), args.text("canvas")?)
            .await
            .map_err(tool_error)?;
        let shown = named(&info.name, &info.others(&account.did));
        Ok((info.id, shown))
    }

    pub(crate) async fn canvas_list_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(arguments, &["canvas"])?;
        let me = who(account);
        let origin = &self.config.public_origin;
        let (id, shown) = self.tool_canvas(account, &args).await?;
        let tiles = self.canvases.tiles(me, &id).await.map_err(tool_error)?;
        let canvas = self
            .canvases
            .canvas(me, &id, origin)
            .await
            .map_err(tool_error)?;
        let storage = &canvas["canvas"]["storage"];
        let count = |n: usize| format!("{n} {}", if n == 1 { "tile" } else { "tiles" });
        if args.text("canvas")?.is_some() {
            return Ok(Output {
                text: format!(
                    "{shown} at {origin}/workspace has {}.{}{}",
                    count(tiles.len()),
                    kept(storage),
                    tile_lines(&tiles)
                ),
                structured: canvas,
                meta: json!({}),
            });
        }
        let list = self.canvases.list(me).await;
        let mut text = format!("Your canvases at {origin}/workspace:");
        for (_, c) in &list {
            let name = c["record"]["name"].as_str().unwrap_or_default();
            let cid = c["key"].as_str().unwrap_or_default();
            let owner = c["members"]
                .as_array()
                .into_iter()
                .flatten()
                .find(|m| m["role"] == "owner")
                .map(|m| {
                    m["handle"]
                        .as_str()
                        .or(m["did"].as_str())
                        .unwrap_or_default()
                        .to_string()
                })
                .unwrap_or_default();
            let viewer = &c["viewer"];
            let whose = match viewer["role"].as_str().unwrap_or_default() {
                "owner" => "yours".to_string(),
                _ if viewer.get("invitedBy").is_some() => {
                    format!("an invitation from {owner}: accept it in the workspace")
                }
                role => format!("{owner}'s, you are an {role}"),
            };
            let n = c["tileCount"].as_u64().unwrap_or(0) as usize;
            let current = if cid == id { ", current" } else { "" };
            text.push_str(&format!(
                "\n- \"{name}\" ({cid}), {whose}, {}{current}",
                count(n)
            ));
        }
        text.push_str(&format!(
            "\nYour current canvas, {shown}, has {}.{}{}",
            count(tiles.len()),
            kept(storage),
            tile_lines(&tiles)
        ));
        let canvases: Vec<Value> = list.into_iter().map(|(_, c)| c).collect();
        Ok(Output {
            text,
            structured: json!({ "canvases": canvases, "current": id, "canvas": canvas }),
            meta: json!({}),
        })
    }

    pub(crate) async fn canvas_add_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(
            arguments,
            &[
                "tool",
                "arguments",
                "title",
                "from",
                "after",
                "width",
                "canvas",
            ],
        )?;
        let tool = checked_tool(args.required("tool")?)?;
        let tool_arguments = self
            .canonical_call(&tool, &checked_arguments(args.0.get("arguments"))?)
            .await;
        let title = args.text("title")?.map(checked_title).transpose()?;
        let from = args.text("from")?.map(checked_id).transpose()?;
        let after = args.text("after")?.map(checked_id).transpose()?;
        let width = args.text("width")?.map(checked_width).transpose()?;
        let (id, shown) = self.tool_canvas(account, &args).await?;
        let tiles = self
            .canvases
            .tiles(who(account), &id)
            .await
            .map_err(tool_error)?;
        for named in [&from, &after].into_iter().flatten() {
            if !tiles.iter().any(|t| &t.id == named) {
                return Err(tool_error(Refused::NoTile(named.clone())));
            }
        }
        // The same call on the canvas already: that tile, none added.
        if let Some(tile) = self
            .same_tile(who(account), &id, &tool, &tool_arguments)
            .await
            .map_err(tool_error)?
        {
            return Ok(Output {
                text: format!(
                    "\"{}\" is already on the canvas {shown} ({}): nothing added.",
                    tile.title, tile.id
                ),
                structured: json!({ "canvas": id, "tile": tile.view(None, &self.config.public_origin), "existing": true }),
                meta: json!({}),
            });
        }
        // The tool, run once as the account: its error adds nothing.
        let out = self
            .call_read_tool(&tool, Some(&tool_arguments), Some(account))
            .await?;
        let me = account.handle.as_deref().unwrap_or(&account.did);
        let title = match title {
            Some(t) => t,
            None => self
                .feed_title(&tool, &tool_arguments)
                .await
                .unwrap_or_else(|| {
                    default_title(&tool, &tool_arguments, Some(&out.text), Some(me))
                }),
        };
        let op = Op::Add {
            tool,
            arguments: tool_arguments,
            title: Some(title),
            from,
            after,
            stack: None,
            width,
        };
        let tile = self
            .canvases
            .apply(who(account), &id, op, By::Agent)
            .await
            .map_err(tool_error)?;
        Ok(Output {
            text: format!(
                "Added \"{}\" to {shown}: {}.",
                tile.title,
                out.text.trim().trim_end_matches('.')
            ),
            structured: json!({ "canvas": id, "tile": tile.view(None, &self.config.public_origin) }),
            meta: json!({}),
        })
    }

    pub(crate) async fn canvas_place_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(arguments, &["id", "before", "after", "width", "canvas"])?;
        let tid = checked_id(args.required("id")?)?;
        let (before, after) = (args.text("before")?, args.text("after")?);
        let to = match (before, after) {
            (None, None) => None,
            _ => Some(Beside::of(before, after)?),
        };
        let width = args.text("width")?.map(checked_width).transpose()?;
        if to.is_none() && width.is_none() {
            return Err(Refusal::Error(
                "Give before or after, a width, or both".into(),
            ));
        }
        let (id, shown) = self.tool_canvas(account, &args).await?;
        let mut done = Vec::new();
        if let Some(to) = to {
            let said = match &to {
                Beside::Before(t) => format!("before {t}"),
                Beside::After(t) => format!("after {t}"),
            };
            self.canvases
                .apply(
                    who(account),
                    &id,
                    Op::Place {
                        id: tid.clone(),
                        to,
                    },
                    By::Agent,
                )
                .await
                .map_err(tool_error)?;
            done.push(format!("placed {said}"));
        }
        if let Some(width) = width {
            self.canvases
                .apply(
                    who(account),
                    &id,
                    Op::Width {
                        id: tid.clone(),
                        width,
                    },
                    By::Agent,
                )
                .await
                .map_err(tool_error)?;
            done.push(format!("its column {} wide", width.as_str()));
        }
        let tile = self
            .canvases
            .tile(who(account), &id, &tid)
            .await
            .map_err(tool_error)?;
        Ok(Output {
            text: format!("\"{}\" on {shown}: {}.", tile.title, done.join(", ")),
            structured: json!({ "canvas": id, "tile": tile.view(None, &self.config.public_origin) }),
            meta: json!({}),
        })
    }

    pub(crate) async fn canvas_remove_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(arguments, &["id", "canvas"])?;
        let tid = checked_id(args.required("id")?)?;
        let (id, shown) = self.tool_canvas(account, &args).await?;
        let tile = self
            .canvases
            .apply(who(account), &id, Op::Remove { id: tid }, By::Agent)
            .await
            .map_err(tool_error)?;
        Ok(Output {
            text: format!("Removed \"{}\" from {shown}.", tile.title),
            structured: json!({ "id": tile.id, "canvas": id }),
            meta: json!({}),
        })
    }

    pub(crate) async fn canvas_create_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let Some(account) = account else {
            return Err(Refusal::SignIn);
        };
        let args = Args::of(arguments, &["name"])?;
        let name = checked_name(args.required("name")?)?;
        let info = self
            .canvases
            .create(who(account), &name, By::Agent)
            .await
            .map_err(tool_error)?;
        let structured = self
            .canvases
            .info(who(account), &info.id)
            .await
            .map_err(tool_error)?;
        Ok(Output {
            text: format!(
                "Made \"{}\" ({}), now your current canvas at {}/workspace.",
                info.name, info.id, self.config.public_origin
            ),
            structured,
            meta: json!({}),
        })
    }
}

#[cfg(test)]
mod tests {
    use crate::Hud;
    use crate::tools::Refusal;
    use serde_json::{Value, json};

    /// A server with sign-in on, its data in a directory of its own.
    fn hud() -> std::sync::Arc<Hud> {
        let dir =
            std::env::temp_dir().join(format!("hud-canvas-tools-{}", atproto::jose::random(6)));
        Hud::new(crate::Config {
            port: 0,
            bind: "::".parse().unwrap(),
            public_origin: "https://hud.test".into(),
            cache_dir: dir.join("cache"),
            blob_cache_bytes: 0,
            cache_memory_bytes: 1 << 24,
            data_dir: dir,
            oauth: true,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: "http://127.0.0.1:9".into(),
            handle_resolver: None,
            allow_private: false,
            backlinks: crate::backlinks::Backlinks::None,
            favicons: None,
            image_cdn: None,
            relay: None,
            sign_up_pds: crate::config::SIGN_UP_PDS.into(),
            client: Default::default(),
            operators: Vec::new(),
            logs: false,
            logs_keep: crate::logs::KEEP,
        })
        .unwrap()
    }

    /// A canvas's tiles' ids, in strip order.
    async fn list_ids(h: &Hud, who: &crate::oauth::Account, canvas: &str) -> Vec<String> {
        let w = crate::canvas::Who {
            did: &who.did,
            handle: who.handle.as_deref(),
        };
        h.canvases
            .tiles(w, canvas)
            .await
            .unwrap()
            .into_iter()
            .map(|t| t.id)
            .collect()
    }

    #[tokio::test]
    async fn tools_name_their_canvas() {
        let h = hud();
        let auth = h.auth().unwrap();
        let alice = auth
            .account(&auth.signed_in_offline("did:plc:alice", Some("alice.test"), false))
            .unwrap();
        let bob = auth
            .account(&auth.signed_in_offline("did:plc:bob", Some("bob.test"), false))
            .unwrap();
        let call = |name: &'static str, args: Value, who: &crate::oauth::Account| {
            let (h, who) = (&h, who.clone());
            async move { h.call_tool(name, Some(&args), Some(&who)).await.unwrap() }
        };
        for name in [
            "canvas_list",
            "canvas_add",
            "canvas_place",
            "canvas_remove",
            "canvas_create",
        ] {
            assert_eq!(
                h.call_tool(name, Some(&json!({})), None)
                    .await
                    .unwrap()
                    .err(),
                Some(Refusal::SignIn),
                "{name}"
            );
        }
        let describe = json!({ "tool": "describe_method", "arguments": { "method": "app.bsky.feed.getFeed" } });
        // With no canvas named: the current one, "My canvas", made on first use.
        let out = call("canvas_add", describe.clone(), &alice).await.unwrap();
        assert!(out.text.starts_with("Added \"app.bsky.feed.getFeed\" to \"My canvas\": app.bsky.feed.getFeed: a query taking"), "{}", out.text);
        // A tool that fails adds nothing.
        let failed = call(
            "canvas_add",
            json!({ "tool": "get_record", "arguments": { "uri": "nope" } }),
            &alice,
        )
        .await;
        assert!(matches!(failed, Err(Refusal::Error(_))));
        // A new canvas is current; a tile goes there by default.
        let made = call("canvas_create", json!({ "name": "Coast trip" }), &alice)
            .await
            .unwrap();
        let trip = made.structured["key"].as_str().unwrap().to_string();
        assert!(
            made.text.starts_with("Made \"Coast trip\""),
            "{}",
            made.text
        );
        // Shared with Bob as an editor, who has opened it.
        let w = crate::canvas::Who {
            did: "did:plc:alice",
            handle: Some("alice.test"),
        };
        h.canvases
            .invite(
                w,
                &trip,
                "did:plc:bob",
                Some("bob.test"),
                crate::canvas::Role::Editor,
            )
            .await
            .unwrap();
        h.canvases
            .open_canvas(
                crate::canvas::Who {
                    did: "did:plc:bob",
                    handle: Some("bob.test"),
                },
                &trip,
            )
            .await
            .unwrap();
        let out = call("canvas_add", describe.clone(), &alice).await.unwrap();
        assert!(
            out.text.starts_with(
                "Added \"app.bsky.feed.getFeed\" to \"Coast trip\" (shared with bob.test):"
            ),
            "{}",
            out.text
        );
        // Bob names it by name; his tile is his.
        let timeline = json!({ "tool": "describe_method", "arguments": { "method": "app.bsky.feed.getTimeline" } });
        let mut theirs = timeline.clone();
        theirs["canvas"] = json!("coast trip");
        let out = call("canvas_add", theirs, &bob).await.unwrap();
        assert_eq!(out.structured["tile"]["author"], "did:plc:bob");
        assert!(
            out.text.contains("(shared with alice.test)"),
            "{}",
            out.text
        );
        let tid = out.structured["tile"]["key"].as_str().unwrap().to_string();
        // The same call again, its keys otherwise and an empty one more:
        // that tile, none added.
        let again = json!({ "arguments": { "view": null, "method": "app.bsky.feed.getFeed" },
                            "tool": "describe_method" });
        let out = call("canvas_add", again, &alice).await.unwrap();
        assert_eq!(out.structured["existing"], true);
        assert!(
            out.text
                .starts_with("\"app.bsky.feed.getFeed\" is already on the canvas \"Coast trip\""),
            "{}",
            out.text
        );
        assert_eq!(list_ids(&h, &alice, &trip).await.len(), 2);
        let first = list_ids(&h, &alice, &trip).await[0].clone();
        // Listed: every canvas, then the current one's tiles.
        let list = call("canvas_list", json!({}), &alice).await.unwrap();
        assert!(
            list.text
                .starts_with("Your canvases at https://hud.test/workspace:\n- \"My canvas\""),
            "{}",
            list.text
        );
        assert!(
            list.text.contains(&format!(
                "- \"Coast trip\" ({trip}), yours, 2 tiles, current"
            )),
            "{}",
            list.text
        );
        assert!(
            list.text.contains(
                "Your current canvas, \"Coast trip\" (shared with bob.test), has 2 tiles."
            ),
            "{}",
            list.text
        );
        let mine = call("canvas_list", json!({ "canvas": "My canvas" }), &alice)
            .await
            .unwrap();
        assert!(
            mine.text
                .starts_with("\"My canvas\" at https://hud.test/workspace has 1 tile."),
            "{}",
            mine.text
        );
        let bobs = call("canvas_list", json!({}), &bob).await.unwrap();
        assert!(
            bobs.text.contains(&format!(
                "- \"Coast trip\" ({trip}), alice.test's, you are an editor, 2 tiles, current"
            )),
            "{}",
            bobs.text
        );
        // Placed, given a width, and removed on the canvas named.
        let placed = call(
            "canvas_place",
            json!({ "id": tid, "before": first, "width": "full", "canvas": trip }),
            &alice,
        )
        .await
        .unwrap();
        assert_eq!(
            placed.text,
            format!(
                "\"app.bsky.feed.getTimeline\" on \"Coast trip\" (shared with bob.test): placed before {first}, its column full wide."
            )
        );
        assert_eq!(
            list_ids(&h, &alice, &trip).await,
            [tid.clone(), first.clone()]
        );
        assert_eq!(placed.structured["tile"]["record"]["width"], "full");
        for bad in [
            json!({ "id": tid, "canvas": trip }),
            json!({ "id": tid, "before": first, "after": first }),
        ] {
            assert!(matches!(
                call("canvas_place", bad, &alice).await,
                Err(Refusal::Error(_))
            ));
        }
        let removed = call(
            "canvas_remove",
            json!({ "id": tid, "canvas": trip }),
            &alice,
        )
        .await
        .unwrap();
        assert!(removed.text.contains("from \"Coast trip\""));
        let missing = call("canvas_list", json!({ "canvas": "Nowhere" }), &alice).await;
        assert!(
            matches!(missing, Err(Refusal::Error(e)) if e.contains("no canvas named \"Nowhere\""))
        );
        // Opened from a tile on the canvas: right of it, joined to it, and
        // listed so; from a tile not on it, or no tile's id, refused.
        let mine = call("canvas_list", json!({ "canvas": "My canvas" }), &alice)
            .await
            .unwrap();
        assert!(
            mine.text
                .contains("has 1 tile. It is kept on this HUD server.\n"),
            "{}",
            mine.text
        );
        let parent = mine.structured["tiles"][0]["key"].clone();
        let mut opened = timeline.clone();
        opened["canvas"] = json!("My canvas");
        opened["from"] = parent.clone();
        let out = call("canvas_add", opened.clone(), &alice).await.unwrap();
        assert_eq!(out.structured["tile"]["record"]["from"], parent);
        let listed = call("canvas_list", json!({ "canvas": "My canvas" }), &alice)
            .await
            .unwrap();
        let from = format!(" · third · from {}", parent.as_str().unwrap());
        assert!(listed.text.contains(&from), "{}", listed.text);
        assert_eq!(
            listed.structured["tiles"][1]["key"],
            out.structured["tile"]["key"]
        );
        opened["from"] = json!("0000000000ff");
        assert!(matches!(
            call("canvas_add", opened.clone(), &alice).await,
            Err(Refusal::Error(e)) if e.contains("no tile 0000000000ff")
        ));
        opened["from"] = json!("nope");
        assert!(matches!(
            call("canvas_add", opened, &alice).await,
            Err(Refusal::Error(_))
        ));
    }

    #[test]
    fn refusals_and_storage_as_text() {
        use super::{Refused, kept, tool_error};
        assert_eq!(
            tool_error(Refused::Limit("Too many".into())),
            Refusal::Error("Too many".into())
        );
        assert_eq!(
            tool_error(Refused::NoCanvas("0123456789ab".into())),
            Refusal::Error("You have no canvas 0123456789ab; canvas_list lists them".into())
        );
        assert_eq!(
            kept(&json!({ "kind": "space", "uri": "at://did:plc:a/space/t/k" })),
            " It is kept in your space at at://did:plc:a/space/t/k."
        );
        assert_eq!(
            kept(
                &json!({ "kind": "file", "reason": "a canvas shared with others stays on this HUD server" })
            ),
            " It is kept on this HUD server: a canvas shared with others stays on this HUD server."
        );
    }

    #[tokio::test]
    async fn titles_stacks_places_and_invitations() {
        let h = hud();
        let auth = h.auth().unwrap();
        let alice = auth
            .account(&auth.signed_in_offline("did:plc:alice", Some("alice.test"), false))
            .unwrap();
        let bob = auth
            .account(&auth.signed_in_offline("did:plc:bob", Some("bob.test"), false))
            .unwrap();
        let call = |name: &'static str, args: Value, who: &crate::oauth::Account| {
            let (h, who) = (&h, who.clone());
            async move { h.call_tool(name, Some(&args), Some(&who)).await.unwrap() }
        };
        let describe =
            |method: &str| json!({ "tool": "describe_method", "arguments": { "method": method } });
        // An argument it does not take: refused.
        let mut odd = describe("app.bsky.feed.getFeed");
        odd["colour"] = json!("red");
        assert!(matches!(
            call("canvas_add", odd, &alice).await,
            Err(Refusal::Error(_))
        ));
        // A title given is the tile's.
        let mut named = describe("app.bsky.feed.getFeed");
        named["title"] = json!("Feeds");
        let out = call("canvas_add", named, &alice).await.unwrap();
        assert!(out.text.starts_with("Added \"Feeds\" to"), "{}", out.text);
        let head = out.structured["tile"]["key"].as_str().unwrap().to_string();
        let canvas = out.structured["canvas"].as_str().unwrap().to_string();
        let out = call("canvas_add", describe("app.bsky.feed.getTimeline"), &alice)
            .await
            .unwrap();
        let under = out.structured["tile"]["key"].as_str().unwrap().to_string();
        // Placed after another, its width as it was; then its width alone.
        let placed = call(
            "canvas_place",
            json!({ "id": head, "after": under }),
            &alice,
        )
        .await
        .unwrap();
        assert!(
            placed.text.ends_with(&format!(": placed after {under}.")),
            "{}",
            placed.text
        );
        let wide = call(
            "canvas_place",
            json!({ "id": head, "width": "half" }),
            &alice,
        )
        .await
        .unwrap();
        assert!(
            wide.text.ends_with(": its column half wide."),
            "{}",
            wide.text
        );
        // Stacked under another: listed so.
        let me = crate::canvas::Who {
            did: "did:plc:alice",
            handle: Some("alice.test"),
        };
        let stack = crate::canvas::Op::Stack {
            id: under.clone(),
            into: head.clone(),
        };
        h.canvases
            .apply(me, &canvas, stack, crate::canvas::By::Person)
            .await
            .unwrap();
        let list = call("canvas_list", json!({ "canvas": canvas }), &alice)
            .await
            .unwrap();
        assert!(
            list.text.contains(&format!("\n{under} · "))
                && list.text.contains(&format!(" · stacked under {head} · ")),
            "{}",
            list.text
        );
        // Invited, not yet joined: an invitation, listed so.
        h.canvases
            .invite(
                me,
                &canvas,
                "did:plc:bob",
                Some("bob.test"),
                crate::canvas::Role::Viewer,
            )
            .await
            .unwrap();
        let bobs = call("canvas_list", json!({}), &bob).await.unwrap();
        assert!(
            bobs.text.contains(&format!(
                "({canvas}), an invitation from alice.test: accept it in the workspace"
            )),
            "{}",
            bobs.text
        );
        // Two of a name: which is refused.
        for _ in 0..2 {
            call("canvas_create", json!({ "name": "Twin" }), &alice)
                .await
                .unwrap();
        }
        assert!(matches!(
            call("canvas_list", json!({ "canvas": "twin" }), &alice).await,
            Err(Refusal::Error(e)) if e.starts_with("2 canvases are named \"twin\"")
        ));
    }
}