~ 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
6158 lines · 259.6 KB Raw History
//! The tools, a fixed list: their definitions as `tools/list` gives them,
//! and their answers. Each answer is a short summary a person could read
//! (`content`), the data (`structuredContent`), and what only the view
//! needs (`_meta`: `ui`, the data drawn as its view draws it, resolved
//! here (`ui`), or generically with none; and, for a call made as a
//! signed-in account, `viewer`, who that is). `describe_repo` draws an
//! account's profile across the apps it uses (`apps`), with its recent
//! activity (the bundled views' `activity`, `view::activity`) and the sections they add to it
//! (`view::Section`), each drawn by its view;
//! `describe_app` an app's page: where to go in it (its views' launchers)
//! and, for an account, its part in it, the same sections of that app's.
//!
//! The record tools, and `query` for a query's answers (`xrpc`), draw with
//! a view (`view`): one given inline, which is untrusted, or else the
//! bundled one for the collection or method, which is trusted; with
//! neither, generically. A record a bundled method view names in its
//! `records` (a post) opens as that view's query answers it (its thread).
//! A view's joins run before the answer (`join`), its summary writes the
//! text (`summary`). An invalid inline view is the tool's error, every
//! problem named, for the model to fix.
//! `describe_collection` and `describe_method` give what a model needs to
//! write one: the schema without its descriptions, sample records or the
//! defs a query refs, the current view, and the component catalog.
//! Anything a record, lexicon or service says is third parties' text: the
//! text names labels on one line each, never a lexicon's words.
//!
//! With sign-in on, three more write as the account (`writes`):
//! `create_record`, `apply_writes` (several records at once, as a view's
//! `Compose` makes them) and `delete_record`; five keep the account's
//! workspace canvases (`canvas`): `canvas_list`, `canvas_add`,
//! `canvas_place`, `canvas_remove` and `canvas_create`; and four the view
//! alone calls: `send_interactions` (`interactions`), telling a feed what
//! was seen, `call_procedure` (`procedures`), a procedure a bundled view
//! calls, and, for a composer, `link_card` (`cards`) and `find_place`
//! (`places`). A tool that needs an
//! account, called with none, asks for sign-in (`Refusal::SignIn`), which
//! the MCP endpoint answers with its challenge, not a tool error.

use crate::Hud;
use crate::apps;
use crate::blobs::{Urls, Visibility, rewrite};
use crate::catalog;
use crate::identity::Identity;
use crate::join::{self, Engine};
use crate::oauth::Account;
use crate::summary;
use crate::ui;
use crate::uri::AtUri;
use crate::view::{self, Mode, View};
use crate::xrpc;
use serde_json::{Map, Value, json};
use std::sync::Arc;
use std::time::Duration;

/// `list_records`'s page size where no view sets one.
const PAGE: u32 = 25;
/// The most records `describe_collection` lists to count them.
const COUNTED: u32 = 100;
/// The sample records `describe_collection` gives.
const SAMPLES: usize = 3;
/// A repository's Bluesky profile's collection; its record is `self`.
const PROFILE: &str = "app.bsky.actor.profile";
/// How long a profile's section has to answer; one that has not is left out.
const SECTION_WAIT: Duration = Duration::from_secs(3);

/// The collections a bundled view draws, as tool descriptions name them:
/// `social.grain.gallery: Grain photo galleries`. Bundled views are the
/// server's own, so their descriptions may go there.
pub fn bundled_collections() -> String {
    view::bundled()
        .iter()
        .filter_map(|b| {
            Some(format!(
                "{}: {}",
                b.view.collection.as_ref()?,
                b.view.description
            ))
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// The collections a bundled method view draws as its query, as the
/// get_record tool's description names them: `app.bsky.feed.post as
/// app.bsky.feed.getPostThread`.
pub fn bundled_records() -> String {
    view::bundled()
        .iter()
        .filter_map(|b| Some((b.view.method.as_ref()?, &b.view.records)))
        .flat_map(|(m, records)| {
            records
                .iter()
                .map(move |r| format!("{} as {m}", r.collection))
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// The queries the bundled views draw, as the query tool's description
/// names them.
pub fn bundled_methods() -> String {
    view::bundled()
        .iter()
        .filter_map(|b| {
            Some(format!(
                "{}: {}",
                b.view.method.as_ref()?,
                b.view.description
            ))
        })
        .collect::<Vec<_>>()
        .join("; ")
}

/// The tools, in their fixed order: with sign-in on (`asked`, the scope it
/// asks for), the two that write, the canvas's where the workspace is
/// served (`workspace`), and the view's own too, `send_interactions` where
/// the scope asks to send them. The record tools and `query` name
/// `view_uri`, the view resource they are shown in (the server's,
/// versioned by its content).
pub fn definitions(asked: Option<&str>, workspace: bool, view_uri: &str) -> Vec<Value> {
    let oauth = asked.is_some();
    let actor = json!({
        "type": "string",
        "description": if oauth {
            "A handle (as alice.bsky.social, with or without @) or a DID; or me, the signed-in account (asks the person to sign in if they haven't)."
        } else {
            "A handle (as alice.bsky.social, with or without @) or a DID."
        }
    });
    let collection = json!({ "type": "string", "description": "The collection's NSID." });
    let inline = json!({
        "type": "object",
        "description": "A view (place.hud.view) to draw the records with, in place of the bundled one: read describe_collection first for its catalog and the collection's schema and samples. Invalid views are refused with every problem named."
    });
    let inline_query = json!({
        "type": "object",
        "description": "A view (place.hud.view, with method and a query mode) to draw the answer with, in place of the bundled one: read describe_method first. Invalid views are refused with every problem named."
    });
    let method =
        json!({ "type": "string", "description": "The query's NSID, as app.bsky.feed.getFeed." });
    let more = json!({ "type": "string",
        "description": "The page token a list in a previous answer carried (its next), for that list's next page alone." });
    let schema = |properties: Value, required: &[&str]| {
        json!({ "type": "object", "properties": properties, "required": required,
                "additionalProperties": false })
    };
    let ui = json!({ "ui": { "resourceUri": view_uri }, "ui/resourceUri": view_uri });
    let tool = |name: &str, title: &str, description: String, input: Value, view: bool| {
        let mut t = json!({
            "name": name,
            "title": title,
            "description": description,
            "inputSchema": input,
            "annotations": { "title": title, "readOnlyHint": true, "openWorldHint": true },
        });
        if view {
            t["_meta"] = ui.clone();
        }
        t
    };
    let bundled = bundled_collections();
    let routed = bundled_records();
    let methods = bundled_methods();
    let mut tools = vec![
        tool(
            "describe_repo",
            "Describe repository",
            "Describe an atproto account as its profile across the apps it uses: its DID, verified handle, PDS and the record collections (NSIDs) it holds, drawn as its profile with its apps and a few recent things from each app a bundled view draws.".into(),
            schema(
                json!({ "actor": actor }),
                &["actor"],
            ),
            true,
        ),
        tool(
            "describe_app",
            "Describe app",
            "Describe an atproto app by its domain, the domain behind its NSIDs (bsky.app for app.bsky.*, knotless.dev for dev.knotless.*): its name and icon, a link to its site, and the places to go in it (Bluesky's Discover feed; signed in, the person's own, as their Following feed), drawn as the app's page. With actor, that account's things in it too, a few recent ones. With page, one of the app's own pages its operator wrote (its terms, its privacy policy), by its path.".into(),
            schema(
                json!({ "domain": { "type": "string",
                                    "description": "The app's domain, as bsky.app or knotless.dev." },
                        "actor": actor,
                        "cursor": { "type": "string",
                                    "description": "The cursor a previous call returned, for the next page." },
                        "more": more,
                        "page": { "type": "string",
                                  "description": "The path of one of the app's own pages, as /support/terms." } }),
                &["domain"],
            ),
            true,
        ),
        tool(
            "describe_collection",
            "Describe collection",
            "Read before writing a view: the collection's schema (structure only), sample records, the current view, and the component catalog.".into(),
            schema(
                json!({ "actor": actor, "collection": collection }),
                &["actor", "collection"],
            ),
            false,
        ),
        tool(
            "describe_method",
            "Describe method",
            "Read before calling a query or writing a view of its answers: the query's parameters and output (structure only, with the defs they ref), the current view, and the component catalog.".into(),
            schema(json!({ "method": method }), &["method"]),
            false,
        ),
        tool(
            "list_records",
            "List records",
            format!(
                "List the public records of one collection (an NSID, as app.bsky.feed.post) in an atproto account's repository, newest first, drawn by a view: the one passed as view, else the bundled one ({bundled}), else generically from the collection's lexicon. Pass the returned cursor for more."
            ),
            schema(
                json!({
                    "actor": actor,
                    "collection": collection,
                    "limit": { "type": "integer", "minimum": 1, "maximum": 100,
                               "description": "How many to return: by default 25, or the view's page size." },
                    "cursor": { "type": "string",
                                "description": "The cursor a previous call returned, for the next page." },
                    "view": inline,
                }),
                &["actor", "collection"],
            ),
            true,
        ),
        tool(
            "get_record",
            "Get record",
            format!(
                "Show one public atproto record by its at-uri (at://<did or handle>/<collection>/<rkey>), drawn by a view: the one passed as view; else, for a record a bundled query view draws, as that query answers it, the same as query would (a post opens as its thread: {routed}); else the bundled one ({bundled}), else generically."
            ),
            schema(
                json!({ "uri": { "type": "string", "description": "The record's at-uri." },
                        "view": inline }),
                &["uri"],
            ),
            true,
        ),
        tool(
            "query",
            "Query",
            format!(
                "Call an XRPC query (read-only; no procedures) of an atproto service, as an AppView's feeds, its params checked against the query's lexicon and its answer too, drawn by a view: the one passed as view, else the bundled one ({methods}), else as a JSON tree. {}Pass the returned cursor for more.",
                if oauth {
                    "Signed in, it is called as the account, through its PDS, so personal queries (app.bsky.feed.getTimeline, notifications) answer, and the account's saved feeds go by name: app.bsky.feed.getFeed takes params.feed as a feed's name (\"For You\"; \"Following\" is the timeline), and app.bsky.feed.getFeedGenerators takes params.feeds \"saved\" or \"pinned\" for the account's own feeds; signed out, public data only. "
                } else {
                    "Public data only. "
                }
            ),
            schema(
                json!({
                    "method": method,
                    "params": { "type": "object", "description": "The query's parameters, as its lexicon names them; arrays repeat." },
                    "service": { "type": "string",
                                 "description": "The service to call: a DID and its service's #fragment, as did:web:api.bsky.app#bsky_appview; by default the bundled view's." },
                    "cursor": { "type": "string",
                                "description": "The cursor a previous call returned, for the next page." },
                    "more": more,
                    "at": { "type": "string",
                            "description": "What to show first where its view shows its answer one at a time, as a story's at-uri among an account's." },
                    "compose": { "type": ["boolean", "string"],
                                 "description": "Open its screen at a form: true for its first Compose drawn as the screen itself, not over an item, or that of this label (as New gallery), opened at once. Where nothing shows one (a story screen with pictures), nothing opens." },
                    "view": inline_query,
                }),
                &["method"],
            ),
            true,
        ),
    ];
    if let Some(asked) = asked {
        tools.extend(crate::writes::definitions(asked));
        if workspace {
            tools.extend(crate::canvas::definitions());
        }
        if crate::scope::sends_interactions(asked) {
            tools.push(crate::interactions::definition());
        }
        tools.push(crate::procedures::definition());
        tools.push(crate::cards::definition());
        tools.push(crate::places::definition());
    }
    tools
}

/// Why a tool did not answer: its error, or that it needs the caller to
/// sign in, which the MCP endpoint answers with its challenge.
#[derive(Clone, Debug, PartialEq)]
pub enum Refusal {
    Error(String),
    SignIn,
}

impl From<String> for Refusal {
    fn from(e: String) -> Refusal {
        Refusal::Error(e)
    }
}

impl From<&str> for Refusal {
    fn from(e: &str) -> Refusal {
        Refusal::Error(e.to_string())
    }
}

/// What a person signed out is asked when a tool needs them signed in.
pub const SIGN_IN: &str = "Sign in to HUD with your atproto account for this";

/// What a person signed out is asked when `tool`, called with `arguments`,
/// needs them signed in: for `query`, its method's bundled view's words
/// (`signIn`, as "Sign in to see your notifications"), else `SIGN_IN`.
pub fn sign_in_words(tool: &str, arguments: Option<&Value>) -> String {
    let method = arguments
        .filter(|_| tool == "query")
        .and_then(|a| a.get("method"))
        .and_then(Value::as_str);
    method
        .and_then(|m| view::for_method(m.trim()))
        .and_then(|v| v.sign_in.clone())
        .unwrap_or_else(|| SIGN_IN.to_string())
}

/// A tool's answer.
#[derive(Debug)]
pub struct Output {
    /// The summary, for `content`.
    pub text: String,
    pub structured: Value,
    /// `_meta`: `ui`, and `viewer` for a call made as an account.
    pub meta: Value,
}

/// A tool's arguments, checked against the names it takes.
pub(crate) struct Args<'a>(pub(crate) &'a Map<String, Value>);

impl<'a> Args<'a> {
    pub(crate) fn of(arguments: Option<&'a Value>, takes: &[&str]) -> Result<Args<'a>, String> {
        static EMPTY: std::sync::LazyLock<Map<String, Value>> = std::sync::LazyLock::new(Map::new);
        let args = match arguments {
            None | Some(Value::Null) => &*EMPTY,
            Some(Value::Object(a)) => a,
            Some(_) => return Err("The arguments must be an object".into()),
        };
        if let Some(k) = args.keys().find(|k| !takes.contains(&k.as_str())) {
            return Err(format!("Unknown argument: {k}"));
        }
        Ok(Args(args))
    }

    /// A string argument, or none if left out (or null).
    pub(crate) fn text(&self, name: &str) -> Result<Option<&'a str>, String> {
        match self.0.get(name) {
            None | Some(Value::Null) => Ok(None),
            Some(Value::String(s)) => Ok(Some(s)),
            Some(_) => Err(format!("{name} must be a string")),
        }
    }

    pub(crate) fn required(&self, name: &str) -> Result<&'a str, String> {
        self.text(name)?
            .filter(|s| !s.trim().is_empty())
            .ok_or_else(|| format!("{name} is required"))
    }

    /// `compose`, the form a query's screen opens at: true for its first
    /// Compose, or one's label (1 to 64 characters); none if left out,
    /// null or false.
    pub(crate) fn compose(&self) -> Result<Option<&'a Value>, String> {
        match self.0.get("compose") {
            None | Some(Value::Null | Value::Bool(false)) => Ok(None),
            Some(v) if ui::is_compose(v) => Ok(Some(v)),
            Some(_) => Err("compose must be true or a Compose's label, 1 to 64 characters".into()),
        }
    }

    /// `limit`, from 1 to 100, `default` if left out.
    fn limit(&self, default: u32) -> Result<u32, String> {
        match self.0.get("limit") {
            None | Some(Value::Null) => Ok(default),
            Some(v) => v
                .as_u64()
                .filter(|n| (1..=100).contains(n))
                .map(|n| n as u32)
                .ok_or_else(|| "limit must be an integer from 1 to 100".to_string()),
        }
    }

    /// The view a record tool draws `collection` with: the one given
    /// inline (untrusted), checked, else the bundled one (trusted), else
    /// none.
    fn view(&self, collection: &str) -> Result<Option<Chosen>, String> {
        match self.0.get("view") {
            None | Some(Value::Null) => Ok(view::for_collection(collection).map(Chosen::Bundled)),
            Some(doc) => {
                let v = view::parse(doc, false).map_err(|p| view::error_text(&p))?;
                if v.collection.as_deref() != Some(collection) {
                    return Err(view::error_text(&[format!(
                        "view: draws {}, but the records are of {collection}",
                        v.drawn()
                    )]));
                }
                Ok(Some(Chosen::Inline(Box::new(v))))
            }
        }
    }

    /// The view the query tool draws `method`'s answer with: the one given
    /// inline (untrusted), checked, else the bundled one, else none.
    fn method_view(&self, method: &str) -> Result<Option<Chosen>, String> {
        match self.0.get("view") {
            None | Some(Value::Null) => Ok(view::for_method(method).map(Chosen::Bundled)),
            Some(doc) => {
                let v = view::parse(doc, false).map_err(|p| view::error_text(&p))?;
                if v.method.as_deref() != Some(method) {
                    return Err(view::error_text(&[format!(
                        "view: draws {}, but the query is {method}",
                        v.drawn()
                    )]));
                }
                Ok(Some(Chosen::Inline(Box::new(v))))
            }
        }
    }
}

/// The view a call draws with.
enum Chosen {
    Inline(Box<View>),
    Bundled(&'static View),
}

impl Chosen {
    fn view(&self) -> &View {
        match self {
            Chosen::Inline(v) => v,
            Chosen::Bundled(v) => v,
        }
    }

    /// The mode drawn, if the view has it.
    fn mode(&self, list: bool) -> Option<&Mode> {
        let v = self.view();
        if list {
            v.list.as_ref()
        } else {
            v.record.as_ref()
        }
    }

    /// Whether it is trusted: a bundled view.
    fn trusted(&self) -> bool {
        matches!(self, Chosen::Bundled(_))
    }
}

/// `n` of a thing, as `1 collection` or `3 collections`.
fn count(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// The collections a repository has that a bundled view draws, as
/// `{collection, description}`, in the repository's order. The
/// descriptions are the bundled views' own, so trusted.
fn repo_views(collections: &[String]) -> Vec<Value> {
    collections
        .iter()
        .filter_map(|c| view::for_collection(c))
        .map(|v| json!({ "collection": v.collection, "description": v.description }))
        .collect()
}

/// A repository's summary: who it is (by display name where its profile
/// has one), where, and what bundled views draw of it, then how many
/// collections it holds: `Meri (meri.garden, did:plc:…) on https://….
/// Views: Bluesky posts; Blog posts (standard.site documents). 87
/// collections.` The views are `; `-joined, as a description may hold a
/// comma ("plyr.fm likes, as a playlist"). Never the profile's bio, nor
/// every collection's NSID.
fn repo_text(who: &Identity, profile: &Value, views: &[Value], collections: usize) -> String {
    let display = profile["value"]["displayName"]
        .as_str()
        .map(|d| summary::one_line(d, 64))
        .filter(|d| !d.is_empty());
    let named = match (display.as_deref(), who.handle.as_deref()) {
        (Some(d), Some(h)) => format!("{d} ({h}, {})", who.did),
        (Some(d), None) | (None, Some(d)) => format!("{d} ({})", who.did),
        (None, None) => who.did.clone(),
    };
    let drawn: Vec<&str> = views
        .iter()
        .filter_map(|v| v["description"].as_str())
        .collect();
    let drawn = if drawn.is_empty() {
        String::new()
    } else {
        format!(" Views: {}.", drawn.join("; "))
    };
    let count = if collections == 0 {
        "No collections".to_string()
    } else {
        count(collections, "collection", "collections")
    };
    format!("{named} on {}.{drawn} {count}.", who.pds)
}

/// A repository's profile as a record, its blobs given URLs (read from its
/// repository, as anyone can); null where it has none, or it cannot be
/// read.
fn profile_rec(read: Result<crate::pds::Record, String>, urls: Urls, did: &str) -> Value {
    match read {
        Ok(mut r) => {
            rewrite(&mut r.value, urls, did, Visibility::Public);
            join::rec(&r)
        }
        Err(_) => Value::Null,
    }
}

/// A section an account's profile shows: a bundled view's `profile`, of
/// the app whose domain is `domain`, the call whose tree it shows, and the
/// call its "See all" opens; a `head` one drawn in the profile's head,
/// untitled.
#[derive(Debug)]
struct Planned {
    title: String,
    domain: String,
    call: Value,
    see_all: Value,
    head: bool,
}

/// The sections the bundled views add to the profile of the account `did`
/// holding `collections`, in their ids' order: a collection view's where
/// it holds that collection, its newest records (`list_records`); a method
/// view's where it holds any collection of the query's domain (app.bsky.*
/// for getAuthorFeed), the query called with the view's params, "See all"
/// the same without their limit; a method view's head section for any
/// account, `signed_in`.
fn planned(did: &str, collections: &[String], signed_in: bool) -> Vec<Planned> {
    view::bundled()
        .iter()
        .filter_map(|b| {
            let v = &b.view;
            let s = v.profile.as_ref()?;
            if s.head && !signed_in {
                return None;
            }
            let domain = apps::domain(v.drawn())?;
            // A view with a profile section draws a collection or a method,
            // never both (`view::parse`).
            let (call, see_all) = match &v.collection {
                Some(c) => {
                    if !collections.contains(c) {
                        return None;
                    }
                    let all = json!({ "actor": did, "collection": c });
                    let mut some = all.clone();
                    some["limit"] = s.limit.into();
                    (call_of("list_records", some), call_of("list_records", all))
                }
                None => {
                    let m = v.method.as_ref()?;
                    let uses = collections
                        .iter()
                        .any(|c| apps::domain(c).as_deref() == Some(domain.as_str()));
                    if !uses && !s.head {
                        return None;
                    }
                    let params = s.params_for(did);
                    let mut usual = params.clone();
                    usual.remove("limit");
                    (
                        call_of("query", json!({ "method": m, "params": params })),
                        call_of("query", json!({ "method": m, "params": usual })),
                    )
                }
            };
            Some(Planned {
                title: s.title.clone(),
                domain,
                call,
                see_all,
                head: s.head,
            })
        })
        .collect()
}

/// A tool call, as a tree's `open` names one.
fn call_of(name: &str, args: Value) -> Value {
    json!({ "name": name, "args": args })
}

/// A `Text` node of plain words.
fn text_node(words: &str, style: &str) -> Value {
    json!({ "c": "Text", "p": { "runs": [{ "text": words }], "style": style } })
}

/// An app's icon, as the server at `origin` serves it, drawn small and
/// whole in a rounded square.
fn icon_node(origin: &str, domain: &str) -> Value {
    json!({ "c": "Image", "p": { "src": { "src": apps::icon(origin, domain), "fallback": null },
                                 "alt": "", "ratio": 1.0, "size": "icon" } })
}

/// A `Row` whose middle takes the room the rest leave.
fn spread_row(first: Value, middle: Value, last: Value) -> Value {
    json!({ "c": "Row", "p": { "gap": "sm", "align": "center" },
            "k": [first, { "c": "Stack", "p": { "gap": "md" }, "k": [middle] }, last] })
}

/// A repository's account as people name it: its profile's display name,
/// else its handle, else its DID.
fn account_name(structured: &Value) -> String {
    structured["profile"]["value"]["displayName"]
        .as_str()
        .map(|d| summary::one_line(d, 64))
        .filter(|d| !d.is_empty())
        .or_else(|| structured["handle"].as_str().map(str::to_string))
        .unwrap_or_else(|| structured["did"].as_str().unwrap_or_default().to_string())
}

/// The collections of `describe_repo`'s answer.
fn collections_of(structured: &Value) -> Vec<String> {
    structured["collections"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|c| c.as_str().map(str::to_string))
        .collect()
}

/// The head of an account's page: its `Profile` (banner, avatar, name,
/// handle, bio, read as `ui` reads a view's), its DID where no handle
/// verifies, and where its PDS is.
fn profile_head(structured: &Value) -> Vec<Value> {
    let layout = json!({ "component": "Profile", "props": {
        "name": { "$": "name" }, "handle": { "$": "handle" },
        "description": { "$": "profile.value.description" },
        "avatar": { "$": "profile.value.avatar" }, "banner": { "$": "profile.value.banner" } } });
    let mut scope = structured.clone();
    scope["name"] = account_name(structured).into();
    let ctx = ui::Ctx {
        origins: &[],
        thumbnails: Vec::new(),
        trusted: true,
        root: &scope,
        report: None,
        inline: None,
        lexicon: None,
        handles: None,
        paged: Vec::new(),
        more: ui::More::default(),
        me: None,
        people: None,
    };
    let mut head: Vec<Value> = ui::resolve(&layout, &scope, &ctx).into_iter().collect();
    if structured["handle"].as_str().is_none() {
        head.push(text_node(
            structured["did"].as_str().unwrap_or_default(),
            "mono",
        ));
    }
    let pds = structured["pds"].as_str().unwrap_or_default();
    let host = url::Url::parse(pds)
        .ok()
        .and_then(|u| u.host_str().map(str::to_string))
        .unwrap_or_else(|| pds.to_string());
    head.push(text_node(&format!("Hosted on {host}"), "muted"));
    head
}

/// An account's profile as `_meta.ui` (`describe_repo`): its head
/// (`profile_head`), the apps it uses that HUD draws something of (an app
/// page, or a section of its profile), each its icon and name, opening its
/// page; its recent activity (`activity_ui`); then each section answered,
/// its app's icon, title and "See all" over its tree. Icons from the
/// server at `origin`.
fn profile_ui(
    structured: &Value,
    origin: &str,
    activity: &[Activity],
    sections: Vec<(Planned, Value)>,
) -> Value {
    let did = structured["did"].as_str().unwrap_or_default();
    let collections = collections_of(structured);
    let mut k = profile_head(structured);
    // Head sections (a Message button) under the profile, untitled.
    k.extend(
        sections
            .iter()
            .filter(|(s, _)| s.head)
            .map(|(_, tree)| tree.clone()),
    );
    // An app only where a bundled view draws this account's part in it: its
    // page, or a section of the profile (a head section, a Message button,
    // is no part in the app).
    let sectioned: Vec<String> = planned(did, &collections, false)
        .into_iter()
        .filter(|p| !p.head)
        .map(|p| p.domain)
        .collect();
    let items: Vec<Value> = apps::group(&collections)
        .iter()
        .filter(|a| view::for_domain(&a.domain).is_some() || sectioned.contains(&a.domain))
        .map(|a| {
            let page = call_of("describe_app", json!({ "domain": a.domain, "actor": did }));
            json!({ "open": { "call": page }, "k": [
                { "c": "Row", "p": { "gap": "xs", "align": "center" }, "k": [
                    icon_node(origin, &a.domain),
                    text_node(&a.name, "strong"),
                ] }
            ] })
        })
        .collect();
    if !items.is_empty() {
        k.push(json!({ "c": "List", "p": { "style": "inline" }, "items": items }));
    }
    k.extend(activity_ui(origin, activity));
    for (s, tree) in sections.iter().filter(|(s, _)| !s.head) {
        let head = spread_row(
            icon_node(origin, &s.domain),
            text_node(&s.title, "heading"),
            json!({ "c": "Link", "p": { "label": "See all", "open": { "call": s.see_all } } }),
        );
        k.push(json!({ "c": "Stack", "p": { "gap": "sm" }, "k": [head, tree] }));
    }
    if collections.is_empty() {
        k.push(text_node("This repository has no records.", "muted"));
    }
    json!({ "v": 1, "trusted": true, "title": account_name(structured),
            "root": { "c": "Stack", "p": { "gap": "lg" }, "k": k } })
}

/// The apps of an account's collections, as `describe_repo`'s data lists
/// them: in its profile's order (`apps::group`), each its domain, name,
/// icon from the server at `origin`, and how many of its collections.
fn apps_listed(collections: &[String], origin: &str) -> Value {
    apps::group(collections)
        .iter()
        .map(|a| {
            json!({ "domain": a.domain, "name": a.name, "icon": apps::icon(origin, &a.domain),
                    "count": a.collections.len() })
        })
        .collect::<Vec<_>>()
        .into()
}

/// An account's part in an app, as the app's page shows it: what it is
/// called there ("Yours" for the person asking), its collections of the
/// app, and the sections of its profile for the app that answered.
struct Here {
    who: String,
    collections: Vec<String>,
    sections: Vec<(Planned, Value)>,
}

/// An app's summary: its name and domain, where to go in it, and how
/// many collections of it the account asked of holds: `Bluesky
/// (bsky.app). Go to: Discover; Following. Yours here: 3 collections.`
fn app_text(domain: &str, name: &str, entries: &[apps::Entry], here: Option<&Here>) -> String {
    let mut text = format!("{name} ({domain}).");
    if !entries.is_empty() {
        let titles: Vec<&str> = entries.iter().map(|e| e.title.as_str()).collect();
        text.push_str(&format!(" Go to: {}.", titles.join("; ")));
    }
    if let Some(h) = here {
        text.push_str(&format!(
            " {} here: {}.",
            h.who,
            count(h.collections.len(), "collection", "collections")
        ));
    }
    text
}

/// An app's page as `_meta.ui` (`describe_app`): its head (its icon from
/// the server at `origin`, name and domain, and a link to its site), then
/// where to go in it (`entries`), each opening its query; then, with an
/// account (`here`) that has sections for the app, its part: each section
/// answered, its title and "See all" over its tree. With nothing to open,
/// a line saying so.
fn app_ui(
    domain: &str,
    name: &str,
    origin: &str,
    entries: &[apps::Entry],
    here: Option<&Here>,
) -> Value {
    let head = json!({ "c": "Row", "p": { "gap": "sm", "align": "center" }, "k": [
        icon_node(origin, domain),
        { "c": "Stack", "p": { "gap": "xs" }, "k": [
            text_node(name, "heading"), text_node(domain, "muted") ] } ] });
    let site = json!({ "c": "Link", "p": { "label": format!("Open {domain}"),
                                            "open": { "url": format!("https://{domain}") } } });
    let mut k = vec![json!({ "c": "Stack", "p": { "gap": "sm" }, "k": [head, site] })];
    if !entries.is_empty() {
        let items: Vec<Value> = entries
            .iter()
            .map(|e| json!({ "open": { "call": e.call }, "k": [text_node(&e.title, "body")] }))
            .collect();
        k.push(json!({ "c": "Stack", "p": { "gap": "sm" }, "k": [
            text_node("Go to", "heading"), { "c": "List", "p": { "style": "rows" }, "items": items } ] }));
    }
    match here.filter(|h| !h.sections.is_empty()) {
        Some(h) => {
            let mut part = vec![text_node(&format!("{} here", h.who), "heading")];
            for (s, tree) in &h.sections {
                let title = json!({ "c": "Row", "p": { "gap": "sm", "align": "center" }, "k": [
                    { "c": "Stack", "p": { "gap": "md" }, "k": [text_node(&s.title, "strong")] },
                    { "c": "Link", "p": { "label": "See all", "open": { "call": s.see_all } } } ] });
                part.push(json!({ "c": "Stack", "p": { "gap": "sm" }, "k": [title, tree] }));
            }
            k.push(json!({ "c": "Stack", "p": { "gap": "md" }, "k": part }));
        }
        None if entries.is_empty() => k.push(text_node(
            &format!("Nothing to open in {name} yet: its records open from an account's profile."),
            "muted",
        )),
        None => {}
    }
    json!({ "v": 1, "trusted": true, "title": name,
            "root": { "c": "Stack", "p": { "gap": "lg" }, "k": k } })
}

/// An app page view's main scope (`view::PageMode`), its query joins'
/// answers then added at `joins`: the app (`app`, `describe_app`'s
/// `domain`, `name` and `icon`), the page's account (`actor`) and the
/// signed-in one (`me`), each `{ did, handle }`, the latter null signed
/// out, whether they are one (`mine`), and the app's entry points
/// (`entries`), each `{ title, call }`.
fn page_scope(
    mut app: Value,
    actor: (&str, Option<&str>),
    me: Option<(&str, Option<&str>)>,
    entries: &[apps::Entry],
) -> Value {
    fn account((did, handle): (&str, Option<&str>)) -> Value {
        json!({ "did": did, "handle": handle })
    }
    app["actor"] = account(actor);
    app["me"] = me.map_or(Value::Null, account);
    app["mine"] = me.is_some_and(|(did, _)| did == actor.0).into();
    app["entries"] = entries
        .iter()
        .map(|e| json!({ "title": e.title, "call": e.call }))
        .collect();
    app
}

/// An app page view's layout resolved over its main scope (`page_scope`),
/// as `_meta.ui`, titled with the app's name; `next` the page more, where
/// the join that pages it (`pages`) answered a cursor; each listing of a
/// join that answered one, the call for its own page after (`more`).
fn page_ui(v: &View, scope: &Value, me: Option<&str>) -> Value {
    let mode = &v.doc["page"];
    let next = v
        .page
        .as_ref()
        .and_then(|p| p.pages.as_deref())
        .and_then(|name| scope["joins"][name]["cursor"].as_str())
        .filter(|c| !c.is_empty())
        .map(|cursor| {
            json!({ "name": "describe_app", "args": {
                "domain": scope["domain"], "actor": scope["actor"]["did"], "cursor": cursor } })
        });
    let more = ui::More {
        next: page_nexts(v, scope, me),
        alone: None,
    };
    let mut ui = resolved_ui(v, true, mode, scope, None, (next, more), me, (None, None));
    ui["title"] = scope["name"].clone();
    ui
}

/// The call for the page after each of an app page's joins that answered
/// a cursor: `describe_app` for the same account, with its page token.
fn page_nexts<'v>(v: &'v View, scope: &Value, me: Option<&str>) -> Vec<(&'v str, Value)> {
    let args = json!({ "domain": scope["domain"], "actor": scope["actor"]["did"] });
    let joins = v.page.as_ref().map_or(&[][..], |p| &p.queries[..]);
    crate::more::calls("describe_app", &args, joins.iter(), &scope["joins"], me)
}

/// A join's page more of an app page (`more`): its listing alone, with
/// the call for the page after it, where its answer has a cursor.
fn page_more_ui(v: &View, scope: &Value, join: &str, me: Option<&str>) -> Result<Value, String> {
    let next = page_nexts(v, scope, me);
    more_ui(v, true, &v.doc["page"], scope, (join, next), me)
}

/// A join's page more (`more`) drawn by a mode's layout over its scope,
/// which holds that join's answer alone: the listing of it, with its
/// items and the call for its page after, at the root of a tree.
fn more_ui(
    v: &View,
    trusted: bool,
    mode: &Value,
    scope: &Value,
    (join, next): (&str, Vec<(&str, Value)>),
    me: Option<&str>,
) -> Result<Value, String> {
    let ctx = ui::Ctx {
        more: ui::More {
            next,
            alone: Some(join),
        },
        me,
        ..view_ctx(v, trusted, scope)
    };
    let drawn = ui::resolve(&mode["layout"], scope, &ctx).and_then(crate::more::found);
    let root = drawn.ok_or_else(|| format!("Nothing on this screen pages {join}"))?;
    let mut ui = json!({ "v": 1, "trusted": trusted, "root": root });
    if let Some(app) = &ctx.people {
        ui["people"] = app.as_str().into();
    }
    Ok(ui)
}

/// A section's tree as its profile shows it: no list in it a page more
/// grows, nor pages itself, as the profile shows a few things of each.
fn unpaged(v: &mut Value) {
    match v {
        Value::Object(o) => {
            if let Some(Value::Object(p)) = o.get_mut("p") {
                p.remove("page");
                p.remove("next");
            }
            o.values_mut().for_each(unpaged);
        }
        Value::Array(a) => a.iter_mut().for_each(unpaged),
        _ => {}
    }
}

/// The planned sections that answered, each with its tree; one that did
/// not is left out.
fn answered(planned: Vec<Planned>, trees: Vec<Option<Value>>) -> Vec<(Planned, Value)> {
    planned
        .into_iter()
        .zip(trees)
        .filter_map(|(p, tree)| Some((p, tree?)))
        .collect()
}

/// How many collections the profile's recent activity reads, their newest
/// record each, and how many of those it shows.
const ACTIVITY_READ: usize = 8;
const ACTIVITY_SHOWN: usize = 6;

/// A thing an account did, as its profile's recent activity shows it:
/// when (`millis` since 1970, and as `Time` draws it), its app's domain,
/// what it did (`Posted “hello”`) and the record's at-uri.
#[derive(Debug, PartialEq)]
struct Activity {
    millis: i64,
    when: String,
    domain: String,
    words: String,
    uri: String,
}

/// The collections of an account's that a bundled view names an activity
/// of, in their apps' order (`apps::group`), at most `ACTIVITY_READ`.
fn active(collections: &[String]) -> Vec<String> {
    apps::group(collections)
        .into_iter()
        .flat_map(|a| a.collections)
        .filter(|c| view::activity(c).is_some())
        .take(ACTIVITY_READ)
        .collect()
}

/// An atproto datetime (`2026-11-16T09:30:00.123Z`, or with an offset) as
/// milliseconds since 1970; none for what is not one.
pub(crate) fn datetime_millis(s: &str) -> Option<i64> {
    if !atproto::lexicon::is_datetime(s) {
        return None;
    }
    let n = |at: std::ops::Range<usize>| s.get(at)?.parse::<i64>().ok();
    let (y, mo, d) = (n(0..4)?, n(5..7)?, n(8..10)?);
    let (h, mi, sec) = (n(11..13)?, n(14..16)?, n(17..19)?);
    let rest = s.get(19..)?;
    let (frac, zone) = match rest.strip_prefix('.') {
        Some(r) => r.split_at(r.find(|c: char| !c.is_ascii_digit()).unwrap_or(r.len())),
        None => ("", rest),
    };
    let ms: i64 = format!("{frac:0<3}").get(..3)?.parse().ok()?;
    let offset = match zone {
        "Z" | "z" => 0,
        // `is_datetime` holds any other zone to `+hh:mm` or `-hh:mm`.
        _ => {
            let sign = if zone.starts_with('-') { -1 } else { 1 };
            let (oh, om) = (
                zone.get(1..3)?.parse::<i64>().ok()?,
                zone.get(4..6)?.parse::<i64>().ok()?,
            );
            sign * (oh * 60 + om)
        }
    };
    // Howard Hinnant's days_from_civil, for the proleptic Gregorian calendar.
    let y = if mo <= 2 { y - 1 } else { y };
    let era = y.div_euclid(400);
    let yoe = y - era * 400;
    let doy = (153 * ((mo + 9) % 12) + 2) / 5 + d - 1;
    let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;
    Some((((days * 24 + h) * 60 + mi) * 60 + sec - offset * 60) * 1000 + ms)
}

/// What making the record `rec` (as `join::rec` gives it) of `collection`
/// was, by the bundled view naming its activity (`view::activity`): its
/// value's `createdAt`, else its record key's TID's time (none with
/// neither), and its verb and label as its summary reads it, quoted, or
/// "a" and its noun where it has none.
fn activity_of(collection: &str, rec: &Value) -> Option<Activity> {
    let (verb, s) = view::activity(collection)?;
    let uri = rec["uri"].as_str()?;
    let created = rec["value"]["createdAt"].as_str();
    let (millis, when) = match created.and_then(|c| Some((datetime_millis(c)?, c))) {
        Some((m, c)) => (m, c.to_string()),
        None => {
            let rkey = uri.rsplit('/').next()?;
            let m = i64::try_from(atproto::tid::micros(rkey)? / 1000).ok()?;
            (m, atproto::time::iso(m))
        }
    };
    let words = match summary::label(s, rec) {
        Some(l) => format!("{verb} “{}”", summary::one_line(&l, 48)),
        None => {
            let noun = &s.noun[0];
            let a = if noun.starts_with(['a', 'e', 'i', 'o', 'u']) {
                "an"
            } else {
                "a"
            };
            format!("{verb} {a} {noun}")
        }
    };
    Some(Activity {
        millis,
        when,
        domain: apps::domain(collection)?,
        words,
        uri: uri.to_string(),
    })
}

/// The recent activity of what was read, each collection's newest records
/// (`join::rec`s), none where its read failed: newest first, at most
/// `ACTIVITY_SHOWN`.
fn recent(read: Vec<Option<(String, Vec<Value>)>>) -> Vec<Activity> {
    let mut all: Vec<Activity> = read
        .into_iter()
        .flatten()
        .flat_map(|(c, recs)| {
            recs.iter()
                .filter_map(|r| activity_of(&c, r))
                .collect::<Vec<_>>()
        })
        .collect();
    all.sort_by_key(|a| std::cmp::Reverse(a.millis));
    all.truncate(ACTIVITY_SHOWN);
    all
}

/// An account's recent activity as its profile shows it: "Recent activity"
/// over its rows, each its app's icon from the server at `origin`, what it
/// did and when, opening the record; none with no activity.
fn activity_ui(origin: &str, activity: &[Activity]) -> Option<Value> {
    if activity.is_empty() {
        return None;
    }
    let items: Vec<Value> = activity
        .iter()
        .map(|a| {
            let row = spread_row(
                icon_node(origin, &a.domain),
                text_node(&a.words, "body"),
                json!({ "c": "Time", "p": { "value": a.when } }),
            );
            json!({ "open": { "call": call_of("get_record", json!({ "uri": a.uri })) }, "k": [row] })
        })
        .collect();
    Some(json!({ "c": "Stack", "p": { "gap": "sm" }, "k": [
        text_node("Recent activity", "heading"),
        { "c": "List", "p": { "style": "rows" }, "items": items } ] }))
}

/// A lexicon's structure, every `description` taken out: those are third
/// parties' words for people, which never reach the model. A key named
/// `description` among an object's `properties` is a field, and stays.
fn strip_descriptions(v: &mut Value, in_properties: bool) {
    match v {
        Value::Object(o) => {
            if !in_properties {
                o.remove("description");
            }
            for (k, child) in o.iter_mut() {
                strip_descriptions(child, !in_properties && k == "properties");
            }
        }
        Value::Array(items) => items.iter_mut().for_each(|i| strip_descriptions(i, false)),
        _ => {}
    }
}

/// The scope a record mode draws in: the record, and the page around it.
fn record_scope(page: &Value, rec: &Value) -> Value {
    let mut scope = page.clone();
    if let (Value::Object(s), Value::Object(r)) = (&mut scope, rec) {
        s.extend(r.iter().map(|(k, v)| (k.clone(), v.clone())));
    }
    scope
}

/// Whether an actor names the signed-in account: `me`, or `@me`.
pub(crate) fn is_me(actor: &str) -> bool {
    matches!(actor.trim().trim_start_matches('@'), "me")
}

/// The arguments with every `me` replaced by the signed-in account's DID:
/// `actor`, a query's `params.actor`, and an at-uri's authority
/// (`at://me/…`). Some when it names `me`; with no account, a request to
/// sign in, so "my timeline" and "my galleries" bring the host's sign-in
/// rather than a guess at who "me" is.
fn with_me(arguments: Option<&Value>, me: Option<&str>) -> Result<Option<Value>, Refusal> {
    let Some(Value::Object(args)) = arguments else {
        return Ok(None);
    };
    let names_me = |v: Option<&Value>| v.and_then(Value::as_str).is_some_and(is_me);
    let uri_me = args
        .get("uri")
        .and_then(Value::as_str)
        .and_then(|u| u.strip_prefix("at://"))
        .is_some_and(|rest| is_me(rest.split('/').next().unwrap_or_default()));
    let params_me = names_me(args.get("params").and_then(|p| p.get("actor")));
    if !names_me(args.get("actor")) && !uri_me && !params_me {
        return Ok(None);
    }
    let did = me.ok_or(Refusal::SignIn)?;
    let mut args = args.clone();
    if names_me(args.get("actor")) {
        args.insert("actor".into(), json!(did));
    }
    if uri_me && let Some(uri) = args.get("uri").and_then(Value::as_str) {
        let rest = uri["at://".len()..].split_once('/').map_or("", |(_, r)| r);
        let uri = if rest.is_empty() {
            format!("at://{did}")
        } else {
            format!("at://{did}/{rest}")
        };
        args.insert("uri".into(), json!(uri));
    }
    if params_me && let Some(Value::Object(params)) = args.get_mut("params") {
        params.insert("actor".into(), json!(did));
    }
    Ok(Some(Value::Object(args)))
}

/// Who a query is asked as: the signed-in account, or no one.
fn caller(account: Option<&Account>) -> xrpc::Caller<'_> {
    match account {
        Some(a) => xrpc::Caller::Account(a),
        None => xrpc::Caller::Public,
    }
}

/// What a query's scope holds before its answer (`query_scope`): a query
/// join reading nothing else starts beside the call.
const ASKED: [&str; 5] = ["method", "service", "params", "me", "at"];

/// A query's scope, which its view draws, its summary says and its query
/// joins read: what was asked (its `params` as sent), its answer
/// (`response`) once there is one, signed in who asked (`me`), and what
/// its view shows first, where one at a time (`at`).
fn query_scope(
    method: &str,
    service: &str,
    params: Map<String, Value>,
    response: Option<Value>,
    me: Option<Value>,
    at: Option<&str>,
) -> Value {
    let mut scope = json!({ "method": method, "service": service, "params": params });
    if let Some(response) = response {
        scope["response"] = response;
    }
    if let Some(me) = me {
        scope["me"] = me;
    }
    if let Some(at) = at {
        scope["at"] = at.into();
    }
    scope
}

/// An answer made as an account says who in `_meta.viewer`.
fn with_viewer(answer: &mut Result<Output, Refusal>, account: Option<&Account>) {
    if let (Ok(out), Some(a)) = (answer, account) {
        out.meta["viewer"] = a.viewer();
    }
}

impl Hud {
    /// Answer a call of the tool `name`, made as `account` if signed in:
    /// none if there is no such tool. An answer made as an account says
    /// who in `_meta.viewer`. An actor of `me` is that account (`with_me`).
    pub async fn call_tool(
        &self,
        name: &str,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Option<Result<Output, Refusal>> {
        if crate::canvas::TOOLS.contains(&name) {
            return Some(self.call_read_tool(name, arguments, account).await);
        }
        let auth = self.oauth.as_ref()?;
        // Those sign-in brings, as `definitions` offers them: the canvas's
        // where the workspace is served, `send_interactions` where the
        // scope asks to send them.
        let offered = match name {
            "create_record" | "apply_writes" | "delete_record" | "call_procedure" | "link_card"
            | "find_place" | "admin_logs" => true,
            "canvas_list" | "canvas_add" | "canvas_place" | "canvas_remove" | "canvas_create" => {
                self.config.workspace
            }
            "send_interactions" => crate::scope::sends_interactions(&auth.scope),
            _ => false,
        };
        if !offered {
            return None;
        }
        let rewritten = match self.with_me(arguments, account) {
            Ok(r) => r,
            Err(refusal) => return Some(Err(refusal)),
        };
        let arguments = rewritten.as_ref().or(arguments);
        let mut answer = match name {
            "create_record" => self.create_record_tool(arguments, account).await,
            "apply_writes" => self.apply_writes_tool(arguments, account).await,
            "link_card" => self.link_card_tool(arguments, account).await,
            "find_place" => self.find_place_tool(arguments, account).await,
            "admin_logs" => self.admin_logs_tool(arguments, account).await,
            "delete_record" => self.delete_record_tool(arguments, account).await,
            "canvas_list" => self.canvas_list_tool(arguments, account).await,
            "canvas_add" => self.canvas_add_tool(arguments, account).await,
            "canvas_place" => self.canvas_place_tool(arguments, account).await,
            "canvas_remove" => self.canvas_remove_tool(arguments, account).await,
            "canvas_create" => self.canvas_create_tool(arguments, account).await,
            "call_procedure" => self.call_procedure_tool(arguments, account).await,
            _ => self.send_interactions_tool(arguments, account).await,
        };
        with_viewer(&mut answer, account);
        Some(answer)
    }

    /// A call of one of the read tools (`canvas::TOOLS`), as `call_tool`
    /// answers it: apart, so that `canvas_add` runs one within a call.
    pub(crate) async fn call_read_tool(
        &self,
        name: &str,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let rewritten = self.with_me(arguments, account)?;
        let arguments = rewritten.as_ref().or(arguments);
        let mut answer = match name {
            "describe_repo" => self
                .describe_repo_tool(arguments, account)
                .await
                .map_err(Into::into),
            "describe_app" => self
                .describe_app_tool(arguments, account)
                .await
                .map_err(Into::into),
            "describe_collection" => self
                .describe_collection_tool(arguments)
                .await
                .map_err(Into::into),
            "describe_method" => self
                .describe_method_tool(arguments)
                .await
                .map_err(Into::into),
            "query" => self.query_tool(arguments, account).await,
            "list_records" => self
                .list_records_tool(arguments, account)
                .await
                .map_err(Into::into),
            "get_record" => self
                .get_record_tool(arguments, account)
                .await
                .map_err(Into::into),
            _ => Err(Refusal::Error(format!("{name} is not a read tool"))),
        };
        with_viewer(&mut answer, account);
        answer
    }

    /// The arguments with `me` as the account (`with_me`), where they name
    /// it, with sign-in on. Off, `me` is left as given, and fails as any
    /// name that is no handle does.
    fn with_me(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Option<Value>, Refusal> {
        if self.oauth.is_none() {
            return Ok(None);
        }
        with_me(arguments, account.map(|a| a.did.as_str()))
    }

    async fn describe_repo_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, String> {
        let args = Args::of(arguments, &["actor"])?;
        let who = self.resolve_actor(args.required("actor")?).await?;
        let (collections, profile) = tokio::join!(
            self.describe_repo(&who.pds, &who.did),
            self.get_record(&who.pds, &who.did, PROFILE, "self")
        );
        let collections = collections?;
        let profile = profile_rec(profile, self.config.blob_urls(), &who.did);
        let views = repo_views(&collections);
        let text = repo_text(&who, &profile, &views, collections.len());
        let origin = &self.config.public_origin;
        let structured = json!({ "did": who.did, "handle": who.handle, "pds": who.pds,
                                 "collections": collections, "profile": profile, "views": views,
                                 "apps": apps_listed(&collections, origin) });
        let (sections, activity) = tokio::join!(
            self.profile_sections(
                planned(
                    &who.did,
                    &collections,
                    account.is_some() && self.oauth.is_some()
                )
                .into_iter()
                .filter(|p| !p.head || account.is_some_and(|a| a.did != who.did))
                .collect(),
                account
            ),
            self.recent_activity(&who, &collections)
        );
        let ui = profile_ui(&structured, origin, &activity, sections);
        Ok(Output {
            text,
            structured,
            meta: json!({ "ui": ui }),
        })
    }

    /// Each planned section's tree, as its tool draws it, asked as the
    /// person asking (signed in or not, as `query` and `list_records` are),
    /// all at once, each within `SECTION_WAIT`; one that fails or has not
    /// answered is left out.
    async fn profile_sections(
        &self,
        planned: Vec<Planned>,
        account: Option<&Account>,
    ) -> Vec<(Planned, Value)> {
        let trees = futures::future::join_all(planned.iter().map(|p| async move {
            let args = Some(&p.call["args"]);
            let asked = async {
                match p.call["name"].as_str() {
                    Some("query") => self.query_tool(args, account).await.ok(),
                    _ => self.list_records_tool(args, account).await.ok(),
                }
            };
            let mut out = tokio::time::timeout(SECTION_WAIT, asked).await.ok()??;
            let mut root = out.meta["ui"]["root"].take();
            unpaged(&mut root);
            Some(root).filter(|r| r.is_object())
        }))
        .await;
        answered(planned, trees)
    }

    /// An account's recent activity (`recent`): the newest record of each
    /// of its collections a bundled view names an activity of (`active`),
    /// read from its repository, all at once, each within `SECTION_WAIT`;
    /// one that fails or has not answered is left out.
    async fn recent_activity(&self, who: &Identity, collections: &[String]) -> Vec<Activity> {
        let read = futures::future::join_all(active(collections).into_iter().map(|c| async move {
            let asked = self.list_records(&who.pds, &who.did, &c, 1, None);
            let (records, _) = tokio::time::timeout(SECTION_WAIT, asked).await.ok()?.ok()?;
            Some((c, records.iter().map(join::rec).collect()))
        }))
        .await;
        recent(read)
    }

    /// An app's page: its bundled app page view's (`app_page`) where it
    /// has one and there is an account to draw it for, the one named
    /// (`actor`) or else the signed-in one; else the generic page
    /// (`app_ui`): where to go in it, made the person's where signed in;
    /// with `actor`, that account's part in it, its profile's sections for
    /// the app asked as `profile_sections` asks them. With `cursor`, an app
    /// page's page more: the join that pages it alone, asked from there;
    /// with `more`, a join's page more (`crate::more`): that join alone,
    /// asked from its page token's cursor, its listing alone drawn.
    /// With `page`, one of the app's own pages, as its app file names it
    /// (`view::Page`): its Markdown, drawn as `ui::page_tree` draws it.
    async fn describe_app_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, String> {
        let args = Args::of(arguments, &["domain", "actor", "cursor", "more", "page"])?;
        let given = args.required("domain")?;
        let domain = crate::icons::checked_domain(given, true)
            .ok_or_else(|| format!("Not an app's domain: {}", given.trim()))?;
        let name = apps::name(&domain);
        let origin = &self.config.public_origin;
        let me = account.map(|a| (a.did.as_str(), a.handle.as_deref()));
        let entries = apps::entries(&domain, me);
        let mut structured =
            json!({ "domain": domain, "name": name, "icon": apps::icon(origin, &domain) });
        if let Some(path) = args.text("page")? {
            let found = view::views().page(&domain, path);
            let page = found.ok_or_else(|| format!("{name} has no page {path}"))?;
            let said = page.description.as_deref().map(|d| format!(": {d}"));
            let said = said.unwrap_or_default();
            let text = format!("{} ({}'s page {path}){said}", page.title, page.app);
            structured["path"] = path.into();
            structured["title"] = page.title.as_str().into();
            structured["markdown"] = page.markdown.as_str().into();
            return Ok(Output {
                text,
                structured,
                meta: json!({ "ui": ui::page_tree(page) }),
            });
        }
        let actor = args.text("actor")?.filter(|a| !a.trim().is_empty());
        let me_did = account.map(|a| a.did.as_str());
        let page = view::for_domain(&domain).and_then(|v| v.page.as_ref());
        let cursor = args.text("cursor")?.filter(|c| !c.is_empty());
        let token = args.text("more")?.filter(|t| !t.is_empty());
        // The join asked from a cursor, and for a join's own page more, its `as`.
        let more = match (cursor, token) {
            (None, None) => None,
            (Some(c), _) => Some((
                page.and_then(|p| p.more(c))
                    .ok_or_else(|| format!("{name}'s page has no page more"))?,
                None,
            )),
            (None, Some(t)) => {
                let (join, cursor) = crate::more::read(t, me_did)?;
                let found = page.and_then(|p| p.queries.iter().find(|j| j.name == join));
                let found = found.ok_or_else(|| format!("{name}'s page has no {join} to page"))?;
                Some((found.at_cursor(&cursor), Some(join)))
            }
        };
        if let Some(v) = view::for_domain(&domain) {
            let whose = match actor {
                Some(a) => {
                    let who = self.resolve_actor(a).await?;
                    Some((who.did, who.handle))
                }
                None => account.map(|a| (a.did.clone(), a.handle.clone())),
            };
            if let Some((did, handle)) = whose {
                let mut scope = page_scope(structured, (&did, handle.as_deref()), me, &entries);
                let queries = match &more {
                    Some((m, _)) => std::slice::from_ref(m),
                    None => page.map_or(&[][..], |p| &p.queries[..]),
                };
                let joined = self
                    .query_joins(
                        Some(queries.iter()),
                        v.service.as_deref(),
                        Some(&scope),
                        account,
                    )
                    .await
                    .unwrap_or_default();
                if let Some((m, _)) = more
                    .as_ref()
                    .filter(|(m, _)| joined.get(&m.name).is_none_or(Value::is_null))
                {
                    return Err(format!("{name}'s page more did not answer ({})", m.method));
                }
                let text = app_text(&domain, &name, &entries, None);
                let text = summary::with_said(text, queries, &joined);
                scope["joins"] = Value::Object(joined);
                let ui = match more.as_ref().and_then(|(_, alone)| alone.as_deref()) {
                    Some(join) => page_more_ui(v, &scope, join, me_did)?,
                    None => page_ui(v, &scope, me_did),
                };
                return Ok(Output {
                    text,
                    structured: scope,
                    meta: json!({ "ui": ui }),
                });
            }
        }
        if more.is_some() {
            return Err(format!(
                "{name}'s page more is of an account: name one, or sign in"
            ));
        }
        let here = match actor {
            None => None,
            Some(actor) => {
                let who = self.resolve_actor(actor).await?;
                let (collections, profile) = tokio::join!(
                    self.describe_repo(&who.pds, &who.did),
                    self.get_record(&who.pds, &who.did, PROFILE, "self")
                );
                let collections = collections?;
                let plan = planned(&who.did, &collections, false)
                    .into_iter()
                    .filter(|p| p.domain == domain)
                    .collect();
                let sections = self.profile_sections(plan, account).await;
                let display = profile.ok().and_then(|r| {
                    r.value["displayName"]
                        .as_str()
                        .map(|d| summary::one_line(d, 64))
                        .filter(|d| !d.is_empty())
                });
                let who_name = if account.is_some_and(|a| a.did == who.did) {
                    "Yours".to_string()
                } else {
                    display
                        .or_else(|| who.handle.as_ref().map(|h| format!("@{h}")))
                        .unwrap_or_else(|| who.did.clone())
                };
                structured["actor"] = json!({ "did": who.did, "handle": who.handle });
                Some(Here {
                    who: who_name,
                    collections: collections
                        .into_iter()
                        .filter(|c| apps::domain(c).as_deref() == Some(domain.as_str()))
                        .collect(),
                    sections,
                })
            }
        };
        let text = app_text(&domain, &name, &entries, here.as_ref());
        let ui = app_ui(&domain, &name, origin, &entries, here.as_ref());
        Ok(Output {
            text,
            structured,
            meta: json!({ "ui": ui }),
        })
    }

    async fn describe_collection_tool(&self, arguments: Option<&Value>) -> Result<Output, String> {
        let args = Args::of(arguments, &["actor", "collection"])?;
        let actor = args.required("actor")?;
        let collection = args.required("collection")?;
        if !atproto::syntax::is_nsid(collection) {
            return Err(format!("Not a collection's NSID: {collection}"));
        }
        let (who, lexicon) = tokio::join!(self.resolve_actor(actor), self.lexicon(collection));
        let who = who?;
        let (mut records, next) = self
            .list_records(&who.pds, &who.did, collection, COUNTED, None)
            .await?;
        let counted = match (records.len(), &next) {
            (0, _) => "no records".to_string(),
            (n, Some(_)) => format!("{n}+ records"),
            (n, None) => count(n, "record", "records"),
        };
        records.truncate(SAMPLES);
        // Read from the repository with `com.atproto.repo.listRecords`, as anyone can.
        for r in &mut records {
            rewrite(
                &mut r.value,
                self.config.blob_urls(),
                &who.did,
                Visibility::Public,
            );
        }
        // Each sample's counts from the backlink index, so a model sees
        // which there are to show; left out with no index, or if it fails.
        let linked =
            futures::future::join_all(records.iter().map(|r| self.backlink_counts(&r.uri))).await;
        let samples: Vec<Value> = records
            .iter()
            .zip(linked)
            .map(|(r, counts)| {
                let mut sample = r.to_json();
                if let Some(c) = counts {
                    sample["backlinks"] = crate::backlinks::listed(&c);
                }
                sample
            })
            .collect();
        let schema = match lexicon {
            Value::Null => Value::Null,
            mut l => {
                strip_descriptions(&mut l["doc"]["defs"], false);
                strip_descriptions(&mut l["refs"], false);
                json!({ "nsid": collection, "defs": l["doc"]["defs"].take(), "refs": l["refs"].take() })
            }
        };
        let bundled = view::for_collection(collection);
        let text = format!(
            "{collection} on {}: {counted}{}; {}",
            who.name(),
            match samples.len() {
                0 => String::new(),
                n => format!(", sampled {n}"),
            },
            match (bundled, view::route(collection)) {
                (Some(v), _) => format!("a bundled view exists ({}).", v.description),
                (None, Some((v, _))) => format!(
                    "no bundled view; get_record opens one as {} ({}).",
                    v.drawn(),
                    v.description
                ),
                (None, None) => "no bundled view.".into(),
            }
        );
        Ok(Output {
            text,
            structured: json!({
                "collection": collection,
                "did": who.did,
                "handle": who.handle,
                "schema": schema,
                "samples": samples,
                "view": bundled.map(|v| json!({ "source": "bundled", "view": v.doc })),
                "catalog": catalog::to_json(),
            }),
            meta: json!({}),
        })
    }

    async fn list_records_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, String> {
        let args = Args::of(
            arguments,
            &["actor", "collection", "limit", "cursor", "view"],
        )?;
        let actor = args.required("actor")?;
        let collection = args.required("collection")?;
        if !atproto::syntax::is_nsid(collection) {
            return Err(format!("Not a collection's NSID: {collection}"));
        }
        let chosen = args.view(collection)?;
        if let Some(c) = &chosen {
            self.check_query_joins(c).await?;
        }
        // A page whose records a query join reads is one the join takes at
        // once (`getPosts`' 25 uris): no longer than the view's page size.
        let page_size = chosen.as_ref().and_then(|c| c.view().page_size);
        let per_page = chosen
            .as_ref()
            .and_then(|c| c.mode(true))
            .is_some_and(|m| m.queries.iter().any(view::QueryJoin::per_page));
        let mut limit = args.limit(page_size.unwrap_or(PAGE))?;
        if per_page {
            limit = limit.min(page_size.unwrap_or(PAGE));
        }
        let cursor = args.text("cursor")?;
        let (who, lexicon) = tokio::join!(self.resolve_actor(actor), self.lexicon(collection));
        let who = who?;
        let (mut records, next) = self
            .list_records(&who.pds, &who.did, collection, limit, cursor)
            .await?;
        // Read from the repository with `com.atproto.repo.listRecords`, as anyone can.
        for r in &mut records {
            rewrite(
                &mut r.value,
                self.config.blob_urls(),
                &who.did,
                Visibility::Public,
            );
        }
        let mut recs: Vec<Value> = records.iter().map(join::rec).collect();
        let mode = chosen.as_ref().and_then(|c| c.mode(true).map(|m| (c, m)));
        // The page's query joins, beside the records' own: all of them on
        // its first page, on a page more those that read its records (a
        // page more keeps the first's others).
        let mut joined = None;
        if let Some((_, m)) = mode {
            let engine = Engine::new(self, &who, self.config.blob_urls());
            let first = cursor.is_none();
            let runs = move |j: &&view::QueryJoin| first || j.per_page();
            let queries =
                Some(m.queries.iter().filter(runs)).filter(|q| q.clone().next().is_some());
            let scope = queries.as_ref().map(|_| {
                json!({ "did": who.did, "handle": who.handle, "collection": collection,
                        "records": recs, "cursor": next })
            });
            let (run, asked) = tokio::join!(
                engine.run(&m.join, recs),
                self.query_joins(queries, None, scope.as_ref(), account)
            );
            recs = run;
            joined = asked;
        }
        let handles = self.handles_of(&recs).await;
        let mut text = match mode.and_then(|(_, m)| m.summary.as_ref()) {
            Some(s) => summary::list(s, &who, &recs, next.as_deref()),
            None => summary::generic_list(collection, &who, recs.len(), next.as_deref()),
        };
        let mut structured = json!({ "did": who.did, "handle": who.handle, "collection": collection,
                                     "records": recs, "cursor": next });
        if let (Some((_, m)), Some(joined)) = (mode, joined) {
            text = summary::with_said(text, &m.queries, &joined);
            structured["joins"] = Value::Object(joined);
        }
        let read = (&lexicon, &handles);
        let ui = self
            .drawn_records(chosen.as_ref(), true, &structured, arguments, account, read)
            .await;
        Ok(Output {
            text,
            structured,
            meta: json!({ "ui": ui }),
        })
    }

    /// A record, drawn by the inline view; else, where a bundled method
    /// view names its collection in `records`, as that query answers it
    /// (`routed_record`); else by its collection's bundled view, or
    /// generically.
    async fn get_record_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, String> {
        let args = Args::of(arguments, &["uri", "view"])?;
        let uri = AtUri::parse(args.required("uri")?.trim())?;
        if args.0.get("view").is_none_or(Value::is_null)
            && let Some((v, routed)) = view::route(&uri.collection)
            && let Some(out) = self.routed_record(&uri, v, routed, account).await
        {
            return Ok(out);
        }
        let chosen = args.view(&uri.collection)?;
        if let Some(c) = &chosen {
            self.check_query_joins(c).await?;
        }
        let (who, lexicon) = tokio::join!(
            self.resolve_actor(&uri.authority),
            self.lexicon(&uri.collection)
        );
        let who = who?;
        let mut record = self
            .get_record(&who.pds, &who.did, &uri.collection, &uri.rkey)
            .await?;
        // Read from the repository with `com.atproto.repo.getRecord`, as anyone can.
        let urls = self.config.blob_urls();
        rewrite(&mut record.value, urls, &who.did, Visibility::Public);
        let mut recs = vec![join::rec(&record)];
        let mode = chosen.as_ref().and_then(|c| c.mode(false).map(|m| (c, m)));
        // The record's query joins, once, beside its own joins, their
        // answers among them.
        let mut joined = None;
        if let Some((_, m)) = mode {
            let engine = Engine::new(self, &who, urls);
            let queries = (!m.queries.is_empty()).then_some(&m.queries[..]);
            let scope = queries.map(|_| {
                let page = json!({ "did": who.did, "handle": who.handle,
                                   "collection": uri.collection, "records": recs, "cursor": null });
                record_scope(&page, &recs[0])
            });
            let (run, asked) = tokio::join!(
                engine.run(&m.join, recs),
                self.query_joins(queries.map(<[_]>::iter), None, scope.as_ref(), account)
            );
            recs = run;
            if let Some(asked) = &asked
                && let Some(joins) = recs[0]["joins"].as_object_mut()
            {
                joins.extend(asked.iter().map(|(k, v)| (k.clone(), v.clone())));
            }
            joined = asked;
        }
        let handles = self.handles_of(&recs).await;
        let structured = json!({ "did": who.did, "handle": who.handle,
                                 "collection": uri.collection, "records": recs, "cursor": null });
        let mut text = match mode.and_then(|(_, m)| m.summary.as_ref()) {
            Some(s) => summary::record(
                s,
                &who,
                &record_scope(&structured, &structured["records"][0]),
            ),
            None => summary::generic_record(&uri.collection, &uri.rkey, &who),
        };
        if let (Some((_, m)), Some(joined)) = (mode, joined) {
            text = summary::with_said(text, &m.queries, &joined);
        }
        let read = (&lexicon, &handles);
        let ui = self
            .drawn_records(
                chosen.as_ref(),
                false,
                &structured,
                arguments,
                account,
                read,
            )
            .await;
        Ok(Output {
            text,
            structured,
            meta: json!({ "ui": ui }),
        })
    }

    /// A record of a collection `v` names in its `records` (`routed`), as
    /// the query tool answers `v`'s method with the params read from it,
    /// as the person asking: `_meta.ui`, text, `next` and all. The record
    /// is read only where a param reads its `value` (or `cid`); else it is
    /// its at-uri, its repository by DID. None where the record cannot be
    /// read, a binding finds nothing, or the query does not answer, for
    /// the record's own drawing.
    async fn routed_record(
        &self,
        uri: &AtUri,
        v: &View,
        routed: &view::Routed,
        account: Option<&Account>,
    ) -> Option<Output> {
        let rec = if routed.reads_record() {
            let who = self.resolve_actor(&uri.authority).await.ok()?;
            let record = self
                .get_record(&who.pds, &who.did, &uri.collection, &uri.rkey)
                .await
                .ok()?;
            join::rec(&record)
        } else {
            let did = match atproto::syntax::is_did(&uri.authority) {
                true => uri.authority.clone(),
                false => self.handle_did(&uri.authority).await.ok()?,
            };
            let at = format!("at://{did}/{}/{}", uri.collection, uri.rkey);
            json!({ "uri": at, "did": did })
        };
        let args = routed.args_for(v.method.as_deref()?, &rec)?;
        self.query_tool(Some(&args), account).await.ok()
    }

    /// A mode's query joins run on its main `scope` as the person asking,
    /// `own` the service a query view names: their answers by name, or
    /// none with no joins to run.
    async fn query_joins<'j>(
        &self,
        queries: Option<impl Iterator<Item = &'j view::QueryJoin> + Clone>,
        own: Option<&str>,
        scope: Option<&Value>,
        account: Option<&Account>,
    ) -> Option<Map<String, Value>> {
        let (queries, scope) = (queries?, scope?);
        let asker = xrpc::As {
            hud: self,
            caller: caller(account),
        };
        Some(join::queries(&asker, queries, own, scope, join::QUERY_WAIT).await)
    }

    /// An inline view's query joins checked against their methods'
    /// lexicons as it loads, every problem the tool's error. A bundled
    /// view's are checked by the tests.
    async fn check_query_joins(&self, chosen: &Chosen) -> Result<(), String> {
        let Chosen::Inline(v) = chosen else {
            return Ok(());
        };
        let checked = futures::future::join_all(v.query_joins().map(|j| async move {
            view::query_join_problems(j, &self.lexicon_docs(&j.method).await)
        }))
        .await;
        let problems: Vec<String> = checked.into_iter().flatten().collect();
        match problems.is_empty() {
            true => Ok(()),
            false => Err(view::error_text(&problems)),
        }
    }

    /// A query's lexicon document, if `method` is an NSID naming one.
    async fn query_lexicon(&self, method: &str) -> Result<Arc<Value>, String> {
        if !atproto::syntax::is_nsid(method) {
            return Err(format!("Not a method's NSID: {method}"));
        }
        self.lexicon_doc(method)
            .await
            .ok_or_else(|| format!("No lexicon for {method}"))
    }

    async fn describe_method_tool(&self, arguments: Option<&Value>) -> Result<Output, String> {
        let args = Args::of(arguments, &["method"])?;
        let method = args.required("method")?.trim();
        let doc = self.query_lexicon(method).await?;
        let def = xrpc::query_def(method, &doc)?;
        let mut defs = Value::Object(self.described_defs(method, def).await);
        strip_descriptions(&mut defs, false);
        let mut parameters = def["parameters"].clone();
        let mut output = def["output"].clone();
        strip_descriptions(&mut parameters, false);
        strip_descriptions(&mut output, false);
        let names: Vec<String> = parameters["properties"]
            .as_object()
            .into_iter()
            .flat_map(|p| p.keys())
            .map(|k| {
                let required = parameters["required"]
                    .as_array()
                    .is_some_and(|r| r.iter().any(|n| n == k));
                if required {
                    format!("{k} (required)")
                } else {
                    k.clone()
                }
            })
            .collect();
        let bundled = view::for_method(method);
        let text = format!(
            "{method}: a query taking {}; {}",
            if names.is_empty() {
                "no params".to_string()
            } else {
                names.join(", ")
            },
            match bundled {
                Some(v) => format!(
                    "a bundled view exists ({}), calling {}.",
                    v.description,
                    v.service.as_deref().unwrap_or_default()
                ),
                None => "no bundled view.".into(),
            }
        );
        Ok(Output {
            text,
            structured: json!({
                "method": method,
                "parameters": parameters,
                "output": output,
                "defs": defs,
                "view": bundled.map(|v| json!({ "source": "bundled", "view": v.doc })),
                "catalog": catalog::to_json(),
            }),
            meta: json!({}),
        })
    }

    async fn query_tool(
        &self,
        arguments: Option<&Value>,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        let args = Args::of(
            arguments,
            &[
                "method", "params", "service", "cursor", "more", "view", "at", "compose",
            ],
        )?;
        let compose = args.compose()?;
        let mut params = match args.0.get("params") {
            None | Some(Value::Null) => Map::new(),
            Some(Value::Object(p)) => p.clone(),
            Some(_) => return Err("params must be an object".into()),
        };
        let paging = args.text("cursor")?;
        if let Some(c) = paging {
            params.insert("cursor".into(), Value::String(c.to_string()));
        }
        let method = args.required("method")?.trim();
        // Signed in, feeds named as a person names them (`feeds`).
        let method = match self.oauth {
            Some(_) => self.feeds_by_name(method, &mut params, account).await?,
            None => method.to_string(),
        };
        let method = method.as_str();
        let doc = self.query_lexicon(method).await?;
        let def = xrpc::query_def(method, &doc)?;
        let chosen = args.method_view(method)?;
        if let Some(c) = &chosen {
            self.check_query_joins(c).await?;
        }
        let service = match (args.text("service")?, chosen.as_ref()) {
            (Some(s), _) => s.to_string(),
            (None, Some(c)) if c.view().service.is_some() => {
                c.view().service.clone().unwrap_or_default()
            }
            _ => {
                return Err(format!(
                    "Name a service for {method}: a DID with its service's #fragment, as did:web:api.bsky.app#bsky_appview"
                ).into());
            }
        };
        let service = xrpc::Service::parse(&service)?;
        let asker = xrpc::As {
            hud: self,
            caller: caller(account),
        };
        let docs = self.lexicon_docs(method).await;
        let ready = xrpc::ready(&asker, &docs, method, &mut params).await?;
        let mode = chosen
            .as_ref()
            .and_then(|c| c.view().query.as_ref().map(|q| (c, q)));
        // Its query joins: all of them on its first page, on a page more
        // those that read the answer (a page more keeps the first's others).
        // Those reading nothing of the answer start beside the call, on the
        // scope as it is before it, its params' handles already made DIDs.
        let first = paging.is_none();
        let joins: Vec<&view::QueryJoin> = mode.map_or_else(Vec::new, |(_, q)| {
            q.queries.iter().filter(|j| first || j.per_page()).collect()
        });
        let (early, late): (Vec<_>, Vec<_>) =
            joins.iter().copied().partition(|j| j.reads_only(&ASKED));
        let (me, at) = (account.map(Account::viewer), args.text("at")?);
        let own = service.name();
        let before = query_scope(method, &own, params.clone(), None, me.clone(), at);
        let wait = join::QUERY_WAIT;
        // A join's page more (`crate::more`): that join alone, asked from
        // its page token's cursor on the scope as it is before the call,
        // which is not made again; its listing alone drawn.
        if let Some(token) = args.text("more")?.filter(|t| !t.is_empty()) {
            let me_did = account.map(|a| a.did.as_str());
            let (join, cursor) = crate::more::read(token, me_did)?;
            let found = mode.and_then(|(c, q)| Some((c, self_paged(q).find(|j| j.name == join)?)));
            let (c, j) = found.ok_or_else(|| format!("{method}'s view has no {join} to page"))?;
            let asked = j.at_cursor(&cursor);
            let once = std::iter::once(&asked);
            let joined = join::queries(&asker, once, Some(&own), &before, wait).await;
            if joined.get(&join).is_none_or(Value::is_null) {
                let why = format!("{method}'s {join} did not answer ({})", j.method);
                return Err(why.into());
            }
            let text = format!("{method}: a page more of {join}");
            let text = summary::with_said(text, std::slice::from_ref(j), &joined);
            let mut structured = before;
            structured["joins"] = Value::Object(joined);
            let args = arguments.unwrap_or(&Value::Null);
            let once = std::iter::once(j);
            let next = crate::more::calls("query", args, once, &structured["joins"], me_did);
            let (v, trusted) = (c.view(), c.trusted());
            let ui = more_ui(
                v,
                trusted,
                &v.doc["query"],
                &structured,
                (&join, next),
                me_did,
            )?;
            return Ok(Output {
                text,
                structured,
                meta: json!({ "ui": ui }),
            });
        }
        // A call that fails answers at once, the joins beside it dropped.
        let early = async {
            let early = join::queries(&asker, early.into_iter(), Some(&own), &before, wait);
            Ok::<_, Refusal>(early.await)
        };
        let fresh = mode.is_some_and(|(_, q)| q.fresh);
        let asked = ready.ask(&asker, &service, &params, fresh);
        let (asked, mut joined) = tokio::try_join!(asked, early)?;
        let xrpc::Asked { response, host } = asked;
        let mut structured = query_scope(method, &own, params, Some(response), me, at);
        joined.extend(join::queries(&asker, late.into_iter(), Some(&own), &structured, wait).await);
        let joined = (!joins.is_empty()).then(|| {
            let order = joins.iter().filter_map(|j| joined.remove_entry(&j.name));
            order.collect::<Map<String, Value>>()
        });
        let response = &structured["response"];
        let mut text = match mode {
            Some((_, q)) => match (&q.summary, &q.items) {
                (Some(s), Some(items)) => {
                    let items = items.get(response).and_then(Value::as_array);
                    let cursor = q
                        .cursor
                        .as_ref()
                        .and_then(|c| c.get(response))
                        .and_then(Value::as_str);
                    summary::query(
                        s,
                        method,
                        &host,
                        items.map_or(&[][..], Vec::as_slice),
                        cursor,
                    )
                }
                // An answer that is one thing: summarized in the scope its
                // layout draws in.
                (Some(s), None) => summary::query_one(s, method, &host, &structured),
                (None, _) => summary::generic_query(method, &host, response),
            },
            None => summary::generic_query(method, &host, response),
        };
        if let (Some((_, q)), Some(joined)) = (mode, joined) {
            text = summary::with_said(text, &q.queries, &joined);
            structured["joins"] = Value::Object(joined);
        }
        let mut ui = self
            .drawn_query(chosen.as_ref(), &structured, arguments, account, def)
            .await;
        // Its screen opened at a form: the Compose it names opened at once.
        if let Some(form) = compose {
            ui::open_compose(&mut ui["root"], form);
        }
        Ok(Output {
            text,
            structured,
            meta: json!({ "ui": ui }),
        })
    }

    /// `_meta.ui` of a query's answer: drawn by its view, else as a JSON
    /// tree; what tells something newer came asking for the newest items
    /// alone, where the method takes a limit (`peek_limit`).
    async fn drawn_query(
        &self,
        chosen: Option<&Chosen>,
        structured: &Value,
        arguments: Option<&Value>,
        account: Option<&Account>,
        def: &Value,
    ) -> Value {
        let none = (&Value::Null, &Value::Null);
        let mut ui = self
            .call_ui(chosen, "query", structured, arguments, account, none)
            .await
            .unwrap_or_else(|| json_ui(structured));
        if let Some(args) = ui.pointer_mut("/latest/call/args") {
            let own = args["params"]["limit"].as_u64();
            if let Some(limit) = peek_limit(&def["parameters"]["properties"]["limit"], own) {
                args["params"]["limit"] = limit.into();
            }
        }
        ui
    }

    /// `_meta.ui` of a page of records (`list`) or one record: drawn by
    /// its view, else generically, with its collection's lexicon and its
    /// accounts' handles.
    async fn drawn_records(
        &self,
        chosen: Option<&Chosen>,
        list: bool,
        structured: &Value,
        arguments: Option<&Value>,
        account: Option<&Account>,
        (lexicon, handles): (&Value, &Value),
    ) -> Value {
        let mode = if list { "list" } else { "record" };
        let read = (lexicon, handles);
        let drawn = self
            .call_ui(chosen, mode, structured, arguments, account, read)
            .await;
        drawn.unwrap_or_else(|| generic_records_ui(list, structured, arguments, lexicon, handles))
    }

    /// A view being written (`place.hud.previewView`), drawn again over
    /// what its call answered before (`structured`, the tool's
    /// `structuredContent`) as the tool draws it: `_meta.ui`. Nothing of
    /// the answer is read again, only what the tool reads to draw it (its
    /// collection's lexicon, its accounts' handles, the Bluesky posts its
    /// documents show), so a change to a view's layout draws at once; the
    /// caller reads afresh when the view's joins or query change. Refused
    /// for a tool that draws no view, arguments the tool does not take, a
    /// view that is not valid or not of the answer, or an answer that is
    /// not that tool's.
    pub async fn redraw(
        &self,
        tool: &str,
        arguments: Option<&Value>,
        structured: &Value,
        account: Option<&Account>,
    ) -> Result<Value, String> {
        let not_of = || format!("The answer is not one {tool} gave");
        let list = tool == "list_records";
        match tool {
            "list_records" | "get_record" => {
                let takes: &[&str] = if list {
                    &["actor", "collection", "limit", "cursor", "view"]
                } else {
                    &["uri", "view"]
                };
                let args = Args::of(arguments, takes)?;
                let collection = structured["collection"].as_str().ok_or_else(not_of)?;
                let records = structured["records"].as_array().ok_or_else(not_of)?;
                let chosen = args.view(collection)?;
                let (lexicon, handles) =
                    tokio::join!(self.lexicon(collection), self.handles_of(records));
                let read = (&lexicon, &handles);
                Ok(self
                    .drawn_records(chosen.as_ref(), list, structured, arguments, account, read)
                    .await)
            }
            "query" => {
                let takes = ["method", "params", "service", "cursor", "view"];
                let args = Args::of(arguments, &takes)?;
                let method = structured["method"].as_str().ok_or_else(not_of)?;
                let doc = self.query_lexicon(method).await?;
                let def = xrpc::query_def(method, &doc)?;
                let chosen = args.method_view(method)?;
                Ok(self
                    .drawn_query(chosen.as_ref(), structured, arguments, account, def)
                    .await)
            }
            _ => Err(format!("{tool} draws no view")),
        }
    }

    /// `_meta.ui` of a call drawn with its view's `mode` (`view_ui`), the
    /// Bluesky posts its documents show fetched (`with_posts`); None
    /// without a view or one without that mode.
    async fn call_ui(
        &self,
        chosen: Option<&Chosen>,
        mode: &str,
        structured: &Value,
        arguments: Option<&Value>,
        account: Option<&Account>,
        (lexicon, handles): (&Value, &Value),
    ) -> Option<Value> {
        let c = chosen?;
        let (v, trusted) = (c.view(), c.trusted());
        let read = lexicon_and_handles(lexicon, handles);
        let me = account.map(|a| a.did.as_str());
        let mut ui = view_ui(v, trusted, mode, structured, arguments, me, read)?;
        self.with_posts(&mut ui, v, trusted, account).await;
        Some(ui)
    }

    /// The Bluesky posts a tree's documents show (`ui::post_uris`), asked
    /// of the AppView as the caller, as `query` asks, up to 25 a call, and
    /// each filled in as its quote (`ui::fill_posts`), read with the view's
    /// origins. A post not answered in time keeps its fallback alone. None
    /// where the tree shows no post.
    async fn with_posts(
        &self,
        ui: &mut Value,
        v: &View,
        trusted: bool,
        account: Option<&Account>,
    ) -> Option<()> {
        let uris = ui::post_uris(ui);
        if uris.is_empty() {
            return None;
        }
        let service = xrpc::Service::parse(crate::interactions::APPVIEW).ok()?;
        let asker = xrpc::As {
            hud: self,
            caller: caller(account),
        };
        let asks = uris.chunks(25).map(|chunk| {
            let mut params = Map::new();
            params.insert("uris".into(), json!(chunk));
            let (asker, service) = (&asker, &service);
            async move {
                tokio::time::timeout(
                    join::QUERY_WAIT,
                    xrpc::ask(asker, service, "app.bsky.feed.getPosts", &mut params),
                )
                .await
            }
        });
        let mut posts = Vec::new();
        for asked in futures::future::join_all(asks).await {
            let Ok(Ok(mut asked)) = asked else { continue };
            // Held to its lexicon: `posts` is an array.
            let answered = asked
                .response
                .get_mut("posts")
                .and_then(Value::as_array_mut);
            posts.extend(answered.map(std::mem::take).unwrap_or_default());
        }
        let root = Value::Null;
        ui::fill_posts(ui, &posts, &view_ctx(v, trusted, &root));
        Some(())
    }
}

/// A query's answer with no view: its response as a JSON tree.
fn json_ui(structured: &Value) -> Value {
    json!({ "v": 1, "trusted": false,
            "root": { "c": "Json", "p": { "value": structured["response"], "open": 2 } } })
}

/// `_meta.ui` of an answer drawn with a view's `mode`: `list` a page of
/// records, `next` the page after; `record` the page with the record's
/// keys on top; `query` a query's answer (`query_ui`); `read` what
/// `Fields` reads beside the records. Its `title` the view's description.
/// None when the view has no such mode.
fn view_ui(
    v: &View,
    trusted: bool,
    mode: &str,
    structured: &Value,
    arguments: Option<&Value>,
    me: Option<&str>,
    read: (Option<&Value>, Option<&Value>),
) -> Option<Value> {
    let mut ui = match mode {
        "query" => query_ui(v, trusted, v.query.as_ref()?, structured, arguments, me),
        "list" => {
            v.list.as_ref()?;
            let next = (next_page(structured, arguments), ui::More::default());
            resolved_ui(v, trusted, &v.doc["list"], structured, None, next, me, read)
        }
        _ => {
            v.record.as_ref()?;
            let scope = record_scope(structured, &structured["records"][0]);
            let next = (None, ui::More::default());
            resolved_ui(v, trusted, &v.doc["record"], &scope, None, next, me, read)
        }
    };
    ui["title"] = v.description.clone().into();
    Some(ui)
}

/// A query view's layout resolved over its answer. Its scope is the
/// answer, its items and cursor where the view says, its query joins;
/// `next` the call for the page after; each listing of a join that pages
/// itself (`query_nexts`), the call for its own; `latest` how to tell
/// something newer came (`latest_ui`); a feed view's `report`, its feed
/// bound in the answer.
fn query_ui(
    v: &View,
    trusted: bool,
    q: &view::QueryMode,
    structured: &Value,
    arguments: Option<&Value>,
    me: Option<&str>,
) -> Value {
    let response = &structured["response"];
    let mut scope = structured.clone();
    scope["joins"] = structured
        .get("joins")
        .cloned()
        .unwrap_or_else(|| json!({}));
    scope["items"] = match &q.items {
        Some(p) => Value::Array(
            p.get(response)
                .and_then(Value::as_array)
                .cloned()
                .unwrap_or_default(),
        ),
        None => Value::Null,
    };
    let cursor = q
        .cursor
        .as_ref()
        .filter(|_| q.items.is_some())
        .and_then(|p| p.get(response))
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty());
    scope["cursor"] = cursor.map_or(Value::Null, |s| s.into());
    let next = cursor.map(|cursor| {
        let mut args = arguments.cloned().unwrap_or_else(|| json!({}));
        args["cursor"] = cursor.into();
        json!({ "name": "query", "args": args })
    });
    let report = v.interactions.as_ref().and_then(|i| {
        let feed = i.feed.get(structured).and_then(Value::as_str)?;
        Some((i, feed))
    });
    let more = ui::More {
        next: query_nexts(q, &scope, arguments, me),
        alone: None,
    };
    let mut ui = resolved_ui(
        v,
        trusted,
        &v.doc["query"],
        &scope,
        report,
        (next, more),
        me,
        (None, None),
    );
    if let Some(latest) = latest_ui(q, &scope["items"], arguments) {
        ui["latest"] = latest;
    }
    ui
}

/// The query joins of a query view that page themselves: those read once,
/// not on every page of the answer, and reading nothing of the answer
/// (`ASKED`), so a page more of one needs no call of the query again.
fn self_paged(q: &view::QueryMode) -> impl Iterator<Item = &view::QueryJoin> {
    q.queries
        .iter()
        .filter(|j| !j.per_page() && j.reads_only(&ASKED))
}

/// The call for the page after each of a query view's joins that page
/// themselves (`self_paged`) and answered a cursor: the same `query`, with
/// its page token.
fn query_nexts<'q>(
    q: &'q view::QueryMode,
    scope: &Value,
    arguments: Option<&Value>,
    me: Option<&str>,
) -> Vec<(&'q str, Value)> {
    let args = arguments.unwrap_or(&Value::Null);
    crate::more::calls("query", args, self_paged(q), &scope["joins"], me)
}

/// How to tell something newer came than a page of a query's items, where
/// its view names each one's key: the call again with no cursor (its
/// `limit` made `peek_limit` by `query`, where the method takes one), the
/// items drawn by their keys, and what they are (the summary's plural
/// noun). Something newer came when that call's tree has a key these lack.
fn latest_ui(q: &view::QueryMode, items: &Value, arguments: Option<&Value>) -> Option<Value> {
    let key = q.latest.as_ref()?;
    let items: Vec<Value> = items
        .as_array()?
        .iter()
        .filter_map(|item| key.get(item).and_then(Value::as_str))
        .take(MAX_LATEST_ITEMS)
        .map(|key| json!({ "key": key }))
        .collect();
    let mut args = arguments.cloned().unwrap_or_else(|| json!({}));
    let o = args.as_object_mut()?;
    o.remove("cursor");
    if let Some(Value::Object(params)) = o.get_mut("params") {
        params.remove("cursor");
    }
    let mut latest = json!({ "call": { "name": "query", "args": args }, "items": items });
    if let Some(s) = &q.summary {
        latest["noun"] = s.noun[1].as_str().into();
    }
    Some(latest)
}

/// The most items a tree's `latest` holds: a page's, as a method's `limit`
/// allows at most (100 for the AppView's feeds).
const MAX_LATEST_ITEMS: usize = 100;

/// How many items what tells something newer came asks for, where the
/// method takes an integer `limit` (its lexicon's `limit`): two, so the
/// newest is seen past one pinned first (an author feed's with
/// `includePins`), within the least and most the lexicon allows, and no
/// more than the call's own `limit` (`own`) drew, as one it never drew
/// would always be newer.
fn peek_limit(limit: &Value, own: Option<u64>) -> Option<u64> {
    if limit["type"] != "integer" {
        return None;
    }
    let least = limit["minimum"].as_u64().unwrap_or(1).max(1);
    let most = limit["maximum"].as_u64().unwrap_or(u64::MAX).max(least);
    let peek = PEEK_ITEMS.clamp(least, most);
    Some(own.map_or(peek, |own| peek.min(own.max(least))))
}

/// What a call telling something newer came asks for: the newest, and one
/// more, past a pinned item.
const PEEK_ITEMS: u64 = 2;

/// The call for the page after a page of records, when it has a cursor.
fn next_page(structured: &Value, arguments: Option<&Value>) -> Option<Value> {
    structured["cursor"]
        .as_str()
        .filter(|s| !s.is_empty())
        .map(|cursor| {
            let mut args = arguments.cloned().unwrap_or_else(|| json!({}));
            args["cursor"] = cursor.into();
            json!({ "name": "list_records", "args": args })
        })
}

/// What `Fields` reads beside the data: the collection's lexicon, when
/// there is one, and the verified handles.
fn lexicon_and_handles<'a>(
    lexicon: &'a Value,
    handles: &'a Value,
) -> (Option<&'a Value>, Option<&'a Value>) {
    (Some(lexicon).filter(|l| !l.is_null()), Some(handles))
}

/// `_meta.ui` of records with no view, as the generic renderer drew them:
/// a note when the collection has no lexicon, then a card per record, its
/// uri on top and its fields under it (`ui::record_fields`); `list` a page,
/// with `next` the page after.
fn generic_records_ui(
    list: bool,
    structured: &Value,
    arguments: Option<&Value>,
    lexicon: &Value,
    handles: &Value,
) -> Value {
    let (lexicon, handles) = lexicon_and_handles(lexicon, handles);
    let ctx = ui::Ctx {
        origins: &[],
        thumbnails: Vec::new(),
        trusted: false,
        root: structured,
        report: None,
        inline: None,
        lexicon,
        handles,
        paged: Vec::new(),
        more: ui::More::default(),
        me: None,
        people: None,
    };
    let collection = structured["collection"].as_str().unwrap_or_default();
    let items: Vec<Value> = structured["records"]
        .as_array()
        .into_iter()
        .flatten()
        .map(|r| {
            let uri = r["uri"].as_str().unwrap_or_default();
            json!({ "k": [
                { "c": "Text", "p": { "runs": [{ "text": uri }], "style": "mono" } },
                ui::record_fields(&r["value"], &ctx),
            ] })
        })
        .collect();
    let mut records = json!({ "c": "List", "p": { "style": "cards", "empty": format!("No records in {collection}.") },
                              "items": items });
    if list {
        records["p"]["page"] = true.into();
    }
    let mut k = Vec::new();
    if lexicon.is_none() {
        k.push(json!({ "c": "Text", "p": { "style": "muted",
            "runs": [{ "text": format!("No lexicon found for {collection}, so these show as JSON.") }] } }));
    }
    k.push(records);
    let mut out =
        json!({ "v": 1, "trusted": false, "root": { "c": "Stack", "p": { "gap": "md" }, "k": k } });
    if let Some(next) = next_page(structured, arguments).filter(|_| list) {
        out["next"] = next;
    }
    out
}

/// What a view's drawing is read with, beside its scope: its origins and
/// thumbnails (an inline view's checked to be bundled views' own); an
/// inline one's collection, a record of which opens with it.
fn view_ctx<'a>(v: &'a View, trusted: bool, root: &'a Value) -> ui::Ctx<'a> {
    let thumbnails = v.doc["thumbnails"]
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|t| {
            Some((
                t["from"].as_str()?.to_string(),
                t["to"].as_str()?.to_string(),
            ))
        })
        .collect();
    ui::Ctx {
        origins: v.origins.as_slice(),
        thumbnails,
        trusted,
        root,
        report: None,
        inline: if trusted {
            None
        } else {
            v.collection
                .as_deref()
                .map(|collection| (collection, &v.doc))
        },
        lexicon: None,
        handles: None,
        paged: match (&v.list, &v.page) {
            (Some(m), _) => m
                .queries
                .iter()
                .filter(|j| j.per_page())
                .map(|j| j.name.as_str())
                .collect(),
            (None, Some(p)) => p.pages.as_deref().into_iter().collect(),
            (None, None) => Vec::new(),
        },
        more: ui::More::default(),
        me: None,
        // A bundled view's app, where it has a page: an account it names
        // opens there.
        people: trusted.then(|| apps::with_page(v)).flatten(),
    }
}

/// A mode's layout resolved over its scope as `_meta.ui` (`view_ctx`); a
/// trusted feed view's `report`, its feed's at-uri beside the paths to
/// each item's; a trusted view's `head`, its mode's read (`ui::head`); its
/// `hero`, the first picture it draws large (`ui::hero`). A layout whose
/// top node draws nothing is an empty stack.
#[allow(clippy::too_many_arguments)]
fn resolved_ui(
    v: &View,
    trusted: bool,
    mode: &Value,
    scope: &Value,
    report: Option<(&view::Interactions, &str)>,
    (next, more): (Option<Value>, ui::More),
    me: Option<&str>,
    (lexicon, handles): (Option<&Value>, Option<&Value>),
) -> Value {
    let report = report.filter(|_| trusted);
    let ctx = ui::Ctx {
        report: report.map(|(i, _)| ui::ReportPaths {
            item: &i.item,
            feed_context: i.feed_context.as_ref(),
            req_id: i.req_id.as_ref(),
        }),
        lexicon,
        handles,
        more,
        me,
        ..view_ctx(v, trusted, scope)
    };
    let root = ui::resolve(&mode["layout"], scope, &ctx)
        .unwrap_or_else(|| json!({ "c": "Stack", "k": [] }));
    let mut out = json!({ "v": 1, "trusted": trusted, "root": root });
    ui::set_hero(&mut out);
    if let Some(app) = &ctx.people {
        out["people"] = app.as_str().into();
    }
    if let Some(next) = next {
        out["next"] = next;
    }
    if let Some((_, feed)) = report {
        out["report"] = json!({ "feed": feed, "seen": me.is_some() });
    }
    // How wide it would be drawn, by the answer's scope where the view says
    // so; the reading width, the default, unsaid.
    if let Some(m @ ("wide" | "full")) = ui::measure(&v.doc, scope) {
        out["measure"] = m.into();
    }
    if let Some(head) = trusted
        .then(|| ui::head::resolve(&mode["head"], scope, &ctx))
        .flatten()
    {
        out["head"] = head;
    }
    out
}

/// An answer as `look`'s fixtures hold one, with `_meta.view` (`doc`,
/// `mode`, `trusted`, `origins`) and, for `Fields`, `_meta.lexicon` and
/// `_meta.handles`: made the answer the tool gives now, `_meta.ui` built
/// from its `structuredContent` as the tool builds it, and those keys
/// taken out. `tool` and
/// `arguments` are the call's, when known: what `next` calls again, and
/// whether records with no view are a page or one record; a
/// `describe_repo` answer is an account's profile, its apps' icons on the
/// server that recorded it (`recorded_origin`). No network: a document's
/// Bluesky posts are left to
/// their fallback, a profile's sections and recent activity out. Drawn as
/// no one, but as the account `_meta.viewer` names where the answer was
/// recorded signed in (its own messages its own, a conversation's box).
/// An error loses those keys alone. The tree is fitted to HUD's own web
/// renderer, as current as this HUD (`kit::fit`), as `look` draws it.
pub fn resolve_answer(
    answer: &mut Value,
    tool: Option<&str>,
    arguments: Option<&Value>,
) -> Result<(), String> {
    drawn_answer(answer, tool, arguments)?;
    crate::kit::fit(
        &mut answer["_meta"],
        &crate::kit::Kit::current("hud resolve"),
    );
    Ok(())
}

/// `resolve_answer`'s tree, as resolved, before it is fitted to a kit.
fn drawn_answer(
    answer: &mut Value,
    tool: Option<&str>,
    arguments: Option<&Value>,
) -> Result<(), String> {
    let error = answer["isError"] == true;
    let meta = answer
        .get_mut("_meta")
        .and_then(Value::as_object_mut)
        .ok_or("the answer has no _meta object")?;
    let shown = meta.remove("view").unwrap_or(Value::Null);
    let lexicon = meta.remove("lexicon").unwrap_or(Value::Null);
    let handles = meta.remove("handles").unwrap_or_else(|| json!({}));
    let viewer = meta
        .get("viewer")
        .and_then(|v| v["did"].as_str())
        .map(str::to_string);
    if error {
        return Ok(());
    }
    if tool == Some("describe_repo") {
        let structured = &answer["structuredContent"];
        let origin = recorded_origin(structured);
        let ui = profile_ui(structured, &origin, &[], Vec::new());
        let listed = apps_listed(&collections_of(structured), &origin);
        answer["structuredContent"]["apps"] = listed;
        answer["_meta"]["ui"] = ui;
        return Ok(());
    }
    // An app's page as recorded: its app page view's, drawn over the
    // recorded scope, where it was drawn for an account; else as anyone
    // sees it, with no account's part, which the recorded data does not
    // hold.
    if tool == Some("describe_app") {
        if answer["_meta"]["ui"].is_object() {
            return Ok(());
        }
        let structured = &answer["structuredContent"];
        let domain = structured["domain"]
            .as_str()
            .ok_or("the answer names no domain")?
            .to_string();
        if let Some(v) = view::for_domain(&domain).filter(|_| structured["actor"].is_object()) {
            answer["_meta"]["ui"] = page_ui(v, structured, viewer.as_deref());
            return Ok(());
        }
        let name = structured["name"]
            .as_str()
            .map_or_else(|| apps::name(&domain), str::to_string);
        let origin = structured["icon"]
            .as_str()
            .and_then(|i| i.strip_suffix(&format!("/icon/{domain}")))
            .unwrap_or("http://localhost:8787")
            .to_string();
        let entries = apps::entries(&domain, None);
        answer["_meta"]["ui"] = app_ui(&domain, &name, &origin, &entries, None);
        return Ok(());
    }
    let chosen = match &shown {
        Value::Null => None,
        shown => {
            let trusted = shown["trusted"] == true;
            let mut v = view::parse(&shown["doc"], trusted).map_err(|p| view::error_text(&p))?;
            if let Some(origins) = shown["origins"].as_array().filter(|_| trusted) {
                v.origins = origins
                    .iter()
                    .filter_map(|o| o.as_str().map(str::to_string))
                    .collect();
            }
            let mode = shown["mode"]
                .as_str()
                .ok_or("_meta.view has no mode")?
                .to_string();
            Some((v, trusted, mode))
        }
    };
    let structured = &answer["structuredContent"];
    let read = lexicon_and_handles(&lexicon, &handles);
    let ui = chosen
        .as_ref()
        .and_then(|(v, trusted, mode)| {
            view_ui(
                v,
                *trusted,
                mode,
                structured,
                arguments,
                viewer.as_deref(),
                read,
            )
        })
        .unwrap_or_else(|| {
            if structured.get("response").is_some() {
                json_ui(structured)
            } else {
                let list = tool != Some("get_record");
                generic_records_ui(list, structured, arguments, &lexicon, &handles)
            }
        });
    answer["_meta"]["ui"] = ui;
    Ok(())
}

/// The origin of the server that recorded a `describe_repo` answer: its
/// profile's pictures' proxy (the server's own blob URLs), else HUD's
/// default, `http://localhost:8787`.
fn recorded_origin(structured: &Value) -> String {
    let value = &structured["profile"]["value"];
    ["avatar", "banner"]
        .iter()
        .flat_map(|k| [&value[*k]["proxy"], &value[*k]["url"]])
        .filter_map(Value::as_str)
        .filter(|u| u.contains("/blob/"))
        .find_map(|u| url::Url::parse(u).ok())
        .map(|u| u.origin().ascii_serialization())
        .unwrap_or_else(|| "http://localhost:8787".to_string())
}

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

    #[test]
    fn repo_views_and_text() {
        let collections: Vec<String> = [
            "app.bsky.actor.profile",
            "app.bsky.feed.post",
            "com.example.thing",
            "site.standard.document",
            "fm.plyr.like",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        // Only those it has, in its own order; a post opens as its
        // thread, drawn by no collection view.
        assert_eq!(
            repo_views(&collections),
            [
                json!({ "collection": "site.standard.document", "description": "Blog posts (standard.site documents)" }),
                json!({ "collection": "fm.plyr.like", "description": "plyr.fm likes, as a playlist" }),
            ]
        );
        assert!(repo_views(&collections[2..3]).is_empty());
        let who = Identity {
            did: "did:plc:meri".into(),
            handle: Some("meri.garden".into()),
            pds: "https://pds.example".into(),
        };
        let profile =
            json!({ "value": { "displayName": "Meri\n", "description": "my bio, all of it" } });
        let views = repo_views(&collections[..4]);
        let text = repo_text(&who, &profile, &views, 87);
        assert_eq!(
            text,
            "Meri (meri.garden, did:plc:meri) on https://pds.example. Views: Blog posts (standard.site documents). 87 collections."
        );
        assert!(!text.contains("bio") && !text.contains("com.example"));
        // With no profile, the handle; with no views, the count alone.
        assert_eq!(
            repo_text(&who, &Value::Null, &[], 1),
            "meri.garden (did:plc:meri) on https://pds.example. 1 collection."
        );
        let unverified = Identity {
            handle: None,
            ..who
        };
        assert_eq!(
            repo_text(&unverified, &Value::Null, &[], 0),
            "did:plc:meri on https://pds.example. No collections."
        );
    }

    #[test]
    fn profiles() {
        let found = crate::pds::Record {
            uri: "at://did:plc:meri/app.bsky.actor.profile/self".into(),
            cid: "c".into(),
            value: json!({ "displayName": "Meri", "avatar": { "$type": "blob",
                "ref": { "$link": "bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy" },
                "mimeType": "image/jpeg", "size": 10 } }),
        };
        let p = profile_rec(
            Ok(found),
            Urls::proxy("https://hud.example"),
            "did:plc:meri",
        );
        assert_eq!(p["uri"], "at://did:plc:meri/app.bsky.actor.profile/self");
        assert_eq!(
            p["value"]["avatar"]["url"],
            "https://hud.example/blob/did:plc:meri/bafkreibme22gw2h7y2h7tg2fhqotaqjucnbc24deqo72b6mkl2egezxhvy"
        );
        // Missing or unreadable is null, never an error.
        assert_eq!(
            profile_rec(
                Err("No record at …".into()),
                Urls::proxy("https://hud.example"),
                "did:plc:meri"
            ),
            Value::Null
        );
    }

    fn strings(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    /// Every Text's and Link's words in a tree, in order.
    fn words(tree: &Value) -> Vec<String> {
        fn walk(v: &Value, out: &mut Vec<String>) {
            match v {
                Value::Object(o) => {
                    match o.get("c").and_then(Value::as_str) {
                        Some("Text") => out.push(
                            v["p"]["runs"]
                                .as_array()
                                .into_iter()
                                .flatten()
                                .filter_map(|r| r["text"].as_str())
                                .collect(),
                        ),
                        Some("Link") => out.push(v["p"]["label"].as_str().unwrap().to_string()),
                        _ => {}
                    }
                    o.values().for_each(|v| walk(v, out));
                }
                Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
                _ => {}
            }
        }
        let mut out = Vec::new();
        walk(tree, &mut out);
        out
    }

    /// A profile shows the apps the account uses, a section for each a
    /// bundled view adds to profiles and that answered, in the views'
    /// order; no collection is shown, nor anything opening them; the tree
    /// is held to its lexicon.
    #[test]
    fn a_profile_shows_the_apps_it_uses() {
        let did = "did:plc:meri";
        let collections = strings(&[
            "app.bsky.actor.profile",
            "app.bsky.feed.post",
            "com.example.thing",
            "site.standard.document",
            "fm.plyr.like",
        ]);
        let plan = planned(did, &collections, false);
        let titles: Vec<&str> = plan.iter().map(|p| p.title.as_str()).collect();
        assert_eq!(titles, ["Bluesky", "Liked on plyr.fm", "Blog"]);
        // The author feed, as the account's DID, its posts alone; "See
        // all" the same at its usual length.
        assert_eq!(
            plan[0].call,
            json!({ "name": "query", "args": { "method": "app.bsky.feed.getAuthorFeed",
                "params": { "actor": did, "filter": "posts_no_replies", "limit": 3 } } })
        );
        assert_eq!(
            plan[0].see_all["args"]["params"],
            json!({ "actor": did, "filter": "posts_no_replies" })
        );
        assert_eq!(
            plan[2].call,
            json!({ "name": "list_records", "args": { "actor": did, "collection": "site.standard.document", "limit": 3 } })
        );
        assert_eq!(
            plan[2].see_all,
            json!({ "name": "list_records", "args": { "actor": did, "collection": "site.standard.document" } })
        );
        // Sections only for the apps it uses.
        assert!(planned(did, &strings(&["com.example.thing"]), false).is_empty());
        let titles = |c: &[&str]| -> Vec<String> {
            planned(did, &strings(c), false)
                .into_iter()
                .map(|p| p.title)
                .collect()
        };
        assert_eq!(titles(&["app.bsky.graph.follow"]), ["Bluesky"]);
        assert_eq!(titles(&["fm.plyr.list"]), ["plyr.fm"]);
        // knotless's, its repositories, for an account using knotless.
        assert_eq!(titles(&["dev.knotless.issue"]), ["knotless"]);
        let repos = planned(did, &strings(&["dev.knotless.repo"]), false);
        assert_eq!(
            repos[0].call,
            json!({ "name": "query", "args": { "method": "dev.knotless.getActorRepos",
                "params": { "actor": did } } })
        );
        // plyr.fm's failed: left out.
        let trees: Vec<Option<Value>> = plan
            .iter()
            .map(|p| {
                (p.title != "Liked on plyr.fm").then(|| {
                    json!({ "c": "Text", "p": { "runs": [{ "text": format!("{} drawn", p.title) }], "style": "body" } })
                })
            })
            .collect();
        let sections = answered(plan, trees);
        assert_eq!(sections.len(), 2);
        let structured = json!({ "did": did, "handle": "meri.garden", "pds": "https://pds.example/",
            "collections": collections, "views": [],
            "profile": { "uri": format!("at://{did}/app.bsky.actor.profile/self"), "cid": "c",
                "value": { "displayName": "Meri", "description": "bio",
                    "avatar": { "url": "https://cdn.example/a@jpeg", "proxy": "https://hud.example/blob/did:plc:meri/a" } } } });
        let ui = profile_ui(&structured, "https://hud.example", &[], sections);
        assert_eq!(ui::check(&ui), Ok(()));
        assert_eq!(
            (&ui["title"], &ui["trusted"]),
            (&json!("Meri"), &json!(true))
        );
        let k = ui["root"]["k"].as_array().unwrap();
        assert_eq!(k[0]["c"], "Profile");
        assert_eq!(
            (
                &k[0]["p"]["name"],
                &k[0]["p"]["handle"],
                &k[0]["p"]["descriptionRuns"]
            ),
            (
                &json!("Meri"),
                &json!("meri.garden"),
                &json!([{ "text": "bio" }])
            )
        );
        assert_eq!(
            k[0]["p"]["avatar"],
            json!({ "src": "https://cdn.example/a@jpeg", "fallback": "https://hud.example/blob/did:plc:meri/a" })
        );
        assert_eq!(words(&k[1]), ["Hosted on pds.example"]);
        // The apps HUD draws something of, the most collections first, each
        // its icon and name; example.com, which no view draws, is not one.
        assert_eq!(k[2]["p"]["style"], "inline");
        let apps = k[2]["items"].as_array().unwrap();
        let names: Vec<Vec<String>> = apps.iter().map(words).collect();
        assert_eq!(names, [["Bluesky"], ["plyr.fm"], ["standard.site"]]);
        assert_eq!(apps[0]["k"][0]["k"][0]["p"]["size"], "icon");
        assert_eq!(
            apps[0]["k"][0]["k"][0]["p"]["src"]["src"],
            "https://hud.example/icon/bsky.app"
        );
        // Each opens its app's page, with this account's part in it.
        assert_eq!(
            apps[0]["open"]["call"],
            json!({ "name": "describe_app", "args": { "domain": "bsky.app", "actor": did } })
        );
        // The sections: their app's icon, title and "See all" over the tree.
        assert_eq!(words(&k[3]), ["Bluesky", "See all", "Bluesky drawn"]);
        assert_eq!(
            k[3]["k"][0]["k"][2]["p"]["open"]["call"]["args"]["method"],
            "app.bsky.feed.getAuthorFeed"
        );
        assert_eq!(words(&k[4]), ["Blog", "See all", "Blog drawn"]);
        assert_eq!(k.len(), 5);
        // With no section answered, the head and apps alone; nothing opens
        // a collection.
        let bare = profile_ui(&structured, "https://hud.example", &[], Vec::new());
        assert_eq!(ui::check(&bare), Ok(()));
        assert_eq!(bare["root"]["k"].as_array().unwrap().len(), 3);
        let drawn = bare.to_string();
        assert!(!drawn.contains("list_records") && !drawn.contains("collection"));
        // Apps no view draws, nor any app at all: no row.
        let unknown = profile_ui(
            &json!({ "did": did, "handle": null, "pds": "https://pds.example", "profile": null,
                     "collections": ["com.example.thing", "chat.bsky.actor.declaration"] }),
            "https://hud.example",
            &[],
            Vec::new(),
        );
        assert_eq!(ui::check(&unknown), Ok(()));
        assert!(!unknown.to_string().contains("describe_app"));
        assert!(words(&unknown).contains(&did.to_string()));
        let empty = profile_ui(
            &json!({ "did": did, "collections": [] }),
            "https://hud.example",
            &[],
            Vec::new(),
        );
        assert!(words(&empty).contains(&"This repository has no records.".to_string()));
        // A recorded answer is resolved so, its icons on the server that
        // recorded it.
        assert_eq!(recorded_origin(&structured), "https://hud.example");
        let mut answer = json!({ "content": [], "structuredContent": structured,
            "_meta": { "view": null, "lexicon": null, "handles": {} } });
        resolve_answer(
            &mut answer,
            Some("describe_repo"),
            Some(&json!({ "actor": did })),
        )
        .unwrap();
        assert_eq!(answer["_meta"], json!({ "ui": bare }));
        // Its data lists its apps as its profile's row has them.
        assert_eq!(
            answer["structuredContent"]["apps"],
            json!([
                { "domain": "bsky.app", "name": "Bluesky", "icon": "https://hud.example/icon/bsky.app", "count": 2 },
                { "domain": "example.com", "name": "example.com", "icon": "https://hud.example/icon/example.com", "count": 1 },
                { "domain": "plyr.fm", "name": "plyr.fm", "icon": "https://hud.example/icon/plyr.fm", "count": 1 },
                { "domain": "standard.site", "name": "standard.site", "icon": "https://hud.example/icon/standard.site", "count": 1 },
            ])
        );
        assert_eq!(
            apps_listed(&collections, "https://hud.example"),
            answer["structuredContent"]["apps"]
        );
    }

    /// Signed in, a profile has a Message head section for anyone,
    /// whatever apps they use, drawn under its head untitled; signed out,
    /// none.
    #[test]
    fn a_message_button_heads_a_profile_signed_in() {
        let did = "did:plc:meri";
        let collections = strings(&["app.bsky.feed.post"]);
        let heads = |signed_in| -> Vec<Value> {
            planned(did, &collections, signed_in)
                .into_iter()
                .filter(|p| p.head)
                .map(|p| p.call)
                .collect()
        };
        assert_eq!(
            heads(true),
            [
                json!({ "name": "query", "args": { "method": "chat.bsky.convo.getConvoAvailability",
                "params": { "members": [did] } } })
            ]
        );
        assert!(heads(false).is_empty());
        let structured = json!({ "did": did, "handle": "meri.test", "pds": "https://pds.example",
            "collections": collections, "profile": null });
        let button = json!({ "c": "Link", "p": { "label": "Message", "style": "button" } });
        let plan = planned(did, &collections, true);
        let sections = plan.into_iter().map(|p| (p, button.clone())).collect();
        let ui = profile_ui(&structured, "https://hud.example", &[], sections);
        assert_eq!(ui::check(&ui), Ok(()));
        let k = ui["root"]["k"].as_array().unwrap();
        let at = k.iter().position(|n| *n == button).unwrap();
        assert!(
            k[..at].iter().any(|n| n["c"] == "Profile"),
            "under the head"
        );
        assert_eq!(at, k.iter().position(|n| n["c"] == "Profile").unwrap() + 2);
    }

    /// A profile's recent activity: the newest record of each collection a
    /// bundled view names an activity of, in their apps' order; each what
    /// it did, by its label or else its noun, and when, by its createdAt
    /// or else its TID; newest first, six at most, a collection without
    /// an activity or whose read failed adding nothing; drawn after the
    /// apps as rows opening each record, held to its lexicon.
    #[test]
    fn a_profile_shows_recent_activity() {
        let did = "did:plc:meri";
        let collections = strings(&[
            "app.bsky.feed.post",
            "app.bsky.feed.repost",
            "com.example.thing",
            "dev.knotless.repo",
            "site.standard.document",
        ]);
        assert_eq!(
            active(&collections),
            strings(&[
                "app.bsky.feed.post",
                "dev.knotless.repo",
                "site.standard.document"
            ])
        );
        // Only views whose label is the record's own words name an
        // activity: a collection view's, or a method view's records'.
        for b in view::bundled() {
            let labels = b
                .view
                .activity
                .as_ref()
                .map(|_| &b.view.doc["list"]["summary"]["label"]["$"])
                .into_iter()
                .chain(
                    b.view.doc["records"]
                        .as_array()
                        .into_iter()
                        .flatten()
                        .filter(|r| r["activity"].is_object())
                        .map(|r| &r["activity"]["label"]["$"]),
                );
            for label in labels {
                assert!(label.as_str().unwrap().starts_with("value."), "{}", b.id);
            }
        }
        // The verbs the record views had, carried over; a release's gone,
        // as nothing routes one.
        let verbs: Vec<(&str, Option<&str>)> = [
            "app.bsky.feed.post",
            "app.bsky.feed.repost",
            "social.grain.gallery",
            "dev.knotless.repo",
            "dev.knotless.issue",
            "dev.knotless.pull",
            "dev.knotless.release",
            "fm.plyr.list",
            "site.standard.document",
        ]
        .into_iter()
        .map(|c| (c, view::activity(c).map(|(verb, _)| verb)))
        .collect();
        assert_eq!(
            verbs,
            [
                ("app.bsky.feed.post", Some("Posted")),
                ("app.bsky.feed.repost", None),
                ("social.grain.gallery", Some("Posted")),
                ("dev.knotless.repo", Some("Created")),
                ("dev.knotless.issue", Some("Opened")),
                ("dev.knotless.pull", Some("Opened")),
                ("dev.knotless.release", None),
                ("fm.plyr.list", Some("Made")),
                ("site.standard.document", Some("Published")),
            ]
        );
        let rec = |c: &str, rkey: &str, value: Value| json!({ "uri": format!("at://{did}/{c}/{rkey}"), "cid": "c", "value": value });
        let post = |rkey: &str, minute: u32, text: &str| {
            let at = format!("2026-11-16T10:{minute:02}:00.000Z");
            rec(
                "app.bsky.feed.post",
                rkey,
                json!({ "text": text, "createdAt": at }),
            )
        };
        let tid =
            |iso: &str| atproto::tid::tid_from(datetime_millis(iso).unwrap() as u64 * 1000, 0);
        let doc = tid("2026-11-16T10:30:00.000Z");
        let read = vec![
            Some((
                "app.bsky.feed.post".to_string(),
                vec![
                    post("a", 1, "main's where the posts go"),
                    post("b", 2, ""),
                    post("c", 3, "three"),
                    post("d", 4, "four"),
                    post("e", 5, "five"),
                    post("f", 6, "six"),
                    post(
                        "g",
                        7,
                        "a line\nthen another line that runs on far past what one row of activity holds",
                    ),
                    // Neither a createdAt nor a TID: left out.
                    rec("app.bsky.feed.post", "self", json!({ "text": "when?" })),
                ],
            )),
            // No activity: nothing.
            Some((
                "app.bsky.feed.repost".to_string(),
                vec![rec(
                    "app.bsky.feed.repost",
                    "r",
                    json!({ "createdAt": "2026-11-16T11:00:00Z" }),
                )],
            )),
            // Its read failed.
            None,
            // Its time from its TID.
            Some((
                "site.standard.document".to_string(),
                vec![rec(
                    "site.standard.document",
                    &doc,
                    json!({ "title": "Coast" }),
                )],
            )),
            // Its createdAt at an offset, 10:20 UTC.
            Some((
                "dev.knotless.repo".to_string(),
                vec![rec(
                    "dev.knotless.repo",
                    "x",
                    json!({ "name": "hud", "createdAt": "2026-11-16T12:20:00+02:00" }),
                )],
            )),
        ];
        let shown = recent(read);
        let said: Vec<&str> = shown.iter().map(|a| a.words.as_str()).collect();
        assert_eq!(
            said,
            [
                "Published “Coast”",
                "Created “hud”",
                "Posted “a line then another line that runs on far past w…”",
                "Posted “six”",
                "Posted “five”",
                "Posted “four”",
            ]
        );
        assert_eq!(shown[0].when, "2026-11-16T10:30:00.000Z");
        assert_eq!(shown[1].when, "2026-11-16T12:20:00+02:00");
        assert_eq!(shown[0].domain, "standard.site");
        assert_eq!(
            shown[0].uri,
            format!("at://{did}/site.standard.document/{doc}")
        );
        // A record lacking its label is named by its noun.
        let unlabelled = recent(vec![Some((
            "app.bsky.feed.post".to_string(),
            vec![post("b", 2, "")],
        ))]);
        assert_eq!(unlabelled[0].words, "Posted a post");
        assert!(recent(vec![None]).is_empty());

        let structured = json!({ "did": did, "handle": "meri.garden", "pds": "https://pds.example/",
            "collections": collections, "views": [], "profile": null });
        let ui = profile_ui(&structured, "https://hud.example", &shown, Vec::new());
        assert_eq!(ui::check(&ui), Ok(()));
        let k = ui["root"]["k"].as_array().unwrap();
        // Right after the apps' row, before the rest.
        let apps_row = k.iter().position(|n| n["p"]["style"] == "inline").unwrap();
        let section = &k[apps_row + 1];
        assert_eq!(words(&section["k"][0]), ["Recent activity"]);
        assert!(!words(section).contains(&"See all".to_string()));
        assert_eq!(section["k"][1]["p"]["style"], "rows");
        let items = section["k"][1]["items"].as_array().unwrap();
        assert_eq!(items.len(), 6);
        let row = &items[0]["k"][0]["k"];
        assert_eq!(
            row[0]["p"]["src"]["src"],
            "https://hud.example/icon/standard.site"
        );
        assert_eq!(words(&items[0]), ["Published “Coast”"]);
        assert_eq!(
            row[2],
            json!({ "c": "Time", "p": { "value": "2026-11-16T10:30:00.000Z" } })
        );
        assert_eq!(
            items[0]["open"]["call"],
            json!({ "name": "get_record", "args": { "uri": shown[0].uri } })
        );
        // None with no activity.
        let none = profile_ui(&structured, "https://hud.example", &[], Vec::new());
        assert!(!words(&none).contains(&"Recent activity".to_string()));
    }

    /// An app's page: its head, where to go in it (those needing someone
    /// signed in only so), and an account's part, its sections for this
    /// app alone; every tree held to its lexicon.
    #[test]
    fn an_app_page() {
        let origin = "https://hud.example";
        let out = apps::entries("bsky.app", None);
        let page = app_ui("bsky.app", "Bluesky", origin, &out, None);
        assert_eq!(ui::check(&page), Ok(()));
        assert_eq!(
            (&page["title"], &page["trusted"]),
            (&json!("Bluesky"), &json!(true))
        );
        assert_eq!(
            words(&page),
            ["Bluesky", "bsky.app", "Open bsky.app", "Go to", "Discover"]
        );
        let k = page["root"]["k"].as_array().unwrap();
        assert_eq!(
            k[0]["k"][0]["k"][0]["p"]["src"]["src"],
            "https://hud.example/icon/bsky.app"
        );
        assert_eq!(
            k[0]["k"][1]["p"]["open"],
            json!({ "url": "https://bsky.app" })
        );
        assert_eq!(
            k[1]["k"][1]["items"][0]["open"]["call"]["args"]["method"],
            "app.bsky.feed.getFeed"
        );
        assert_eq!(
            app_text("bsky.app", "Bluesky", &out, None),
            "Bluesky (bsky.app). Go to: Discover."
        );
        // Signed in, the person's own too.
        let mine = apps::entries("bsky.app", Some(("did:plc:me", Some("me.test"))));
        let page = app_ui("bsky.app", "Bluesky", origin, &mine, None);
        assert_eq!(ui::check(&page), Ok(()));
        assert_eq!(
            words(&page)[4..],
            [
                "Posts",
                "Discover",
                "Saved feeds",
                "Notifications",
                "Following"
            ]
        );
        // An account's part: its sections of this app alone, never its
        // collections.
        let did = "did:plc:paul";
        let collections = strings(&[
            "app.bsky.actor.profile",
            "app.bsky.feed.post",
            "fm.plyr.like",
            "site.standard.document",
        ]);
        let plan: Vec<Planned> = planned(did, &collections, false)
            .into_iter()
            .filter(|p| p.domain == "bsky.app")
            .collect();
        assert_eq!(plan.len(), 1);
        let trees = vec![Some(text_node("Posts drawn", "body"))];
        let here = Here {
            who: "P(aul) Frazee".into(),
            collections: collections[..2].to_vec(),
            sections: answered(plan, trees),
        };
        let page = app_ui("bsky.app", "Bluesky", origin, &out, Some(&here));
        assert_eq!(ui::check(&page), Ok(()));
        let part = page["root"]["k"].as_array().unwrap().last().unwrap();
        assert_eq!(
            words(part),
            ["P(aul) Frazee here", "Bluesky", "See all", "Posts drawn"]
        );
        assert_eq!(
            part["k"][1]["k"][0]["k"][1]["p"]["open"]["call"]["args"]["method"],
            "app.bsky.feed.getAuthorFeed"
        );
        assert!(!page.to_string().contains("list_records"));
        assert_eq!(
            app_text("bsky.app", "Bluesky", &out, Some(&here)),
            "Bluesky (bsky.app). Go to: Discover. P(aul) Frazee here: 2 collections."
        );
        // An app with nowhere to go, and no account, or one with no
        // section for it: a line saying so.
        let bare = app_ui("leaflet.pub", "leaflet.pub", origin, &[], None);
        assert_eq!(ui::check(&bare), Ok(()));
        assert_eq!(bare["root"]["k"].as_array().unwrap().len(), 2);
        let none = Here {
            who: "Yours".into(),
            collections: strings(&["pub.leaflet.document"]),
            sections: Vec::new(),
        };
        let empty = app_ui("leaflet.pub", "leaflet.pub", origin, &[], Some(&none));
        assert_eq!(empty, bare);
        // With somewhere to go, that alone.
        let quiet = app_ui("bsky.app", "Bluesky", origin, &out, Some(&none));
        assert_eq!(quiet, app_ui("bsky.app", "Bluesky", origin, &out, None));
        // A recorded answer keeps its tree; one without is drawn as anyone
        // sees it.
        let structured = json!({ "domain": "bsky.app", "name": "Bluesky", "icon": "https://hud.example/icon/bsky.app" });
        let mut answer = json!({ "structuredContent": structured, "_meta": {} });
        resolve_answer(&mut answer, Some("describe_app"), None).unwrap();
        assert_eq!(
            answer["_meta"]["ui"],
            app_ui("bsky.app", "Bluesky", origin, &out, None)
        );
        let mut kept = json!({ "structuredContent": structured, "_meta": { "ui": page.clone() } });
        resolve_answer(&mut kept, Some("describe_app"), None).unwrap();
        assert_eq!(kept["_meta"]["ui"], page);
    }

    /// knotless's page is its own view's (`knotless-app`): My work with
    /// its counts, each row opening its query, Favorites from the stars and
    /// Recent, a tree the clients draw, signed in on one's own page or not;
    /// an app with no page view, or no account to draw one for, has the
    /// generic page.
    #[test]
    fn knotless_has_its_own_page() {
        let origin = "https://hud.example";
        let (did, handle) = ("did:plc:chad", Some("chadtmiller.com"));
        let app = json!({ "domain": "knotless.dev", "name": "knotless",
                          "icon": apps::icon(origin, "knotless.dev") });
        let v = view::for_domain("knotless.dev").unwrap();
        let item = |n: usize| {
            json!({
            "item": { "uri": format!("at://{did}/dev.knotless.issue/{n}"), "kind": "issue",
                      "state": "open", "title": format!("Issue {n}"), "createdAt": "2026-11-16T10:00:00.000Z",
                      "author": { "did": did, "handle": "chadtmiller.com" }, "comments": 0 },
            "repo": { "did": did, "handle": "chadtmiller.com", "name": "knotless" } })
        };
        let joins = json!({
            "issues": { "items": (0..50).map(item).collect::<Vec<_>>(), "cursor": "50" },
            "pulls": { "items": [] },
            "stars": { "repos": [{ "uri": format!("at://{did}/dev.knotless.repo/monolith"),
                                   "owner": { "did": did, "handle": "chadtmiller.com" },
                                   "name": "monolith", "description": "An atproto PDS",
                                   "createdAt": "2026-01-01T00:00:00.000Z" }] },
            "recent": { "events": [{ "createdAt": "2026-11-16T10:00:00.000Z",
                "actor": { "did": did, "handle": "chadtmiller.com" },
                "repo": { "did": did, "handle": "chadtmiller.com", "name": "knotless" },
                "action": { "$type": "dev.knotless.getFeed#opened",
                            "subject": format!("at://{did}/dev.knotless.issue/1"),
                            "title": "Issue 1", "subjectState": "open" } }] }
        });
        let me = Some((did, handle));
        for (me, mine) in [(me, true), (None, false)] {
            let entries = apps::entries("knotless.dev", me);
            let mut scope = page_scope(app.clone(), (did, handle), me, &entries);
            assert_eq!(scope["mine"], mine);
            assert_eq!(
                scope["actor"],
                json!({ "did": did, "handle": "chadtmiller.com" })
            );
            scope["joins"] = joins.clone();
            let page = page_ui(v, &scope, None);
            assert_eq!(ui::check(&page), Ok(()), "{page:#}");
            assert_eq!(page["title"], "knotless");
            let drawn = page.to_string();
            for words in [
                "Issues",
                "Pull requests",
                "Review requests",
                "Starred",
                "Favorites",
                "monolith",
                "Recent",
            ] {
                assert!(drawn.contains(&format!("\"{words}\"")), "{words}: {page:#}");
            }
            assert_eq!(drawn.contains("\"My work\""), mine);
            assert_eq!(drawn.contains("\"Notifications\""), mine);
            // Each row opens its query, for the page's account.
            for part in [
                "\"method\":\"dev.knotless.listActorItems\"",
                "\"relation\":\"review\"",
                "\"method\":\"dev.knotless.getActorStars\"",
                "\"actor\":\"did:plc:chad\"",
            ] {
                assert!(drawn.contains(part), "{part}: {page:#}");
            }
            // A recorded answer is drawn as the tool drew it.
            let mut answer = json!({ "structuredContent": scope, "_meta": {} });
            resolve_answer(&mut answer, Some("describe_app"), None).unwrap();
            assert_eq!(answer["_meta"]["ui"], page);
        }
        // With no account, the generic page; so too an app with no page view.
        let mut answer = json!({ "structuredContent": app, "_meta": {} });
        resolve_answer(&mut answer, Some("describe_app"), None).unwrap();
        let entries = apps::entries("knotless.dev", None);
        assert_eq!(
            answer["_meta"]["ui"],
            app_ui("knotless.dev", "knotless", origin, &entries, None)
        );
        assert!(view::for_domain("bsky.chat").is_none());
    }

    /// Grain's page pages its galleries (`pages`): their Covers is the page
    /// list, its `next` `describe_app` from the cursor; a page more, its
    /// join alone answered, draws those galleries as the page list, and
    /// ends where they have no cursor.
    #[test]
    fn grain_pages_its_galleries() {
        fn page_lists(n: &Value) -> Vec<&Value> {
            let mut found: Vec<&Value> =
                (n["p"]["page"] == true).then_some(n).into_iter().collect();
            for k in n["k"].as_array().into_iter().flatten() {
                found.extend(page_lists(k));
            }
            found
        }
        let did = "did:plc:dan";
        let v = view::for_domain("grain.social").unwrap();
        let gallery = |n: usize| {
            json!({ "uri": format!("at://{did}/social.grain.gallery/{n}"), "title": format!("Gallery {n}"),
                    "items": [], "creator": { "did": did, "handle": "dan.example" } })
        };
        let app = json!({ "domain": "grain.social", "name": "Grain",
                          "icon": apps::icon("https://hud.example", "grain.social") });
        let mut scope = page_scope(app, (did, Some("dan.example")), None, &[]);
        scope["joins"] = json!({
            "profile": { "did": did, "handle": "dan.example", "galleryCount": 20 },
            "galleries": { "items": (0..18).map(gallery).collect::<Vec<_>>(), "cursor": "c18" },
        });
        let page = page_ui(v, &scope, None);
        assert_eq!(ui::check(&page), Ok(()), "{page:#}");
        assert_eq!(
            page["next"],
            json!({ "name": "describe_app",
                    "args": { "domain": "grain.social", "actor": did, "cursor": "c18" } })
        );
        let lists = page_lists(&page["root"]);
        assert_eq!(lists.len(), 1, "{page:#}");
        assert_eq!(lists[0]["c"], "Covers");
        assert_eq!(lists[0]["items"].as_array().map(Vec::len), Some(18));
        // The page more: the galleries alone, the last of them.
        scope["joins"] =
            json!({ "galleries": { "items": (18..20).map(gallery).collect::<Vec<_>>() } });
        let more = page_ui(v, &scope, None);
        assert!(more.get("next").is_none(), "{more:#}");
        let lists = page_lists(&more["root"]);
        assert_eq!(lists.len(), 1, "{more:#}");
        assert_eq!(lists[0]["items"][1]["title"], "Gallery 19");
    }

    /// A view's measure reaches its tree where it is wide or full; the
    /// reading width, said or not, is left unsaid. With `measureWhen`, the
    /// first case whose `when` the answer holds decides it, else `measure`.
    #[test]
    fn a_view_says_how_wide_it_would_be_drawn() {
        let b = view::bundled()
            .iter()
            .find(|b| b.id == "grain-feed")
            .unwrap();
        let layout = json!({ "layout": { "component": "Text", "props": { "value": "x" } } });
        for (measure, want) in [
            (None, None),
            (Some("content"), None),
            (Some("wide"), Some("wide")),
            (Some("full"), Some("full")),
        ] {
            let mut v = b.view.clone();
            v.doc["measure"] = measure.into();
            let ui = resolved_ui(
                &v,
                true,
                &layout,
                &json!({}),
                None,
                (None, ui::More::default()),
                None,
                (None, None),
            );
            assert_eq!(ui::check(&ui), Ok(()));
            assert_eq!(ui["measure"].as_str(), want, "{measure:?}");
        }
        let mut v = b.view.clone();
        v.doc["measure"] = json!("content");
        v.doc["measureWhen"] = json!([
            { "when": "params.camera", "measure": "wide" },
            { "when": "params.tag", "measure": "full" }
        ]);
        for (params, want) in [
            (
                json!({ "camera": "Ricoh GR II", "tag": "film" }),
                Some("wide"),
            ),
            (json!({ "tag": "film" }), Some("full")),
            (json!({ "camera": "" }), None),
            (json!({ "feed": "recent" }), None),
        ] {
            let ui = resolved_ui(
                &v,
                true,
                &layout,
                &json!({ "params": params }),
                None,
                (None, ui::More::default()),
                None,
                (None, None),
            );
            assert_eq!(ui["measure"].as_str(), want, "{params}");
        }
    }

    /// An account a bundled view names opens as its page in the view's app,
    /// where that app has one (so its mentions too, by the tree's `people`);
    /// in an app with none, or an inline view, as its profile across apps.
    #[test]
    fn an_account_opens_in_the_app_it_is_read_in() {
        let layout =
            json!({ "component": "Link", "props": { "href": { "$": "did" }, "label": "Dan" } });
        let scope = json!({ "did": "did:plc:dan" });
        let drawn = |id: &str, trusted: bool| {
            let b = view::bundled().iter().find(|b| b.id == id).unwrap();
            let ui = resolved_ui(
                &b.view,
                trusted,
                &json!({ "layout": layout }),
                &scope,
                None,
                (None, ui::More::default()),
                None,
                (None, None),
            );
            assert_eq!(ui::check(&ui), Ok(()));
            (
                ui["people"].clone(),
                ui["root"]["p"]["open"]["call"].clone(),
            )
        };
        let page = |domain: &str| json!({ "name": "describe_app", "args": { "domain": domain, "actor": "did:plc:dan" } });
        let whole = json!({ "name": "describe_repo", "args": { "actor": "did:plc:dan" } });
        assert_eq!(
            drawn("bsky-timeline", true),
            (json!("bsky.app"), page("bsky.app"))
        );
        assert_eq!(
            drawn("grain-feed", true),
            (json!("grain.social"), page("grain.social"))
        );
        assert_eq!(
            drawn("knotless-feed", true),
            (json!("knotless.dev"), page("knotless.dev"))
        );
        assert_eq!(drawn("plyr-likes", true), (Value::Null, whole.clone()));
        assert_eq!(drawn("bsky-chats", true), (Value::Null, whole.clone()));
        assert_eq!(drawn("bsky-timeline", false), (Value::Null, whole));
    }

    #[test]
    fn definitions_in_order() {
        let tools = definitions(None, true, "ui://records/view/test");
        let names: Vec<&str> = tools.iter().filter_map(|t| t["name"].as_str()).collect();
        assert_eq!(
            names,
            [
                "describe_repo",
                "describe_app",
                "describe_collection",
                "describe_method",
                "list_records",
                "get_record",
                "query"
            ]
        );
        for t in &tools {
            assert_eq!(t["inputSchema"]["additionalProperties"], json!(false));
            assert_eq!(t["annotations"]["readOnlyHint"], json!(true));
            let ui = t["_meta"]["ui"]["resourceUri"].as_str();
            assert_eq!(
                ui.is_some(),
                matches!(
                    t["name"].as_str().unwrap(),
                    "describe_repo" | "describe_app" | "list_records" | "get_record" | "query"
                ),
                "{}",
                t["name"]
            );
        }
        assert_eq!(
            tools[0]["inputSchema"]["properties"],
            json!({ "actor": tools[0]["inputSchema"]["properties"]["actor"] })
        );
        assert_eq!(tools[1]["inputSchema"]["required"], json!(["domain"]));
        let list = tools[4]["description"].as_str().unwrap();
        assert!(
            list.contains("site.standard.document: Blog posts"),
            "{list}"
        );
        assert!(!list.contains("social.grain.gallery"), "{list}");
        // A post opens as its thread.
        let get = tools[5]["description"].as_str().unwrap();
        assert!(
            get.contains("app.bsky.feed.post as app.bsky.feed.getPostThread"),
            "{get}"
        );
        assert!(get.contains("social.grain.gallery as social.grain.gallery.getGallery"));
        assert_eq!(
            tools[4]["inputSchema"]["properties"]["view"]["type"],
            "object"
        );
        let query = tools[6]["description"].as_str().unwrap();
        assert!(query.contains("app.bsky.feed.getFeed: "), "{query}");
        assert!(query.contains("social.grain.feed.getFeed: "), "{query}");
        assert!(!query.contains("social.grain.gallery: "), "{query}");
        assert!(query.contains("Public data only"), "{query}");
        // Sign-in on: the same seven, then the two that write.
        let asked = crate::scope::asked(crate::view::views(), true, false);
        let signed = definitions(Some(&asked), true, "ui://records/view/test");
        let names: Vec<&str> = signed.iter().filter_map(|t| t["name"].as_str()).collect();
        assert_eq!(
            names[..7],
            tools
                .iter()
                .filter_map(|t| t["name"].as_str())
                .collect::<Vec<_>>()[..]
        );
        assert_eq!(
            names[7..],
            [
                "create_record",
                "apply_writes",
                "delete_record",
                "canvas_list",
                "canvas_add",
                "canvas_place",
                "canvas_remove",
                "canvas_create",
                "send_interactions",
                "call_procedure",
                "link_card",
                "find_place"
            ]
        );
        let create = &signed[7]["annotations"];
        assert_eq!(
            (
                create["readOnlyHint"].clone(),
                create["destructiveHint"].clone(),
                create["idempotentHint"].clone()
            ),
            (json!(false), json!(false), json!(false))
        );
        assert_eq!(signed[8]["annotations"]["readOnlyHint"], json!(false));
        assert_eq!(signed[9]["annotations"]["destructiveHint"], json!(true));
        // The canvas's: they draw nothing; listing reads alone, removing
        // destroys.
        assert!(signed[7..15].iter().all(|t| t["_meta"].is_null()));
        assert_eq!(signed[10]["annotations"]["readOnlyHint"], json!(true));
        for t in &signed[11..15] {
            assert_eq!(t["annotations"]["readOnlyHint"], json!(false));
            assert_eq!(t["inputSchema"]["additionalProperties"], json!(false));
        }
        for t in &signed[10..14] {
            assert_eq!(t["inputSchema"]["properties"]["canvas"]["type"], "string");
        }
        assert_eq!(signed[11]["annotations"]["destructiveHint"], json!(false));
        assert_eq!(signed[12]["annotations"]["destructiveHint"], json!(false));
        assert_eq!(signed[13]["annotations"]["destructiveHint"], json!(true));
        assert_eq!(signed[14]["name"], "canvas_create");
        // The view's alone: hidden from the model.
        for t in &signed[15..] {
            assert_eq!(t["_meta"]["ui"]["visibility"], json!(["app"]));
        }
        // An instance serving Grain's apps alone, with no workspace: no
        // canvas, and no interactions, which none of its views sends; and
        // the writes name its collections alone.
        let grain = crate::operator::load(std::path::Path::new(view::GRAIN_APPS), false).unwrap();
        let asked = crate::scope::asked(&grain.views, false, false);
        let apps = definitions(Some(&asked), false, "ui://records/view/test");
        let names: Vec<&str> = apps.iter().filter_map(|t| t["name"].as_str()).collect();
        assert_eq!(
            names[7..],
            [
                "create_record",
                "apply_writes",
                "delete_record",
                "call_procedure",
                "link_card",
                "find_place"
            ]
        );
        let create = apps[7]["description"].as_str().unwrap();
        let (_, listed) = create.split_once("the ones HUD asks to write: ").unwrap();
        let (listed, _) = listed.split_once(". ").unwrap();
        assert!(
            listed.split(", ").all(|c| c.starts_with("social.grain.")),
            "{listed}"
        );
        assert!(listed.contains("social.grain.gallery"), "{listed}");
    }

    /// An instance serving its operator's apps alone has no canvas tools,
    /// and no `send_interactions` where none of its views sends them: a
    /// call of one is of no tool, as one of no name is.
    #[tokio::test]
    async fn an_apps_instance_has_no_canvas() {
        let path = std::path::Path::new(view::GRAIN_APPS);
        let grain = crate::operator::load(path, false).unwrap().views;
        let hud = crate::tests::hud_with("http://127.0.0.1:1", |c| {
            c.oauth = true;
            c.workspace = false;
            c.oauth_scope = crate::scope::asked(&grain, false, false);
        });
        for name in ["canvas_list", "canvas_create", "send_interactions"] {
            assert!(hud.call_tool(name, None, None).await.is_none(), "{name}");
        }
        let full = crate::tests::hud_with("http://127.0.0.1:1", |c| c.oauth = true);
        for name in ["canvas_list", "send_interactions"] {
            assert!(full.call_tool(name, None, None).await.is_some(), "{name}");
        }
    }

    #[test]
    fn arguments_checked() {
        let a = json!({ "actor": "x", "limit": 101, "extra": 1 });
        assert_eq!(
            Args::of(Some(&a), &["actor", "limit"]).err().as_deref(),
            Some("Unknown argument: extra")
        );
        let a = json!({ "actor": "x", "limit": 101 });
        let args = Args::of(Some(&a), &["actor", "limit"]).unwrap();
        assert!(args.limit(25).is_err());
        assert_eq!(Args::of(Some(&json!({})), &[]).unwrap().limit(12), Ok(12));
        assert!(Args::of(Some(&json!([])), &[]).is_err());
    }

    /// `me` is the signed-in account wherever an account is named: an
    /// actor, a query's `params.actor`, an at-uri's authority. Signed out,
    /// it asks for sign-in; arguments naming no `me` pass as they are.
    #[test]
    fn me_is_the_signed_in_account() {
        let did = "did:plc:me";
        let a = json!({ "actor": "@me", "collection": "app.bsky.feed.post" });
        assert_eq!(
            with_me(Some(&a), Some(did)),
            Ok(Some(
                json!({ "actor": did, "collection": "app.bsky.feed.post" })
            ))
        );
        let q = json!({ "method": "app.bsky.feed.getAuthorFeed", "params": { "actor": "me", "limit": 5 } });
        assert_eq!(
            with_me(Some(&q), Some(did)).unwrap().unwrap()["params"],
            json!({ "actor": did, "limit": 5 })
        );
        let u = json!({ "uri": "at://me/app.bsky.feed.post/3abc" });
        assert_eq!(
            with_me(Some(&u), Some(did)).unwrap().unwrap()["uri"],
            json!("at://did:plc:me/app.bsky.feed.post/3abc")
        );
        assert_eq!(with_me(Some(&a), None), Err(Refusal::SignIn));
        // A handle that merely starts so, or no `me` at all, is left alone.
        for other in [
            json!({ "actor": "meri.garden" }),
            json!({ "uri": "at://meri.garden/x/y" }),
            json!({}),
        ] {
            assert_eq!(with_me(Some(&other), None), Ok(None));
        }
    }

    #[test]
    fn views_chosen() {
        let none = json!({});
        let args = Args::of(Some(&none), &["view"]).unwrap();
        assert!(matches!(
            args.view("fm.plyr.like"),
            Ok(Some(Chosen::Bundled(_)))
        ));
        let bundled = args.view("fm.plyr.like").unwrap().unwrap();
        assert!(bundled.trusted());
        assert!(matches!(args.view("app.bsky.feed.like"), Ok(None)));
        let inline = json!({ "view": { "collection": "app.bsky.feed.post", "description": "Posts",
            "list": { "layout": { "component": "Text", "props": { "value": { "$": "value.text" } } } } } });
        let args = Args::of(Some(&inline), &["view"]).unwrap();
        let chosen = args.view("app.bsky.feed.post").unwrap().unwrap();
        let root = Value::Null;
        assert!(
            view_ctx(chosen.view(), chosen.trusted(), &root)
                .origins
                .is_empty()
        );
        assert!(!chosen.trusted());
        assert!(chosen.mode(false).is_none());
        // An origin a bundled view names, an inline view draws from too.
        let mut on_cdn = inline.clone();
        on_cdn["view"]["origins"] = json!(["https://cdn.bsky.app"]);
        let args = Args::of(Some(&on_cdn), &["view"]).unwrap();
        let chosen = args.view("app.bsky.feed.post").unwrap().unwrap();
        assert_eq!(
            view_ctx(chosen.view(), chosen.trusted(), &root).origins,
            ["https://cdn.bsky.app"]
        );
        let args = Args::of(Some(&inline), &["view"]).unwrap();
        assert_eq!(
            args.view("fm.plyr.like").err().as_deref(),
            Some(
                "Invalid view: 1 problem: view: draws app.bsky.feed.post, but the records are of fm.plyr.like"
            )
        );
        let bad = json!({ "view": { "collection": "app.bsky.feed.post", "description": "Posts",
            "origins": ["https://evil.example"], "list": { "layout": { "component": "Nope" } } } });
        let err = Args::of(Some(&bad), &["view"])
            .unwrap()
            .view("app.bsky.feed.post")
            .err()
            .unwrap();
        assert!(
            err.starts_with("Invalid view: 2 problems: view.origins[0]: "),
            "{err}"
        );
        // A query's view: inline, of that method alone; else the bundled one.
        assert!(matches!(
            Args::of(Some(&none), &["view"])
                .unwrap()
                .method_view("app.bsky.feed.getFeed"),
            Ok(Some(Chosen::Bundled(_)))
        ));
        assert!(args.method_view("app.bsky.feed.getFeed").is_err());
    }

    #[test]
    fn an_answer_with_its_view_resolves_as_the_tool_draws_it() {
        let chosen = Args::of(Some(&json!({})), &["view"])
            .unwrap()
            .view("site.standard.document")
            .unwrap()
            .expect("site.standard.document has a bundled view");
        assert!(chosen.trusted());
        let v = chosen.view();
        let did = "did:plc:ragtjsm2j2vknwkz3zp4oxrd";
        let structured = json!({ "did": did, "handle": "pfrazee.com", "collection": "site.standard.document",
            "records": [{ "uri": format!("at://{did}/site.standard.document/3l"), "cid": "bafyrei",
                "value": { "$type": "site.standard.document", "title": "hello", "publishedAt": "2026-11-14T19:00:00.000Z" } }],
            "cursor": "3l" });
        let arguments =
            json!({ "actor": "pfrazee.com", "collection": "site.standard.document", "limit": 6 });
        let (lexicon, handles) = (
            Value::Null,
            json!({ "did:plc:ragtjsm2j2vknwkz3zp4oxrd": "pfrazee.com" }),
        );
        let read = lexicon_and_handles(&lexicon, &handles);
        let drawn = view_ui(v, true, "list", &structured, Some(&arguments), None, read).unwrap();
        assert_eq!(drawn["title"], v.description.as_str());
        assert_eq!(drawn["next"]["args"]["cursor"], "3l");
        let mut answer = json!({ "content": [], "structuredContent": structured,
            "_meta": { "lexicon": lexicon, "handles": handles,
                       "view": { "doc": v.doc, "mode": "list", "trusted": true, "origins": v.origins } } });
        resolve_answer(&mut answer, Some("list_records"), Some(&arguments)).unwrap();
        assert_eq!(answer["_meta"], json!({ "ui": drawn }));
        // No view: the generic drawing, a page or one record.
        let mut bare = json!({ "structuredContent": answer["structuredContent"],
            "_meta": { "view": null, "lexicon": null, "handles": {} } });
        resolve_answer(&mut bare, Some("get_record"), None).unwrap();
        assert_eq!(
            bare["_meta"]["ui"],
            generic_records_ui(false, &structured, None, &Value::Null, &json!({}))
        );
    }

    /// An answer of `method`, as its lexicon allows one, drawn by its
    /// bundled view as the signed-in `did:plc:me`: the list's items.
    fn notifications_drawn(method: &str, response: Value, joins: Value) -> Vec<Value> {
        let docs: Vec<Arc<Value>> = crate::lexicon::all_bundled().cloned().collect();
        let doc = docs.iter().find(|d| d["id"] == method).unwrap();
        let def = crate::xrpc::query_def(method, doc).unwrap();
        let lexicons = crate::xrpc::lexicons_for(method, &docs);
        assert_eq!(
            crate::xrpc::output_problem(&lexicons, method, def, &response),
            None
        );
        let v = view::for_method(method).unwrap();
        let structured = json!({ "method": method, "service": v.service, "params": {},
                                 "response": response, "joins": joins });
        let args = json!({ "method": method });
        let none = (None, None);
        let drawn = view_ui(
            v,
            true,
            "query",
            &structured,
            Some(&args),
            Some("did:plc:me"),
            none,
        );
        let drawn = drawn.unwrap();
        assert_eq!(ui::check(&drawn), Ok(()));
        drawn["root"]["items"].as_array().unwrap().clone()
    }

    /// The query each item opens (its `{ method, params }`), the item's own
    /// first, then those of the lists within it, but no account's.
    fn queries_opened(item: &Value) -> Vec<Value> {
        fn walk(v: &Value, out: &mut Vec<Value>) {
            match v {
                Value::Object(o) => {
                    if let Some(args) = o.get("open").map(|open| &open["call"]["args"])
                        && args.get("method").is_some()
                    {
                        out.push(json!({ "method": args["method"], "params": args["params"] }));
                    }
                    o.values().for_each(|v| walk(v, out));
                }
                Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
                _ => {}
            }
        }
        let mut out = Vec::new();
        walk(item, &mut out);
        out
    }

    /// Bluesky's notifications: a like shows the post it likes, from the
    /// join, and opens it; a reply its own words, opening its thread; a
    /// follow opens nothing but its follower.
    #[test]
    fn bluesky_notifications_show_and_open_what_they_are_about() {
        let cid = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm";
        let mine = "at://did:plc:me/app.bsky.feed.post/3mine";
        let reply = "at://did:plc:bob/app.bsky.feed.post/3reply";
        let at = "2026-11-16T12:00:00.000Z";
        let author = |did: &str, handle: &str| json!({ "did": did, "handle": handle });
        let notification = |uri: &str, who: Value, reason: &str, record: Value| {
            json!({ "uri": uri, "cid": cid, "author": who, "reason": reason, "record": record,
                    "isRead": false, "indexedAt": at })
        };
        let response = json!({ "notifications": [
            notification("at://did:plc:alice/app.bsky.feed.like/3like", author("did:plc:alice", "alice.test"), "like",
                json!({ "$type": "app.bsky.feed.like", "subject": { "uri": mine, "cid": cid }, "createdAt": at })),
            notification(reply, author("did:plc:bob", "bob.test"), "reply",
                json!({ "$type": "app.bsky.feed.post", "text": "Nice one", "createdAt": at,
                        "reply": { "root": { "uri": mine, "cid": cid }, "parent": { "uri": mine, "cid": cid } } })),
            notification("at://did:plc:carol/app.bsky.graph.follow/3follow", author("did:plc:carol", "carol.test"), "follow",
                json!({ "$type": "app.bsky.graph.follow", "subject": "did:plc:me", "createdAt": at })),
        ] });
        let joins = json!({ "subjects": { "posts": [{ "uri": mine, "cid": cid, "author": author("did:plc:me", "me.test"),
            "record": { "$type": "app.bsky.feed.post", "text": "My post", "createdAt": at }, "indexedAt": at }] } });
        let items = notifications_drawn("app.bsky.notification.listNotifications", response, joins);
        let thread = |uri: &str| json!({ "method": "app.bsky.feed.getPostThread", "params": { "uri": uri } });
        assert_eq!(queries_opened(&items[0])[0], thread(mine));
        let liked = words(&items[0]);
        assert!(liked.contains(&"liked your post".into()) && liked.contains(&"My post".into()));
        assert!(items[1].get("open").is_none());
        assert_eq!(queries_opened(&items[1]), [thread(reply)]);
        assert!(words(&items[1]).contains(&"replied to you".into()));
        assert!(!words(&items[1]).contains(&"My post".into()));
        assert!(queries_opened(&items[2]).is_empty());
        assert!(words(&items[2]).contains(&"followed you".into()));
    }

    /// A Grain gallery's page head, from its recorded answer: its title by
    /// its photographer, the description it lacks said for it, its first
    /// photo, its canonical path, its structured data a posting with each
    /// photo; what reads nothing (the photo's alt, labels) left out. A
    /// view that is not trusted says no head; a mode with none, none.
    #[test]
    fn a_grain_gallery_says_its_head() {
        let recorded: Value =
            serde_json::from_str(include_str!("../../../harness/look/tools.json")).unwrap();
        let key = "query {\"method\":\"social.grain.gallery.getGallery\",\"params\":{\"gallery\":\"at://did:plc:bcgltzqazw5tb6k2g3ttenbj/social.grain.gallery/3mpgwvcrieu2d\"}}";
        let structured = &recorded["calls"][key]["structuredContent"];
        let v = view::for_method("social.grain.gallery.getGallery").unwrap();
        let args = json!({ "method": "social.grain.gallery.getGallery" });
        let drawn = |trusted: bool, v: &View| {
            let ui = view_ui(
                v,
                trusted,
                "query",
                structured,
                Some(&args),
                None,
                (None, None),
            );
            let ui = ui.unwrap();
            assert_eq!(ui::check(&ui), Ok(()));
            ui
        };
        let head = drawn(true, v)["head"].clone();
        let photo = &structured["response"]["gallery"]["items"][0]["fullsize"];
        assert_eq!(
            head["title"],
            "TMB Day 6: La Fouly to Col de la Forclaz by chad on Grain"
        );
        assert_eq!(
            head["description"],
            "A photo gallery by @chadtmiller.com on Grain."
        );
        assert_eq!(&head["image"], photo);
        let photo_url = photo.as_str().unwrap();
        let tree = drawn(true, v);
        assert!(
            tree["hero"]
                .as_str()
                .is_some_and(|h| h.ends_with(photo_url.rsplit('/').next().unwrap())),
            "{}",
            tree["hero"]
        );
        // Its photos come in Grain's two sizes, the thumbnail first; the hero with them.
        let thumb = structured["response"]["gallery"]["items"][0]["thumb"]
            .as_str()
            .unwrap();
        let sizes = format!("{thumb} 1000w, {photo_url} 2000w");
        assert_eq!(tree["heroSrcset"], sizes.as_str());
        assert_eq!(tree["hero"], photo_url);
        assert_eq!(head["type"], "article");
        assert_eq!(
            head["canonical"],
            "/profile/chadtmiller.com/gallery/3mpgwvcrieu2d"
        );
        for absent in ["imageAlt", "noindex"] {
            assert!(head.get(absent).is_none(), "{absent}: {head:#}");
        }
        let ld = &head["jsonLd"];
        assert_eq!(ld["@type"], "SocialMediaPosting");
        assert_eq!(ld["author"]["alternateName"], "@chadtmiller.com");
        assert!(ld.get("text").is_none());
        let images = ld["image"].as_array().unwrap();
        assert_eq!(images.len(), 20);
        assert_eq!(&images[0]["contentUrl"], photo);
        assert_eq!(images[0]["creditText"], "@chadtmiller.com");
        assert!(drawn(false, v).get("head").is_none());
        let mut headless = v.clone();
        headless.doc["query"]
            .as_object_mut()
            .unwrap()
            .remove("head");
        assert!(drawn(true, &headless).get("head").is_none());
    }

    /// Grain's notifications as Grain draws them, from a page of each
    /// reason: a gallery's favorites within two days one row (its first's,
    /// each author in its pile once, a third favorite of one author's left
    /// out, one three days before its own row), follows one row, the rest
    /// each their own. Each its reason's glyph, in the heart's colour for a
    /// favorite and the accent's else, who did it and what, the comment, the
    /// reply's quote and the thumbnail; each opens its gallery, its story in
    /// its account's archive, or a follow its follower.
    #[test]
    fn grain_notifications_draw_and_group_as_grain_does() {
        fn first<'a>(v: &'a Value, c: &str) -> Option<&'a Value> {
            match v {
                Value::Object(o) if o.get("c").and_then(Value::as_str) == Some(c) => Some(v),
                Value::Object(o) => o.values().find_map(|v| first(v, c)),
                Value::Array(a) => a.iter().find_map(|v| first(v, c)),
                _ => None,
            }
        }
        let response: Value =
            serde_json::from_str(include_str!("testdata/grain/listNotifications.answer.json"))
                .unwrap();
        let items = notifications_drawn(
            "social.grain.notification.listNotifications",
            response,
            Value::Null,
        );
        let icons: Vec<String> = items
            .iter()
            .map(|item| {
                let icon = &first(item, "Icon").unwrap()["p"];
                assert_eq!(icon["style"], "glyph");
                format!(
                    "{} {}",
                    icon["name"].as_str().unwrap(),
                    icon["tint"].as_str().unwrap()
                )
            })
            .collect();
        assert_eq!(
            icons,
            [
                "heart red",
                "comment blue",
                "reply blue",
                "follow blue",
                "heart red",
                "heart red",
                "mention blue",
                "mention blue",
                "comment blue",
                "heart red"
            ]
        );
        // The gallery's favorites: seven authors, Alice's first and once.
        let pile = &first(&items[0], "Faces").unwrap()["p"];
        let names: Vec<&str> = pile["faces"]
            .as_array()
            .unwrap()
            .iter()
            .map(|f| f["name"].as_str().unwrap())
            .collect();
        assert_eq!(
            names,
            [
                "Alice",
                "Bob",
                "Carol",
                "Dave",
                "erin.test",
                "Frank",
                "Grace"
            ]
        );
        assert_eq!(
            (
                pile["count"].as_u64(),
                pile["max"].as_u64(),
                &pile["expand"]
            ),
            (Some(7), Some(5), &json!(true))
        );
        assert_eq!(pile["faces"][0]["handle"], "alice.test");
        assert_eq!(
            pile["faces"][0]["open"]["call"]["args"]["actor"],
            "did:plc:alice"
        );
        assert_eq!(pile["faces"][4]["src"], Value::Null);
        let said = words(&items[0]);
        for w in ["Alice", "and 6 others", "favorited your gallery", "Coast"] {
            assert!(said.contains(&w.into()), "{w}");
        }
        let thumb = &first(&items[0], "Image").unwrap()["p"];
        assert_eq!(
            (&thumb["size"], &thumb["src"]["src"]),
            (
                &json!("thumb"),
                &json!("https://cdn.grain.social/thumb/coast.jpg")
            )
        );
        let gallery = |uri: &str| json!({ "method": "social.grain.gallery.getGallery", "params": { "gallery": uri } });
        let coast = gallery("at://did:plc:me/social.grain.gallery/3coast");
        assert_eq!(queries_opened(&items[0])[0], coast);
        // A comment alone, its words under who wrote it.
        let commented = words(&items[1]);
        assert!(commented.contains(&"Lovely light on the water".into()));
        assert!(!commented.iter().any(|w| w.starts_with("and ")));
        assert_eq!(first(&items[1], "Faces").unwrap()["p"]["count"], 1);
        // A reply, what it replied to quoted.
        let replied = words(&items[2]);
        assert!(replied.iter().any(|w| w.starts_with("Shot at dawn")));
        assert!(replied.contains(&"Thanks, it was worth the early start".into()));
        assert!(
            serde_json::to_string(&items[2])
                .unwrap()
                .contains("\"style\":\"quote\"")
        );
        // Follows: one row of both, opening the first follower, no thumbnail.
        let followed = words(&items[3]);
        assert!(
            followed.contains(&"and 1 other".into()) && followed.contains(&"followed you".into())
        );
        assert!(first(&items[3], "Image").is_none());
        assert_eq!(items[3]["open"]["call"]["args"]["actor"], "did:plc:heidi");
        // A story's favorite, and a favorite of a comment on it: the story
        // in its account's archive.
        let story = "at://did:plc:me/social.grain.story/3story";
        for item in &items[4..6] {
            assert_eq!(
                item["open"]["call"]["args"],
                json!({ "method": "social.grain.story.getArchive", "params": { "actor": "did:plc:me" }, "at": story })
            );
        }
        assert!(words(&items[5]).contains(&"Morning swim".into()));
        assert_eq!(
            queries_opened(&items[6])[0],
            gallery("at://did:plc:leo/social.grain.gallery/3harbour")
        );
        // A favorite three days before the gallery's others: a row of its own.
        assert_eq!(first(&items[9], "Faces").unwrap()["p"]["count"], 1);
        assert_eq!(queries_opened(&items[9])[0], coast);
    }

    /// plyr.fm's charts draw their tracks in the Player, each with its
    /// title and audio: the top tracks' inside their `track`, the latest's
    /// as they are.
    #[test]
    fn plyr_charts_draw_their_tracks() {
        let track = |n: usize| {
            json!({ "uri": format!("at://did:plc:a/fm.plyr.track/{n}"), "cid": "bafyrei",
                    "artist": { "did": "did:plc:a", "handle": "a.test" },
                    "record": { "$type": "fm.plyr.track", "title": format!("Track {n}"), "artist": "A",
                                "audioUrl": format!("https://audio.plyr.fm/audio/{n}.mp3"),
                                "fileType": "mp3", "createdAt": "2026-11-17T09:00:00.000Z" },
                    "indexedAt": "2026-11-17T09:00:00.000Z" })
        };
        for (method, response) in [
            (
                "fm.plyr.unspecced.getTopTracks",
                json!({ "tracks": [{ "track": track(1), "likeCount": 3 }, { "track": track(2), "likeCount": 1 }] }),
            ),
            (
                "fm.plyr.unspecced.getLatestTracks",
                json!({ "tracks": [track(1), track(2)], "cursor": "c" }),
            ),
        ] {
            let chosen = Args::of(Some(&json!({})), &["view"])
                .unwrap()
                .method_view(method)
                .unwrap()
                .expect("a bundled view");
            let structured = json!({ "method": method, "params": {}, "response": response,
                                     "service": "did:web:api.next.plyr.fm#plyr_appview" });
            let ui = view_ui(
                chosen.view(),
                true,
                "query",
                &structured,
                None,
                None,
                (None, None),
            )
            .unwrap();
            assert_eq!(ui::check(&ui), Ok(()), "{ui:#}");
            let player = &ui["root"];
            assert_eq!(player["c"], "Player", "{ui:#}");
            let items = player["items"].as_array().unwrap();
            assert_eq!(items.len(), 2, "{method}");
            assert_eq!(items[0]["title"], "Track 1");
            assert_eq!(items[1]["src"], "https://audio.plyr.fm/audio/2.mp3");
        }
    }

    #[test]
    fn a_feed_tree_says_how_to_tell_something_newer_came() {
        let bundled = |method| {
            let chosen = Args::of(Some(&json!({})), &["view"])
                .unwrap()
                .method_view(method)
                .unwrap()
                .expect("a bundled view");
            assert!(chosen.trusted());
            chosen
        };
        let post = |rkey: &str| {
            json!({ "post": { "uri": format!("at://did:plc:alice/app.bsky.feed.post/{rkey}"), "cid": "bafyrei",
                "author": { "did": "did:plc:alice", "handle": "alice.test" },
                "record": { "text": rkey, "createdAt": "2026-11-17T09:00:00.000Z" },
                "indexedAt": "2026-11-17T09:00:00.000Z" } })
        };
        // A page after the first: its keys, and the call again from the top.
        let arguments = json!({ "method": "app.bsky.feed.getAuthorFeed", "cursor": "c1",
            "params": { "actor": "alice.test", "cursor": "c0", "includePins": true } });
        let structured = json!({ "method": "app.bsky.feed.getAuthorFeed", "service": "did:web:api.bsky.app#bsky_appview",
            "params": arguments["params"], "response": { "feed": [post("pinned"), post("b"), post("a")], "cursor": "c2" } });
        let read = (None, None);
        let chosen = bundled("app.bsky.feed.getAuthorFeed");
        let v = chosen.view();
        let ui = view_ui(v, true, "query", &structured, Some(&arguments), None, read).unwrap();
        assert_eq!(ui::check(&ui), Ok(()));
        assert_eq!(
            ui["latest"],
            json!({ "call": { "name": "query", "args": { "method": "app.bsky.feed.getAuthorFeed",
                        "params": { "actor": "alice.test", "includePins": true } } },
                    "items": [{ "key": "at://did:plc:alice/app.bsky.feed.post/pinned" },
                              { "key": "at://did:plc:alice/app.bsky.feed.post/b" },
                              { "key": "at://did:plc:alice/app.bsky.feed.post/a" }],
                    "noun": "posts" })
        );
        // A custom feed too, as Bluesky checks one: the feed named again,
        // as the call named it.
        let feed = json!({ "method": "app.bsky.feed.getFeed", "params": { "feed": "For You" } });
        let answered = json!({ "method": "app.bsky.feed.getFeed", "service": "did:web:api.bsky.app#bsky_appview",
            "params": { "feed": "at://did:plc:feeds/app.bsky.feed.generator/for-you" },
            "response": { "feed": [post("b")], "cursor": "c1" } });
        let chosen = bundled("app.bsky.feed.getFeed");
        let v = chosen.view();
        let ui = view_ui(v, true, "query", &answered, Some(&feed), None, read).unwrap();
        assert_eq!(ui::check(&ui), Ok(()));
        assert_eq!(
            ui["latest"],
            json!({ "call": { "name": "query", "args": feed },
                    "items": [{ "key": "at://did:plc:alice/app.bsky.feed.post/b" }],
                    "noun": "posts" })
        );
        // Grain's feeds, by each gallery's at-uri.
        let recent = json!({ "method": "social.grain.feed.getFeed",
            "params": { "feed": "at://did:web:grain.social/social.grain.feed.generator/recent" } });
        let gallery = "at://did:plc:alice/social.grain.gallery/g1";
        let answered = json!({ "method": "social.grain.feed.getFeed", "service": "did:web:grain.social#grain_appview",
            "params": recent["params"],
            "response": { "items": [{ "uri": gallery, "cid": "bafyrei",
                "creator": { "did": "did:plc:alice", "handle": "alice.test" },
                "record": { "title": "g1", "createdAt": "2026-11-17T09:00:00.000Z" },
                "indexedAt": "2026-11-17T09:00:00.000Z" }] } });
        let chosen = bundled("social.grain.feed.getFeed");
        let v = chosen.view();
        let ui = view_ui(v, true, "query", &answered, Some(&recent), None, read).unwrap();
        assert_eq!(ui::check(&ui), Ok(()));
        assert_eq!(
            ui["latest"],
            json!({ "call": { "name": "query", "args": recent },
                    "items": [{ "key": gallery }], "noun": "galleries" })
        );
        // A view naming no key says nothing of it.
        let unkeyed = view::parse(
            &json!({ "method": "app.bsky.feed.getAuthorFeed", "description": "Feed",
                     "service": "did:web:api.bsky.app#bsky_appview",
                     "query": { "items": "feed",
                                "layout": { "component": "Text", "props": { "value": "feed" } } } }),
            false,
        )
        .unwrap();
        let ui = view_ui(
            &unkeyed,
            false,
            "query",
            &structured,
            Some(&arguments),
            None,
            read,
        )
        .unwrap();
        assert!(ui.get("latest").is_none());
        // A view with no summary names no noun for them.
        let inline = view::parse(
            &json!({ "method": "app.bsky.feed.getAuthorFeed", "description": "Feed",
                     "service": "did:web:api.bsky.app#bsky_appview",
                     "query": { "items": "feed", "latest": "post.uri",
                                "layout": { "component": "Text", "props": { "value": "feed" } } } }),
            false,
        )
        .unwrap();
        let ui = view_ui(
            &inline,
            false,
            "query",
            &structured,
            Some(&arguments),
            None,
            read,
        )
        .unwrap();
        assert_eq!(ui["latest"]["items"].as_array().unwrap().len(), 3);
        assert!(ui["latest"].get("noun").is_none());
    }

    #[test]
    fn a_peek_sees_past_a_pinned_item_within_the_lexicons_limit() {
        let limit = |l: Value| peek_limit(&l, None);
        // The AppView's feeds (1 to 100): the newest and one more, so a
        // pinned post first never hides it.
        let feeds = json!({ "type": "integer", "minimum": 1, "maximum": 100 });
        assert_eq!(limit(feeds.clone()), Some(2));
        assert_eq!(limit(json!({ "type": "integer" })), Some(2));
        // Within what the lexicon allows.
        assert_eq!(limit(json!({ "type": "integer", "minimum": 5 })), Some(5));
        assert_eq!(limit(json!({ "type": "integer", "maximum": 1 })), Some(1));
        // No more than the call drew: a tile of one item asks for one, as
        // a second it never drew would be newer every time.
        assert_eq!(peek_limit(&feeds, Some(1)), Some(1));
        assert_eq!(peek_limit(&feeds, Some(30)), Some(2));
        // No integer limit: the call as it is.
        assert_eq!(limit(Value::Null), None);
        assert_eq!(limit(json!({ "type": "string" })), None);
    }

    #[test]
    fn descriptions_stripped() {
        let mut defs = json!({ "main": { "type": "record", "description": "a record",
            "record": { "type": "object", "description": "x",
                "properties": {
                    "description": { "type": "string", "description": "the field's own" },
                    "items": { "type": "array", "items": { "type": "ref", "ref": "#i", "description": "y" } },
                } } },
            "i": { "type": "object", "description": "z", "properties": {} } });
        strip_descriptions(&mut defs, false);
        assert_eq!(
            defs,
            json!({ "main": { "type": "record",
                "record": { "type": "object",
                    "properties": {
                        "description": { "type": "string" },
                        "items": { "type": "array", "items": { "type": "ref", "ref": "#i" } },
                    } } },
                "i": { "type": "object", "properties": {} } })
        );
    }

    #[test]
    fn record_scopes() {
        let page =
            json!({ "did": "d", "records": [{ "uri": "u", "value": { "t": 1 } }], "cursor": null });
        let scope = record_scope(&page, &page["records"][0]);
        assert_eq!(scope["did"], "d");
        assert_eq!(scope["value"]["t"], 1);
        assert_eq!(scope["records"][0]["uri"], "u");
    }

    #[test]
    fn sign_in_words() {
        let notifications = json!({ "method": " dev.knotless.listNotifications " });
        assert_eq!(
            super::sign_in_words("query", Some(&notifications)),
            "Sign in to see your notifications"
        );
        // Bluesky's timeline needs an account, and says so.
        assert_eq!(
            super::sign_in_words(
                "query",
                Some(&json!({ "method": "app.bsky.feed.getTimeline" }))
            ),
            "Sign in to see your Following feed"
        );
        // A query whose view says nothing, another tool, or none named.
        for (tool, arguments) in [
            ("query", json!({ "method": "app.bsky.feed.getAuthorFeed" })),
            ("create_record", notifications),
            ("query", json!({})),
        ] {
            assert_eq!(super::sign_in_words(tool, Some(&arguments)), SIGN_IN);
        }
        assert_eq!(super::sign_in_words("query", None), SIGN_IN);
    }

    const ALICE: &str = "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa";
    const BOB: &str = "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb";
    const CAROL: &str = "did:plc:cccccccccccccccccccccccc";
    const CID: &str = "bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm";

    type Asked = Arc<std::sync::Mutex<Vec<String>>>;

    /// A post as the AppView answers one, by Alice.
    fn post_view(uri: &str, text: &str) -> Value {
        json!({ "uri": uri, "cid": CID, "author": { "did": ALICE, "handle": "alice.test" },
                "record": { "$type": "app.bsky.feed.post", "text": text,
                            "createdAt": "2026-11-16T10:00:00.000Z" },
                "indexedAt": "2026-11-16T10:00:00.000Z" })
    }

    /// A server whose PLC directory, handle resolver, PDS, Bluesky's
    /// AppView and backlink index are one fake on a loopback port: Alice's
    /// records `records` holds by `collection/rkey`, listed in their order,
    /// Bob's and Carol's repositories empty; Alice's handle alice.test and
    /// Bob's bob.test, Carol none; for anyone a thread, an author feed, a
    /// profile (Alice's) and any post asked for, and three likes of
    /// anything. The server is signed out, but as `config` sets; the
    /// lexicons of the collections the tests make up resolve to none.
    /// With it the paths the fake was asked, and its URL.
    async fn served<K: Into<String>>(
        records: Vec<(K, Value)>,
        config: impl FnOnce(&mut crate::Config),
    ) -> (Arc<Hud>, Asked, String) {
        use axum::extract::{Query, State};
        use axum::http::{StatusCode, Uri};
        use axum::response::{IntoResponse, Response};
        use std::collections::HashMap;
        type Shared = (String, Asked, Arc<Vec<(String, Value)>>);
        async fn answer(
            State((url, asked, records)): State<Shared>,
            uri: Uri,
            Query(q): Query<HashMap<String, String>>,
        ) -> Response {
            let path = uri.path().to_string();
            asked.lock().unwrap().push(path.clone());
            let arg = |k: &str| q.get(k).cloned().unwrap_or_default();
            let repo = arg("repo");
            // The repository's records, Alice's alone.
            let held: Vec<&(String, Value)> = records.iter().filter(|_| repo == ALICE).collect();
            let json = |v: Value| axum::Json(v).into_response();
            match path.as_str() {
                "/xrpc/com.atproto.repo.getRecord" => {
                    let key = format!("{}/{}", arg("collection"), arg("rkey"));
                    match held.iter().find(|(k, _)| *k == key) {
                        Some((_, value)) => json(json!({
                            "uri": format!("at://{repo}/{key}"), "cid": CID, "value": value
                        })),
                        None => (
                            StatusCode::BAD_REQUEST,
                            axum::Json(json!({ "error": "RecordNotFound", "message": "no" })),
                        )
                            .into_response(),
                    }
                }
                "/xrpc/com.atproto.repo.listRecords" => {
                    let prefix = format!("{}/", arg("collection"));
                    let all: Vec<_> = held
                        .iter()
                        .filter(|(k, _)| k.starts_with(&prefix))
                        .collect();
                    let after = format!("/{}", arg("cursor"));
                    let from = all
                        .iter()
                        .position(|(k, _)| q.contains_key("cursor") && k.ends_with(&after))
                        .map_or(0, |at| at + 1);
                    let limit: usize = arg("limit").parse().unwrap();
                    let page: Vec<_> = all.iter().skip(from).take(limit).collect();
                    let listed: Vec<Value> = page
                        .iter()
                        .map(|(k, v)| json!({ "uri": format!("at://{repo}/{k}"), "cid": CID, "value": v }))
                        .collect();
                    let more = from + limit < all.len();
                    let cursor = page
                        .last()
                        .filter(|_| more)
                        .map(|(k, _)| k.rsplit('/').next());
                    json(json!({ "records": listed, "cursor": cursor }))
                }
                "/xrpc/com.atproto.repo.describeRepo" => {
                    let mut collections: Vec<&str> = Vec::new();
                    for (k, _) in &held {
                        let c = k.split('/').next().unwrap();
                        if !collections.contains(&c) {
                            collections.push(c);
                        }
                    }
                    json(
                        json!({ "did": repo, "handle": "handle.invalid", "didDoc": {},
                                 "collections": collections, "handleIsCorrect": false }),
                    )
                }
                "/xrpc/com.atproto.identity.resolveHandle" => match arg("handle").as_str() {
                    "alice.test" => json(json!({ "did": ALICE })),
                    "bob.test" => json(json!({ "did": BOB })),
                    _ => (
                        StatusCode::BAD_REQUEST,
                        axum::Json(json!({ "error": "HandleNotFound", "message": "no" })),
                    )
                        .into_response(),
                },
                "/xrpc/app.bsky.feed.getPostThread" => json(json!({ "thread": {
                    "$type": "app.bsky.feed.defs#threadViewPost",
                    "post": post_view(&arg("uri"), "hello"),
                    "replies": [] } })),
                "/xrpc/app.bsky.feed.getAuthorFeed" => json(json!({ "feed": [
                    { "post": post_view(&format!("at://{ALICE}/app.bsky.feed.post/3abc"), "hello") }
                ], "cursor": "c2" })),
                "/xrpc/app.bsky.feed.getPosts" => {
                    json(json!({ "posts": [post_view(&arg("uris"), "quoted")] }))
                }
                // Posts found by a text, none, the text as their cursor.
                "/xrpc/app.bsky.feed.searchPosts" => {
                    json(json!({ "posts": [], "cursor": arg("q") }))
                }
                // An account's likes, none, answered after 300 ms, which
                // `answered` marks among what was asked.
                "/xrpc/app.bsky.feed.getActorLikes" => {
                    tokio::time::sleep(Duration::from_millis(300)).await;
                    asked.lock().unwrap().push("answered".into());
                    json(json!({ "feed": [], "cursor": "l2" }))
                }
                "/xrpc/app.bsky.actor.getProfile" => json(json!({
                    "did": ALICE, "handle": "alice.test", "displayName": "Alice", "postsCount": 2 })),
                "/xrpc/app.bsky.feed.describeFeedGenerator" => {
                    json(json!({ "did": "did:web:feeds.example", "feeds": [] }))
                }
                // A page of no galleries, or none answered from `broken`.
                "/xrpc/social.grain.feed.getFeed" => match arg("cursor").as_str() {
                    "broken" => StatusCode::BAD_GATEWAY.into_response(),
                    _ => json(json!({ "items": [], "cursor": "g2" })),
                },
                // An account's favorites: a page, then the last.
                "/xrpc/social.grain.actor.getFavorites" => match arg("cursor").as_str() {
                    "" => json(json!({ "items": [], "cursor": "f2" })),
                    _ => json(json!({ "items": [] })),
                },
                // Explore's places and cameras, none.
                "/xrpc/social.grain.gallery.getLocations" => json(json!({ "locations": [] })),
                "/xrpc/social.grain.gallery.getCameras" => json(json!({ "cameras": [] })),
                // An account's stories, two of them.
                "/xrpc/social.grain.story.getArchive" => {
                    let actor = arg("actor");
                    let story = |rkey: &str| {
                        json!({ "uri": format!("at://{actor}/social.grain.story/{rkey}"), "cid": CID,
                                "creator": { "did": actor, "handle": "alice.test" },
                                "thumb": "https://cdn.grain.social/t.jpg", "fullsize": "https://cdn.grain.social/f.jpg",
                                "aspectRatio": { "width": 3, "height": 4 }, "createdAt": "2026-11-16T11:00:00.000Z" })
                    };
                    json(json!({ "stories": [story("s1"), story("s2")] }))
                }
                "/links/all" => json(json!({ "links": { "app.bsky.feed.like": {
                    ".subject.uri": { "records": 3, "distinct_dids": 3 } } } })),
                did => {
                    let pds = json!({ "id": "#atproto_pds", "type": "AtprotoPersonalDataServer",
                                      "serviceEndpoint": url });
                    let doc = |id: &str, aka: &[&str]| {
                        json(json!({ "id": id, "alsoKnownAs": aka, "service": [pds] }))
                    };
                    match did.trim_start_matches('/') {
                        ALICE => doc(ALICE, &["at://alice.test"]),
                        BOB => doc(BOB, &["at://bob.test"]),
                        CAROL => doc(CAROL, &[]),
                        _ => StatusCode::NOT_FOUND.into_response(),
                    }
                }
            }
        }
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let asked: Asked = Arc::new(std::sync::Mutex::new(Vec::new()));
        let records: Vec<(String, Value)> =
            records.into_iter().map(|(k, v)| (k.into(), v)).collect();
        let app = axum::Router::new().fallback(answer).with_state((
            url.clone(),
            asked.clone(),
            Arc::new(records),
        ));
        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
        let dir = std::env::temp_dir().join(format!("hud-routed-{}", atproto::jose::random(6)));
        let mut settings = 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: false,
            oauth_scope: crate::scope::asked(crate::view::views(), true, false),
            oauth_include: None,
            workspace: true,
            spaces: false,
            plc_url: url.clone(),
            handle_resolver: Some(url.clone()),
            allow_private: true,
            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,
        };
        config(&mut settings);
        let hud = Hud::new(settings).unwrap();
        // Bluesky's AppView and Grain's are the fake.
        for (did, id) in [
            ("did:web:api.bsky.app", "#bsky_appview"),
            ("did:web:grain.social", "#grain_appview"),
        ] {
            let doc = json!({ "id": did, "service": [
                { "id": id, "type": "AppView", "serviceEndpoint": url }] });
            hud.docs
                .put(did.into(), Ok(Arc::new(doc)), Duration::from_secs(600));
        }
        for nsid in [
            "site.standard.document",
            "site.standard.publication",
            "com.example.many",
            "com.example.nothing",
        ] {
            hud.lexicons
                .put(nsid.into(), None, Duration::from_secs(600));
        }
        (hud, asked, url)
    }

    /// A record a bundled method view names in its `records` opens as
    /// that query answers it, `_meta.ui` and all: a post as its thread,
    /// its repository's record never read; a repost as the thread of the
    /// post it reposts, read for its subject. One whose binding finds
    /// nothing is drawn as itself, generically.
    #[tokio::test]
    async fn a_record_opens_as_its_query() {
        let post = format!("at://{ALICE}/app.bsky.feed.post/3abc");
        let (hud, asked, _) = served(
            vec![
            (
                "app.bsky.feed.repost/r1",
                json!({ "$type": "app.bsky.feed.repost", "subject": { "uri": post, "cid": CID },
                        "createdAt": "2026-11-16T11:00:00.000Z" }),
            ),
            (
                "app.bsky.feed.repost/r2",
                json!({ "$type": "app.bsky.feed.repost", "createdAt": "2026-11-16T11:00:00.000Z" }),
            ),
            ],
            |_| {},
        )
        .await;
        let call = |tool: &'static str, args: Value| {
            let hud = hud.clone();
            async move {
                hud.call_tool(tool, Some(&args), None)
                    .await
                    .unwrap()
                    .unwrap()
            }
        };
        let thread = call(
            "query",
            json!({ "method": "app.bsky.feed.getPostThread", "params": { "uri": post } }),
        )
        .await;
        let thread_view = view::for_method("app.bsky.feed.getPostThread").unwrap();
        assert_eq!(thread.meta["ui"]["title"], thread_view.description.as_str());
        assert_eq!(thread.meta["ui"]["trusted"], true);
        let read = |asked: &std::sync::Mutex<Vec<String>>| {
            asked
                .lock()
                .unwrap()
                .iter()
                .filter(|p| *p == "/xrpc/com.atproto.repo.getRecord")
                .count()
        };
        let opened = call("get_record", json!({ "uri": post })).await;
        assert_eq!(
            (&opened.text, &opened.structured, &opened.meta),
            (&thread.text, &thread.structured, &thread.meta)
        );
        assert_eq!(read(&asked), 0);
        // Its binding reads value.subject.uri: the repost is read.
        let reposted = call(
            "get_record",
            json!({ "uri": format!("at://{ALICE}/app.bsky.feed.repost/r1") }),
        )
        .await;
        assert_eq!(
            (&reposted.text, &reposted.structured, &reposted.meta),
            (&thread.text, &thread.structured, &thread.meta)
        );
        assert_eq!(read(&asked), 1);
        // A story: its account's archive, at the story, its record unread.
        let story = format!("at://{ALICE}/social.grain.story/s2");
        let archive = call("get_record", json!({ "uri": story })).await;
        assert_eq!(
            (&archive.structured["method"], &archive.structured["at"]),
            (&json!("social.grain.story.getArchive"), &json!(story))
        );
        assert_eq!(archive.meta["ui"]["root"]["p"]["start"], 1);
        assert_eq!(read(&asked), 1);
        // A repost of nothing: itself, generically.
        let bare = call(
            "get_record",
            json!({ "uri": format!("at://{ALICE}/app.bsky.feed.repost/r2") }),
        )
        .await;
        assert_eq!(bare.structured["collection"], "app.bsky.feed.repost");
        assert_eq!(bare.meta["ui"]["trusted"], false);
        assert_eq!(ui::check(&bare.meta["ui"]), Ok(()));
        // A record that cannot be read is the tool's error, as ever.
        let gone = hud
            .call_tool(
                "get_record",
                Some(&json!({ "uri": format!("at://{ALICE}/app.bsky.feed.repost/r3") })),
                None,
            )
            .await
            .unwrap();
        assert!(matches!(gone, Err(Refusal::Error(_))), "{gone:?}");
        // An inline view of the collection draws it as asked, not routed.
        let inline = json!({ "collection": "app.bsky.feed.post", "description": "Posts",
            "record": { "layout": { "component": "Text", "props": { "value": { "$": "value.text" } } } } });
        let mine = hud
            .call_tool(
                "get_record",
                Some(&json!({ "uri": post, "view": inline })),
                None,
            )
            .await
            .unwrap();
        // Alice holds no such post: asked of her PDS, not the AppView.
        // Reads: the repost r1, r2 twice (routed, then as itself), r3
        // twice, and this.
        assert!(mine.is_err());
        assert_eq!(read(&asked), 6);
    }

    /// Alice's records: her profile, a post, and four blog posts, the
    /// newest first, each made with a Bluesky post, its text linking it.
    fn alice() -> Vec<(String, Value)> {
        let post = format!("at://{ALICE}/app.bsky.feed.post/3abc");
        let mut records = vec![
            (
                "app.bsky.actor.profile/self".to_string(),
                json!({ "$type": "app.bsky.actor.profile", "displayName": "Alice" }),
            ),
            (
                "app.bsky.feed.post/3abc".to_string(),
                json!({ "$type": "app.bsky.feed.post", "text": "hello",
                        "createdAt": "2026-11-16T10:00:00.000Z" }),
            ),
        ];
        for (minute, title) in [(4, "Coast"), (3, "Hills"), (2, "Woods"), (1, "Moor")] {
            let at = format!("2026-11-15T10:0{minute}:00.000Z");
            let rkey = atproto::tid::tid_from(datetime_millis(&at).unwrap() as u64 * 1000, 0);
            records.push((
                format!("site.standard.document/{rkey}"),
                json!({ "$type": "site.standard.document", "title": title, "publishedAt": at,
                        "site": format!("at://{ALICE}/site.standard.publication/self"),
                        "textContent": "A walk.\n\nhttps://bsky.app/profile/alice.test/post/3abc",
                        "bskyPostRef": { "uri": post, "cid": CID } }),
            ));
        }
        records
    }

    /// Alice's records and 101 more of a collection with no lexicon.
    fn alice_and_many() -> Vec<(String, Value)> {
        let mut records = alice();
        for n in 0..101 {
            records.push((format!("com.example.many/{n:03}"), json!({ "n": n })));
        }
        records
    }

    /// Whether any list in a tree grows a page more.
    fn paged(v: &Value) -> bool {
        match v {
            Value::Object(o) => {
                o.get("p").is_some_and(|p| p.get("page").is_some()) || o.values().any(paged)
            }
            Value::Array(a) => a.iter().any(paged),
            _ => false,
        }
    }

    /// A call of `tool` as `account`, as `/mcp` makes it.
    async fn call(
        hud: &Hud,
        tool: &str,
        args: Value,
        account: Option<&Account>,
    ) -> Result<Output, Refusal> {
        hud.call_tool(tool, Some(&args), account).await.unwrap()
    }

    /// An account's profile from its repository: who it is, its apps, its
    /// recent activity and its sections, which grow no page more; with no
    /// records, its DID and a line saying so.
    #[tokio::test]
    async fn describe_repo_draws_an_accounts_profile() {
        let (hud, _, url) = served(alice(), |_| {}).await;
        let out = call(
            &hud,
            "describe_repo",
            json!({ "actor": "@alice.test" }),
            None,
        )
        .await
        .unwrap();
        assert_eq!(
            out.text,
            format!(
                "Alice (alice.test, {ALICE}) on {url}. Views: Blog posts (standard.site documents). 3 collections."
            )
        );
        assert_eq!(out.structured["profile"]["value"]["displayName"], "Alice");
        let apps: Vec<&str> = out.structured["apps"]
            .as_array()
            .unwrap()
            .iter()
            .map(|a| a["domain"].as_str().unwrap())
            .collect();
        assert_eq!(apps, ["bsky.app", "standard.site"]);
        let ui = &out.meta["ui"];
        assert_eq!(ui::check(ui), Ok(()));
        let said = words(ui);
        for w in [
            "Recent activity",
            "Posted “hello”",
            "Published “Coast”",
            "Blog",
            "Bluesky",
            "See all",
        ] {
            assert!(said.contains(&w.to_string()), "{w}: {said:?}");
        }
        assert!(!paged(ui));
        let carol = call(&hud, "describe_repo", json!({ "actor": CAROL }), None)
            .await
            .unwrap();
        assert_eq!(carol.text, format!("{CAROL} on {url}. No collections."));
        let said = words(&carol.meta["ui"]);
        assert!(said.contains(&CAROL.to_string()));
        assert!(said.contains(&"This repository has no records.".to_string()));
        let nobody = call(
            &hud,
            "describe_repo",
            json!({ "actor": "nobody.test" }),
            None,
        )
        .await;
        assert!(format!("{:?}", nobody.err()).contains("nobody.test"));
    }

    /// An app's own page, by its path, as its app file names it: its
    /// Markdown as data, drawn as its title over its text, its head its
    /// title on the app's, its description and its path; one it has not
    /// is the call's error.
    #[tokio::test]
    async fn describe_app_draws_an_apps_own_page() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let page = |path: &str| {
            let hud = hud.clone();
            let args = json!({ "domain": "grain.social", "page": path });
            async move { call(&hud, "describe_app", args, None).await }
        };
        let terms = page("/support/terms").await.unwrap();
        assert_eq!(
            terms.text,
            "Terms and Conditions (Grain's page /support/terms): The terms of using Grain, the photo sharing app built on the AT Protocol."
        );
        assert_eq!(terms.structured["path"], "/support/terms");
        assert_eq!(terms.structured["title"], "Terms and Conditions");
        assert!(
            terms.structured["markdown"]
                .as_str()
                .unwrap()
                .contains("## Overview")
        );
        let tree = &terms.meta["ui"];
        assert_eq!(ui::check(tree), Ok(()));
        assert_eq!(tree["trusted"], true);
        assert_eq!(
            tree["head"],
            json!({ "title": "Terms and Conditions - Grain",
                    "description": "The terms of using Grain, the photo sharing app built on the AT Protocol.",
                    "canonical": "/support/terms" })
        );
        assert_eq!(
            tree["root"]["k"][0],
            json!({ "c": "Bar", "p": { "title": "Terms and Conditions" } })
        );
        assert_eq!(tree["root"]["k"][1]["c"], "RichText");
        assert_eq!(
            page("/support/none").await.err(),
            Some(Refusal::Error("Grain has no page /support/none".into()))
        );
        // A page with no description says its title alone, its head none.
        let mut bare = view::views()
            .page("grain.social", "/support/terms")
            .unwrap()
            .clone();
        bare.description = None;
        assert!(ui::page_tree(&bare)["head"].get("description").is_none());
    }

    /// An app's page: where to go in it; with an app page view, drawn by it
    /// for the account named, its joins asked; else an account's part in
    /// it, named as its profile names it, else by its handle, else its DID.
    #[tokio::test]
    async fn describe_app_draws_an_apps_page() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let app = |args: Value| {
            let hud = hud.clone();
            async move { call(&hud, "describe_app", args, None).await }
        };
        assert_eq!(
            app(json!({ "domain": "not a domain" })).await.err(),
            Some(Refusal::Error("Not an app's domain: not a domain".into()))
        );
        let bsky = app(json!({ "domain": "bsky.app" })).await.unwrap();
        assert!(
            bsky.text.starts_with("Bluesky (bsky.app). Go to: "),
            "{}",
            bsky.text
        );
        assert!(bsky.structured.get("actor").is_none());
        let alices = app(json!({ "domain": "bsky.app", "actor": "alice.test" }))
            .await
            .unwrap();
        assert_eq!(
            alices.structured["actor"],
            json!({ "did": ALICE, "handle": "alice.test" })
        );
        assert_eq!(alices.structured["mine"], false);
        assert_eq!(
            alices.structured["joins"]["profile"]["displayName"],
            "Alice"
        );
        assert_eq!(alices.meta["ui"]["title"], "Bluesky");
        assert_eq!(ui::check(&alices.meta["ui"]), Ok(()));
        assert!(
            app(json!({ "domain": "bsky.app", "actor": "nobody.test" }))
                .await
                .is_err()
        );
        let name = apps::name("standard.site");
        let head = format!("{name} (standard.site).");
        for (actor, part) in [
            (ALICE, "Alice here: 1 collection."),
            ("bob.test", "@bob.test here: 0 collections."),
            (CAROL, &format!("{CAROL} here: 0 collections.")),
        ] {
            let out = app(json!({ "domain": "standard.site", "actor": actor }))
                .await
                .unwrap();
            assert!(out.text.starts_with(&head), "{}", out.text);
            assert!(out.text.ends_with(part), "{}", out.text);
            assert_eq!(ui::check(&out.meta["ui"]), Ok(()));
        }
        let blog = app(json!({ "domain": "standard.site", "actor": ALICE }))
            .await
            .unwrap();
        let said = words(&blog.meta["ui"]);
        for w in ["Alice here", "Blog", "See all"] {
            assert!(said.contains(&w.to_string()), "{w}: {said:?}");
        }
    }

    /// A collection described for a model: how many records, three
    /// samples with their backlink counts, its schema without its
    /// descriptions, and its view, bundled or the query it opens as.
    #[tokio::test]
    async fn describe_collection_samples_a_collection() {
        let (hud, _, _) = served(alice_and_many(), |c| {
            c.backlinks = crate::backlinks::Backlinks::Constellation(c.plc_url.clone());
        })
        .await;
        let describe = |collection: &'static str| {
            let hud = hud.clone();
            async move {
                let args = json!({ "actor": "alice.test", "collection": collection });
                call(&hud, "describe_collection", args, None).await
            }
        };
        let docs = describe("site.standard.document").await.unwrap();
        assert_eq!(
            docs.text,
            "site.standard.document on alice.test: 4 records, sampled 3; a bundled view exists (Blog posts (standard.site documents))."
        );
        assert_eq!(docs.structured["samples"].as_array().unwrap().len(), 3);
        assert_eq!(
            docs.structured["samples"][0]["backlinks"],
            json!([{ "collection": "app.bsky.feed.like", "path": ".subject.uri", "records": 3 }])
        );
        assert_eq!(docs.structured["schema"], Value::Null);
        assert_eq!(docs.structured["view"]["source"], "bundled");
        let posts = describe("app.bsky.feed.post").await.unwrap();
        let thread = view::for_method("app.bsky.feed.getPostThread").unwrap();
        assert_eq!(
            posts.text,
            format!(
                "app.bsky.feed.post on alice.test: 1 record, sampled 1; no bundled view; get_record opens one as app.bsky.feed.getPostThread ({}).",
                thread.description
            )
        );
        let schema = &posts.structured["schema"];
        assert_eq!(schema["nsid"], "app.bsky.feed.post");
        assert_eq!(schema["defs"]["main"]["type"], "record");
        assert!(schema["defs"]["main"].get("description").is_none());
        assert_eq!(
            describe("com.example.many").await.unwrap().text,
            "com.example.many on alice.test: 100+ records, sampled 3; no bundled view."
        );
        let none = describe("com.example.nothing").await.unwrap();
        assert_eq!(
            none.text,
            "com.example.nothing on alice.test: no records; no bundled view."
        );
        assert_eq!(none.structured["samples"], json!([]));
        assert_eq!(
            describe("not an nsid").await.err(),
            Some(Refusal::Error(
                "Not a collection's NSID: not an nsid".into()
            ))
        );
    }

    /// A collection's records a page at a time: generically with no view,
    /// by the bundled one, or by an inline one whose query joins run on the
    /// first page, those reading its records on every page, which is no
    /// longer than such a join takes.
    #[tokio::test]
    async fn list_records_pages_through_a_collection() {
        let (hud, _, _) = served(alice_and_many(), |_| {}).await;
        let list = |args: Value| {
            let hud = hud.clone();
            async move { call(&hud, "list_records", args, None).await }
        };
        let many = |more: Value| {
            let mut args = json!({ "actor": "alice.test", "collection": "com.example.many" });
            args.as_object_mut()
                .unwrap()
                .extend(more.as_object().unwrap().clone());
            args
        };
        assert_eq!(
            list(json!({ "actor": "alice.test", "collection": "nope" }))
                .await
                .err(),
            Some(Refusal::Error("Not a collection's NSID: nope".into()))
        );
        assert_eq!(
            list(many(json!({ "cursor": 5 }))).await.err(),
            Some(Refusal::Error("cursor must be a string".into()))
        );
        assert_eq!(
            list(many(json!({ "page": 2 }))).await.err(),
            Some(Refusal::Error("Unknown argument: page".into()))
        );
        let first = list(many(json!({ "limit": 2 }))).await.unwrap();
        assert_eq!(first.structured["records"].as_array().unwrap().len(), 2);
        assert_eq!(first.structured["cursor"], "001");
        let ui = &first.meta["ui"];
        assert_eq!(ui["next"]["args"]["cursor"], "001");
        assert!(words(ui).contains(
            &"No lexicon found for com.example.many, so these show as JSON.".to_string()
        ));
        let second = list(many(json!({ "limit": 2, "cursor": "001" })))
            .await
            .unwrap();
        assert_eq!(
            second.structured["records"][0]["uri"],
            format!("at://{ALICE}/com.example.many/002")
        );
        let blog = list(json!({ "actor": "alice.test", "collection": "site.standard.document" }))
            .await
            .unwrap();
        let v = view::for_collection("site.standard.document").unwrap();
        assert_eq!(blog.meta["ui"]["title"], v.description.as_str());
        assert_eq!(blog.meta["ui"]["trusted"], true);
        assert_eq!(ui::check(&blog.meta["ui"]), Ok(()));
        assert!(blog.text.contains("Coast"), "{}", blog.text);
        let joined = json!({ "collection": "com.example.many", "description": "Many", "list": {
            "join": [
                { "as": "posts", "query": "app.bsky.feed.getPosts", "service": "did:web:api.bsky.app#bsky_appview",
                  "params": { "uris": { "$each": ["records", "uri"] } } },
                { "as": "profile", "query": "app.bsky.actor.getProfile",
                  "params": { "actor": { "$": "did" } },
                  "say": { "noun": ["post", "posts"], "count": "postsCount" } } ],
            "layout": { "component": "Text", "props": { "value": { "$": "joins.profile.displayName" } } } } });
        let page = list(many(json!({ "limit": 50, "view": joined })))
            .await
            .unwrap();
        assert_eq!(page.structured["records"].as_array().unwrap().len(), 25);
        assert_eq!(page.structured["joins"]["profile"]["displayName"], "Alice");
        assert!(page.structured["joins"]["posts"]["posts"].is_array());
        assert!(page.text.contains("2 posts"), "{}", page.text);
        assert_eq!(words(&page.meta["ui"]), ["Alice"]);
        assert_eq!(page.meta["ui"]["trusted"], false);
        let more = list(many(
            json!({ "cursor": page.structured["cursor"], "view": joined }),
        ))
        .await
        .unwrap();
        assert!(more.structured["joins"]["posts"]["posts"].is_array());
        assert!(more.structured["joins"].get("profile").is_none());
        // With no backlink index, samples have no counts.
        let args = json!({ "actor": "alice.test", "collection": "site.standard.document" });
        let described = call(&hud, "describe_collection", args, None).await.unwrap();
        assert!(
            described.structured["samples"][0]
                .get("backlinks")
                .is_none()
        );
        let bad = json!({ "collection": "com.example.many", "description": "Many", "list": {
            "join": [{ "as": "posts", "query": "app.bsky.feed.getPosts",
                       "service": "did:web:api.bsky.app#bsky_appview", "params": { "nope": 1 } }],
            "layout": { "component": "Text", "props": { "value": "x" } } } });
        assert_eq!(
            list(many(json!({ "view": bad }))).await.err(),
            Some(Refusal::Error(
                "Invalid view: 2 problems: list.join[0].params.nope: not a parameter of app.bsky.feed.getPosts; list.join[0].params.uris: app.bsky.feed.getPosts requires it".into()
            ))
        );
    }

    /// A record drawn by its view, its query joins run once beside its
    /// own, the Bluesky posts its text links drawn as their quotes; a post
    /// named by its handle opens as its thread.
    #[tokio::test]
    async fn get_record_draws_a_record_with_its_joins() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let get = |args: Value| {
            let hud = hud.clone();
            async move { call(&hud, "get_record", args, None).await.unwrap() }
        };
        let doc = get(json!({ "uri": format!("at://{ALICE}/{}", alice()[2].0) })).await;
        assert!(doc.text.contains("Coast"), "{}", doc.text);
        assert!(doc.structured["records"][0]["joins"]["replies"]["thread"].is_object());
        let ui = &doc.meta["ui"];
        assert_eq!(ui::check(ui), Ok(()));
        // The Bluesky post its text links, drawn as its quote.
        let linked = &ui["root"]["k"][2]["p"]["blocks"][1];
        assert_eq!(linked["kind"], "bskyPost");
        assert_eq!(linked["quote"]["runs"][0]["text"], "quoted");
        let inline = json!({ "collection": "app.bsky.feed.post", "description": "Posts", "record": {
            "join": [{ "as": "profile", "query": "app.bsky.actor.getProfile",
                       "params": { "actor": { "$": "did" } },
                       "say": { "noun": ["post", "posts"], "count": "postsCount" } }],
            "summary": { "noun": ["post", "posts"], "label": { "$": "value.text" } },
            "layout": { "component": "Text", "props": { "value": { "$": "joins.profile.displayName" } } } } });
        let post =
            get(json!({ "uri": "at://alice.test/app.bsky.feed.post/3abc", "view": inline })).await;
        assert_eq!(words(&post.meta["ui"]), ["Alice"]);
        assert_eq!(
            post.structured["records"][0]["joins"]["profile"]["handle"],
            "alice.test"
        );
        assert!(
            post.text.contains("hello") && post.text.contains("2 posts"),
            "{}",
            post.text
        );
        // An inline view with no query joins: the record alone.
        let plain = json!({ "collection": "app.bsky.feed.post", "description": "Posts", "record": {
            "layout": { "component": "Text", "props": { "value": { "$": "value.text" } } } } });
        let alone =
            get(json!({ "uri": "at://alice.test/app.bsky.feed.post/3abc", "view": plain })).await;
        assert_eq!(words(&alone.meta["ui"]), ["hello"]);
        assert!(
            alone.structured["records"][0]["joins"]
                .get("profile")
                .is_none()
        );
        let thread = call(
            &hud,
            "query",
            json!({ "method": "app.bsky.feed.getPostThread",
                    "params": { "uri": format!("at://{ALICE}/app.bsky.feed.post/3abc") } }),
            None,
        )
        .await
        .unwrap();
        let routed = get(json!({ "uri": "at://alice.test/app.bsky.feed.post/3abc" })).await;
        assert_eq!(
            (&routed.text, &routed.structured),
            (&thread.text, &thread.structured)
        );
    }

    /// A query described for a model, or why it cannot be.
    #[tokio::test]
    async fn describe_method_needs_a_query_with_a_lexicon() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let describe = |method: &'static str| {
            let hud = hud.clone();
            async move { call(&hud, "describe_method", json!({ "method": method }), None).await }
        };
        assert_eq!(
            describe("x").await.err(),
            Some(Refusal::Error("Not a method's NSID: x".into()))
        );
        assert_eq!(
            describe("com.example.nothing").await.err(),
            Some(Refusal::Error("No lexicon for com.example.nothing".into()))
        );
        let generator = describe("app.bsky.feed.describeFeedGenerator")
            .await
            .unwrap();
        assert_eq!(
            generator.text,
            "app.bsky.feed.describeFeedGenerator: a query taking no params; no bundled view."
        );
        assert_eq!(generator.structured["view"], Value::Null);
        assert_eq!(
            hud.call_tool("describe_method", None, None)
                .await
                .unwrap()
                .err(),
            Some(Refusal::Error("method is required".into()))
        );
    }

    /// A query's answer: as a JSON tree with no view, and only with a
    /// service named then; by its bundled view, its joins said; by an
    /// inline view of it alone, its joins on its first page.
    #[tokio::test]
    async fn query_answers_by_its_view() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let query = |args: Value| {
            let hud = hud.clone();
            async move { call(&hud, "query", args, None).await }
        };
        let generator = "app.bsky.feed.describeFeedGenerator";
        let appview = "did:web:api.bsky.app#bsky_appview";
        assert_eq!(
            query(json!({ "method": generator, "params": "x" }))
                .await
                .err(),
            Some(Refusal::Error("params must be an object".into()))
        );
        assert_eq!(
            query(json!({ "method": generator, "actor": ALICE }))
                .await
                .err(),
            Some(Refusal::Error("Unknown argument: actor".into()))
        );
        assert_eq!(
            query(json!({ "method": generator, "params": null }))
                .await
                .err(),
            Some(Refusal::Error(format!(
                "Name a service for {generator}: a DID with its service's #fragment, as did:web:api.bsky.app#bsky_appview"
            )))
        );
        let bare = query(json!({ "method": generator, "service": appview }))
            .await
            .unwrap();
        assert_eq!(bare.meta["ui"]["trusted"], false);
        assert_eq!(bare.meta["ui"]["root"]["c"], "Json");
        assert_eq!(
            bare.meta["ui"]["root"]["p"]["value"]["did"],
            "did:web:feeds.example"
        );
        // A view naming each item's key, of a method that takes no limit:
        // what tells something newer came calls it as it was.
        let keyed = json!({ "method": generator, "description": "Feeds", "service": appview,
            "query": { "items": "feeds", "latest": "uri",
                       "layout": { "component": "Text", "props": { "value": "feeds" } } } });
        let peeked = query(json!({ "method": generator, "service": appview, "view": keyed }))
            .await
            .unwrap();
        assert_eq!(
            peeked.meta["ui"]["latest"]["call"]["args"],
            json!({ "method": generator, "service": appview, "view": keyed })
        );
        let profile = query(json!({ "method": "app.bsky.actor.getProfile",
                                    "params": { "actor": "alice.test" } }))
        .await
        .unwrap();
        assert!(profile.text.contains("Alice"), "{}", profile.text);
        assert!(profile.structured["joins"]["posts"]["feed"].is_array());
        let inline = json!({ "method": "app.bsky.feed.getAuthorFeed", "description": "Feed",
            "service": appview, "query": { "items": "feed", "cursor": "cursor",
            "join": [{ "as": "profile", "query": "app.bsky.actor.getProfile",
                       "params": { "actor": { "$": "params.actor" } } }],
            "layout": { "component": "Text", "props": { "value": { "$": "joins.profile.displayName" } } } } });
        let first = query(json!({ "method": "app.bsky.feed.getAuthorFeed",
                                  "params": { "actor": ALICE }, "view": inline }))
        .await
        .unwrap();
        assert_eq!(words(&first.meta["ui"]), ["Alice"]);
        assert_eq!(first.meta["ui"]["next"]["args"]["cursor"], "c2");
        assert_eq!(first.meta["ui"]["trusted"], false);
        let next = query(
            json!({ "method": "app.bsky.feed.getAuthorFeed", "cursor": "c2",
                                 "params": { "actor": ALICE }, "view": inline }),
        )
        .await
        .unwrap();
        assert_eq!(next.structured["params"]["cursor"], "c2");
        assert!(next.structured.get("joins").is_none());
        let other = query(json!({ "method": "app.bsky.actor.getProfile",
                                  "params": { "actor": ALICE }, "view": inline }))
        .await
        .err();
        assert!(
            format!("{other:?}").contains("but the query is app.bsky.actor.getProfile"),
            "{other:?}"
        );
        let invalid = query(json!({ "method": "app.bsky.feed.getAuthorFeed",
                                    "params": { "actor": ALICE }, "view": {} }))
        .await
        .err();
        assert!(
            format!("{invalid:?}").contains("Invalid view: "),
            "{invalid:?}"
        );
    }

    /// A query asked to open at a form (`compose`): its screen's Compose of
    /// that label, or its first for true, marked open; one it lacks opens
    /// nothing, and anything but true or a label is the caller's error.
    #[tokio::test]
    async fn a_query_opens_its_screen_at_the_form_it_names() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let query = |compose: Value| {
            let hud = hud.clone();
            let compose_form = |label: &str| {
                json!({ "component": "Compose", "props": { "label": label, "send": "Post",
                    "fields": [{ "name": "text", "kind": "text", "label": "Text", "max": 300 }],
                    "writes": [{ "collection": "app.bsky.feed.post",
                                 "record": { "text": { "$value": "text" }, "createdAt": { "$now": true } } }] } })
            };
            let view = json!({ "method": "app.bsky.feed.searchPosts", "description": "Posts",
                "service": "did:web:api.bsky.app#bsky_appview", "query": { "items": "posts",
                    "layout": { "component": "Stack", "children": [compose_form("Reply"), compose_form("New post")] } } });
            async move {
                let args = json!({ "method": "app.bsky.feed.searchPosts", "params": { "q": "a" },
                                   "view": view, "compose": compose });
                call(&hud, "query", args, None).await
            }
        };
        let opened = |out: &Output| -> Vec<Value> {
            let k = out.meta["ui"]["root"]["k"].as_array().unwrap();
            k.iter().map(|c| c["p"]["open"].clone()).collect()
        };
        let first = query(json!(true)).await.unwrap();
        assert_eq!(opened(&first), [json!(true), Value::Null]);
        assert_eq!(ui::check(&first.meta["ui"]), Ok(()));
        assert!(first.structured.get("compose").is_none());
        let named = query(json!("New post")).await.unwrap();
        assert_eq!(opened(&named), [Value::Null, json!(true)]);
        for none in [json!("Quote"), json!(false), Value::Null] {
            assert_eq!(
                opened(&query(none).await.unwrap()),
                [Value::Null, Value::Null]
            );
        }
        assert_eq!(
            query(json!("")).await.err(),
            Some(Refusal::Error(
                "compose must be true or a Compose's label, 1 to 64 characters".into()
            ))
        );
    }

    /// A query's joins reading nothing of its answer start beside its
    /// call, those reading it once it answers, their answers in its view's
    /// order and as all of them read after the answer would be; one reading
    /// its params reads them as sent, a post named by its handle by its DID.
    #[tokio::test]
    async fn query_joins_reading_no_answer_start_beside_the_call() {
        let (hud, asked, _) = served(alice(), |_| {}).await;
        let appview = "did:web:api.bsky.app#bsky_appview";
        let search = |q: &str| json!({ "query": "app.bsky.feed.searchPosts", "params": { "q": { "$": q } } });
        let (mut after, mut found) = (search("response.cursor"), search("params.uri"));
        (after["as"], found["as"]) = (json!("after"), json!("found"));
        let likes = json!({ "method": "app.bsky.feed.getActorLikes", "description": "Likes",
            "service": appview, "query": { "items": "feed", "cursor": "cursor",
            "join": [after, { "as": "profile", "query": "app.bsky.actor.getProfile",
                              "params": { "actor": { "$": "params.actor" } } }],
            "layout": { "component": "Text", "props": { "value": { "$": "joins.profile.displayName" } } } } });
        let thread = json!({ "method": "app.bsky.feed.getPostThread", "description": "Thread",
            "service": appview, "query": { "join": [found],
            "layout": { "component": "Text", "props": { "value": { "$": "joins.found.cursor" } } } } });
        let ask = |method: &str, params: Value, view: &Value| {
            let (hud, args) = (
                hud.clone(),
                json!({ "method": method, "params": params, "view": view }),
            );
            async move { call(&hud, "query", args, None).await.unwrap() }
        };
        // The joins as they were read before: all of them after the answer.
        let before = |out: &Output, view: &Value| {
            let mut scope = out.structured.clone();
            scope.as_object_mut().unwrap().remove("joins");
            let (hud, queries) = (
                hud.clone(),
                view::parse(view, false).unwrap().query.unwrap().queries,
            );
            async move {
                let asker = xrpc::As {
                    hud: &hud,
                    caller: xrpc::Caller::Public,
                };
                let own = Some("did:web:api.bsky.app#bsky_appview");
                Value::Object(
                    join::queries(&asker, queries.iter(), own, &scope, join::QUERY_WAIT).await,
                )
            }
        };
        let liked = ask(
            "app.bsky.feed.getActorLikes",
            json!({ "actor": ALICE }),
            &likes,
        )
        .await;
        let joins = &liked.structured["joins"];
        let names: Vec<&String> = joins.as_object().unwrap().keys().collect();
        assert_eq!(names, ["after", "profile"]);
        assert_eq!(
            (&joins["after"]["cursor"], &joins["profile"]["displayName"]),
            (&json!("l2"), &json!("Alice"))
        );
        let order = asked.lock().unwrap().clone();
        let at = |p: &str| order.iter().position(|a| a == p).unwrap();
        assert!(
            at("/xrpc/app.bsky.actor.getProfile") < at("answered"),
            "{order:?}"
        );
        assert!(
            at("answered") < at("/xrpc/app.bsky.feed.searchPosts"),
            "{order:?}"
        );
        assert_eq!(*joins, before(&liked, &likes).await);
        let post = format!("at://{ALICE}/app.bsky.feed.post/3abc");
        let read = ask(
            "app.bsky.feed.getPostThread",
            json!({ "uri": "at://alice.test/app.bsky.feed.post/3abc" }),
            &thread,
        )
        .await;
        assert_eq!(read.structured["params"]["uri"], post);
        assert_eq!(read.structured["joins"]["found"]["cursor"], post);
        assert_eq!(read.structured["joins"], before(&read, &thread).await);
    }

    /// Which of Grain's query views' joins start beside their call, reading
    /// only what was asked: on Home, Explore and a story all of them; a
    /// gallery's none, each reading its answer.
    #[test]
    fn grain_joins_that_start_beside_the_call() {
        let early = |id: &str| -> Vec<(String, bool)> {
            let b = view::bundled().iter().find(|b| b.id == id).unwrap();
            let q = b.view.query.as_ref().unwrap();
            q.queries
                .iter()
                .map(|j| (j.name.clone(), j.reads_only(&ASKED)))
                .collect()
        };
        let all = |names: &[&str], early: bool| -> Vec<(String, bool)> {
            names.iter().map(|n| (n.to_string(), early)).collect()
        };
        let home = ["stories", "me", "mine", "prefs", "suggest"];
        assert_eq!(early("grain-feed"), all(&home, true));
        assert_eq!(
            early("grain-explore"),
            all(&["cameras", "recent", "places"], true)
        );
        assert_eq!(early("grain-stories"), all(&["who", "prefs"], true));
        assert_eq!(
            early("grain-gallery-view"),
            all(&["comments", "more"], false)
        );
    }

    /// A view drawn again over what its call read before draws as the
    /// call made afresh with it draws: a page of records, one record and a
    /// query, their joins as read, nothing read again; refused for a tool
    /// that draws no view and an answer not of the call.
    #[tokio::test]
    async fn a_view_drawn_again_over_its_answer() {
        let (hud, asked, _) = served(alice_and_many(), |_| {}).await;
        let appview = "did:web:api.bsky.app#bsky_appview";
        let text = |path: &str| json!({ "component": "Text", "props": { "value": { "$": path } } });
        // Each a view in one mode, with no layout: given one each time.
        let cases = [
            (
                "list_records",
                json!({ "actor": "alice.test", "collection": "com.example.many", "limit": 2 }),
                json!({ "collection": "com.example.many", "description": "Many", "list": {
                    "join": [{ "as": "profile", "query": "app.bsky.actor.getProfile",
                               "params": { "actor": { "$": "did" } } }] } }),
                "/list",
                ["joins.profile.displayName", "joins.profile.handle"],
            ),
            (
                "get_record",
                json!({ "uri": "at://alice.test/app.bsky.feed.post/3abc" }),
                json!({ "collection": "app.bsky.feed.post", "description": "Posts", "record": {} }),
                "/record",
                ["value.text", "uri"],
            ),
            (
                "query",
                json!({ "method": "app.bsky.feed.getAuthorFeed", "params": { "actor": ALICE } }),
                json!({ "method": "app.bsky.feed.getAuthorFeed", "description": "Feed",
                        "service": appview, "query": { "items": "feed", "cursor": "cursor" } }),
                "/query",
                ["params.actor", "cursor"],
            ),
        ];
        for (tool, args, doc, mode, [first, then]) in cases {
            let with = |path: &str| {
                let mut args = args.clone();
                let mut doc = doc.clone();
                doc.pointer_mut(mode).unwrap()["layout"] = text(path);
                args["view"] = doc;
                args
            };
            let read = call(&hud, tool, with(first), None).await.unwrap();
            let fresh = call(&hud, tool, with(then), None).await.unwrap();
            let before = asked.lock().unwrap().len();
            let drawn = hud
                .redraw(tool, Some(&with(then)), &read.structured, None)
                .await
                .unwrap();
            assert_eq!(drawn, fresh.meta["ui"], "{tool}");
            assert_ne!(drawn, read.meta["ui"], "{tool}");
            assert_eq!(ui::check(&drawn), Ok(()), "{tool}");
            // What it draws with was read with the answer: nothing asked.
            assert_eq!(asked.lock().unwrap().len(), before, "{tool}");
            // An answer of another tool is not this one's.
            let other = json!({ "response": {} });
            assert_eq!(
                hud.redraw(tool, Some(&with(then)), &other, None).await,
                Err(format!("The answer is not one {tool} gave")),
                "{tool}"
            );
        }
        let many = json!({ "collection": "com.example.many", "records": {} });
        assert_eq!(
            hud.redraw("list_records", None, &many, None).await,
            Err("The answer is not one list_records gave".into())
        );
        assert_eq!(
            hud.redraw("get_record", Some(&json!({ "actor": ALICE })), &many, None)
                .await,
            Err("Unknown argument: actor".into())
        );
        assert_eq!(
            hud.redraw("describe_repo", None, &many, None).await,
            Err("describe_repo draws no view".into())
        );
        // With no view given, the bundled one draws, as the tool draws.
        let profile =
            json!({ "method": "app.bsky.actor.getProfile", "params": { "actor": ALICE } });
        let read = call(&hud, "query", profile.clone(), None).await.unwrap();
        assert_eq!(
            hud.redraw("query", Some(&profile), &read.structured, None)
                .await
                .unwrap(),
            read.meta["ui"]
        );
        // A query with no lexicon, or a lexicon not of a query, was never
        // answered.
        for (method, why) in [
            ("com.example.nothing", "No lexicon for com.example.nothing"),
            ("x", "Not a method's NSID: x"),
        ] {
            let answer = json!({ "method": method, "response": {} });
            assert_eq!(
                hud.redraw("query", None, &answer, None).await,
                Err(why.into())
            );
        }
        let post = json!({ "method": "app.bsky.feed.post", "response": {} });
        assert!(hud.redraw("query", None, &post, None).await.is_err());
    }

    /// Signed in, the tools act as the account: `me` is it, its queries go
    /// through its PDS, an app's page is its own; signed out, a tool that
    /// needs it asks for sign-in.
    #[tokio::test]
    async fn signed_in_tools_act_as_the_account() {
        let (hud, asked, url) = served(alice(), |c| {
            c.oauth = true;
            c.oauth_scope = crate::scope::asked(crate::view::views(), true, false);
        })
        .await;
        let messaged = |asked: &Asked| {
            asked
                .lock()
                .unwrap()
                .iter()
                .filter(|p| *p == "/xrpc/chat.bsky.convo.getConvoAvailability")
                .count()
        };
        let auth = hud.auth().unwrap();
        let me = auth
            .account(&auth.signed_in_offline_at(ALICE, Some("alice.test"), false, &url))
            .unwrap();
        let mine = json!({ "uri": "at://me/app.bsky.feed.post/3abc" });
        assert_eq!(
            call(&hud, "delete_record", mine, None).await.err(),
            Some(Refusal::SignIn)
        );
        assert_eq!(
            call(&hud, "apply_writes", json!({}), None).await.err(),
            Some(Refusal::SignIn)
        );
        // A write naming no `me` asks for sign-in too; a tool there is
        // none of, nothing.
        let theirs = json!({ "uri": format!("at://{ALICE}/app.bsky.feed.post/3abc") });
        assert_eq!(
            call(&hud, "delete_record", theirs, None).await.err(),
            Some(Refusal::SignIn)
        );
        assert!(hud.call_tool("delete_repo", None, None).await.is_none());
        let feed = call(
            &hud,
            "query",
            json!({ "method": "app.bsky.feed.getAuthorFeed", "params": { "actor": "me" } }),
            Some(&me),
        )
        .await
        .unwrap();
        assert_eq!(feed.structured["params"]["actor"], ALICE);
        assert_eq!(feed.meta["viewer"]["did"], ALICE);
        let page = call(
            &hud,
            "describe_app",
            json!({ "domain": "bsky.app" }),
            Some(&me),
        )
        .await
        .unwrap();
        assert_eq!(page.structured["actor"]["did"], ALICE);
        assert_eq!(page.structured["mine"], true);
        let blog = call(
            &hud,
            "describe_app",
            json!({ "domain": "standard.site", "actor": "me" }),
            Some(&me),
        )
        .await
        .unwrap();
        assert!(
            blog.text.ends_with("Yours here: 1 collection."),
            "{}",
            blog.text
        );
        // Another's profile asks whether they can be messaged; one's own
        // does not.
        let bob = call(
            &hud,
            "describe_repo",
            json!({ "actor": "bob.test" }),
            Some(&me),
        )
        .await
        .unwrap();
        assert_eq!(
            bob.text,
            format!("bob.test ({BOB}) on {url}. No collections.")
        );
        assert_eq!(messaged(&asked), 1);
        call(&hud, "describe_repo", json!({ "actor": "me" }), Some(&me))
            .await
            .unwrap();
        assert_eq!(messaged(&asked), 1);
    }

    /// Recorded answers resolved: an error loses the view's keys alone; a
    /// query's with no view is its JSON tree; one drawn by an inline view
    /// is untrusted; an account's profile whose pictures name no server
    /// takes its icons from HUD's default.
    #[test]
    fn recorded_answers_resolve() {
        let viewer = json!({ "did": ALICE, "handle": "alice.test" });
        let mut failed = json!({ "isError": true, "_meta": { "view": { "mode": "list" },
            "lexicon": null, "handles": {}, "viewer": viewer } });
        resolve_answer(&mut failed, Some("list_records"), None).unwrap();
        assert_eq!(failed["_meta"], json!({ "viewer": viewer }));
        let structured = json!({ "method": "m", "response": { "a": 1 } });
        let mut answered = json!({ "structuredContent": structured, "_meta": {} });
        resolve_answer(&mut answered, Some("query"), None).unwrap();
        assert_eq!(answered["_meta"]["ui"], json_ui(&structured));
        let inline = json!({ "collection": "com.example.many", "description": "Many",
            "list": { "layout": { "component": "Text", "props": { "value": "many" } } } });
        let mut drawn = json!({ "structuredContent": { "did": ALICE, "collection": "com.example.many",
                                                      "records": [], "cursor": null },
            "_meta": { "view": { "doc": inline, "mode": "list", "trusted": false,
                                 "origins": ["https://evil.example"] } } });
        resolve_answer(&mut drawn, Some("list_records"), None).unwrap();
        assert_eq!(drawn["_meta"]["ui"]["trusted"], false);
        assert_eq!(words(&drawn["_meta"]["ui"]), ["many"]);
        let mut profile = json!({ "structuredContent": { "did": ALICE, "handle": "alice.test",
            "pds": "https://pds.example", "collections": ["app.bsky.feed.post"],
            "profile": null, "views": [] }, "_meta": {} });
        resolve_answer(&mut profile, Some("describe_repo"), None).unwrap();
        assert_eq!(
            profile["structuredContent"]["apps"][0]["icon"],
            "http://localhost:8787/icon/bsky.app"
        );
        let feed = view::for_method("app.bsky.feed.getAuthorFeed").unwrap();
        let mut paged = json!({ "structuredContent": { "method": "app.bsky.feed.getAuthorFeed",
                "service": "did:web:api.bsky.app#bsky_appview", "params": { "actor": ALICE },
                "response": { "feed": [], "cursor": "c2" } },
            "_meta": { "view": { "doc": feed.doc, "mode": "query", "trusted": true } } });
        resolve_answer(&mut paged, Some("query"), None).unwrap();
        assert_eq!(
            paged["_meta"]["ui"]["next"],
            json!({ "name": "query", "args": { "cursor": "c2" } })
        );
        let mut app = json!({ "structuredContent": { "domain": "standard.site",
                "icon": "https://hud.example/icon/standard.site" }, "_meta": {} });
        resolve_answer(&mut app, Some("describe_app"), None).unwrap();
        assert_eq!(app["_meta"]["ui"]["title"], apps::name("standard.site"));
        let mut invalid = json!({ "structuredContent": {},
            "_meta": { "view": { "doc": {}, "mode": "list" } } });
        let refused = resolve_answer(&mut invalid, Some("list_records"), None);
        assert!(refused.unwrap_err().starts_with("Invalid view: "));
        let mut bare = json!({ "structuredContent": {} });
        assert_eq!(
            resolve_answer(&mut bare, None, None),
            Err("the answer has no _meta object".into())
        );
        let mut nameless = json!({ "structuredContent": {}, "_meta": {} });
        assert_eq!(
            resolve_answer(&mut nameless, Some("describe_app"), None),
            Err("the answer names no domain".into())
        );
        let doc = view::for_collection("site.standard.document")
            .unwrap()
            .doc
            .clone();
        let mut modeless = json!({ "structuredContent": {},
            "_meta": { "view": { "doc": doc, "trusted": true } } });
        assert_eq!(
            resolve_answer(&mut modeless, Some("list_records"), None),
            Err("_meta.view has no mode".into())
        );
    }

    /// The edges of the helpers the tools lean on: an argument of the
    /// wrong type, a limit given, `me` alone as an at-uri, arguments not
    /// an object, a scope that is no object, datetimes behind UTC or none,
    /// and a thing named by a noun that starts with a vowel.
    #[test]
    fn helpers_at_their_edges() {
        let a = json!({ "limit": 5, "cursor": 1 });
        let args = Args::of(Some(&a), &["limit", "cursor"]).unwrap();
        assert_eq!(args.limit(25), Ok(5));
        assert_eq!(args.text("cursor"), Err("cursor must be a string".into()));
        assert_eq!(
            with_me(Some(&json!({ "uri": "at://me" })), Some(ALICE))
                .unwrap()
                .unwrap()["uri"],
            format!("at://{ALICE}")
        );
        assert_eq!(with_me(Some(&json!("me")), None), Ok(None));
        assert_eq!(with_me(None, None), Ok(None));
        assert_eq!(
            record_scope(&json!({ "did": "d" }), &Value::Null),
            json!({ "did": "d" })
        );
        assert_eq!(datetime_millis("yesterday"), None);
        assert_eq!(
            datetime_millis("2026-11-16T05:20:00-05:00"),
            datetime_millis("2026-11-16T10:20:00Z")
        );
        let issue = json!({ "uri": format!("at://{ALICE}/dev.knotless.issue/3abc"),
                            "value": { "createdAt": "2026-11-16T10:00:00.000Z" } });
        assert_eq!(
            activity_of("dev.knotless.issue", &issue).unwrap().words,
            "Opened an issue"
        );
    }

    /// A name outside the read tools, asked of `call_read_tool` directly
    /// (as a read tool added to `canvas::TOOLS` but not to its match
    /// would be), is refused, never run as another tool.
    #[tokio::test]
    async fn only_read_tools_are_read() {
        let (hud, asked, _) = served(Vec::<(String, Value)>::new(), |_| {}).await;
        let args = json!({ "uri": format!("at://{ALICE}/app.bsky.feed.post/3abc") });
        assert_eq!(
            hud.call_read_tool("create_record", Some(&args), None)
                .await
                .err(),
            Some(Refusal::Error("create_record is not a read tool".into()))
        );
        assert!(asked.lock().unwrap().is_empty());
    }

    /// An app page's page more: the join that pages it alone, asked from
    /// the cursor for the account named; refused where it does not
    /// answer, where there is no account, or where the page has none.
    #[tokio::test]
    async fn an_app_page_pages_its_join() {
        let (hud, _, _) = served(alice(), |_| {}).await;
        let app = |args: Value| {
            let hud = hud.clone();
            async move { call(&hud, "describe_app", args, None).await }
        };
        let more = app(json!({ "domain": "grain.social", "actor": "alice.test", "cursor": "g1" }))
            .await
            .unwrap();
        let joins = more.structured["joins"].as_object().unwrap();
        assert_eq!(joins.keys().collect::<Vec<_>>(), ["galleries"]);
        assert_eq!(joins["galleries"]["cursor"], "g2");
        assert_eq!(more.structured["actor"]["did"], ALICE);
        let name = apps::name("grain.social");
        assert_eq!(
            app(json!({ "domain": "grain.social", "actor": "alice.test", "cursor": "broken" }))
                .await
                .err(),
            Some(Refusal::Error(format!(
                "{name}'s page more did not answer (social.grain.feed.getFeed)"
            )))
        );
        assert_eq!(
            app(json!({ "domain": "grain.social", "cursor": "g1" }))
                .await
                .err(),
            Some(Refusal::Error(format!(
                "{name}'s page more is of an account: name one, or sign in"
            )))
        );
        assert_eq!(
            app(json!({ "domain": "standard.site", "cursor": "g1" }))
                .await
                .err(),
            Some(Refusal::Error(format!(
                "{}'s page has no page more",
                apps::name("standard.site")
            )))
        );
    }

    /// The calls for their own pages after (`p.next`) of the listings a
    /// tree draws, in its order.
    fn own_nexts(n: &Value) -> Vec<Value> {
        match n {
            Value::Object(o) => {
                let own = o.get("p").and_then(|p| p.get("next")).cloned();
                own.into_iter()
                    .chain(o.values().flat_map(own_nexts))
                    .collect()
            }
            Value::Array(a) => a.iter().flat_map(own_nexts).collect(),
            _ => Vec::new(),
        }
    }

    /// Grain's profile's panes each page themselves: the Covers of each
    /// join that answered a cursor carries `describe_app` for the same
    /// account with its page token, made for who reads it; the tree's
    /// `next` still pages the galleries, for a kit that knows no listing's.
    #[test]
    fn grain_profile_panes_page_themselves() {
        let did = "did:plc:dan";
        let v = view::for_domain("grain.social").unwrap();
        let app = json!({ "domain": "grain.social", "name": "Grain",
                          "icon": apps::icon("https://hud.example", "grain.social") });
        let me = Some((did, Some("dan.example")));
        let mut scope = page_scope(app, (did, Some("dan.example")), me, &[]);
        scope["joins"] = json!({
            "profile": { "did": did, "handle": "dan.example", "galleryCount": 40 },
            "galleries": { "items": [], "cursor": "g18" },
            "favorites": { "items": [], "cursor": "f30" },
            "stories": { "stories": [], "cursor": "s50" },
        });
        let page = page_ui(v, &scope, Some(did));
        assert_eq!(ui::check(&page), Ok(()), "{page:#}");
        let call = |join: &str, cursor: &str| {
            json!({ "name": "describe_app", "args": { "domain": "grain.social", "actor": did,
                    "more": crate::more::token(join, cursor, Some(did)) } })
        };
        assert_eq!(
            own_nexts(&page["root"]),
            vec![
                call("galleries", "g18"),
                call("favorites", "f30"),
                call("stories", "s50")
            ]
        );
        assert_eq!(page["next"]["args"]["cursor"], "g18");
    }

    /// A pane's page more, by its token: that join alone, asked from its
    /// cursor for the account the page is of, as the account calling, its
    /// Covers alone drawn with the next after it, none at the end. Refused
    /// to another account than it was read as, and to no one; on another's
    /// page, where one's own favorites never run; for a join the page has
    /// not.
    #[tokio::test]
    async fn a_pane_pages_itself_by_its_token() {
        let (hud, _, url) = served(alice(), |c| {
            c.oauth = true;
            c.oauth_scope = crate::scope::asked(crate::view::views(), true, false);
        })
        .await;
        let auth = hud.auth().unwrap();
        let me = auth
            .account(&auth.signed_in_offline_at(ALICE, Some("alice.test"), false, &url))
            .unwrap();
        let name = apps::name("grain.social");
        let page = json!({ "domain": "grain.social", "actor": "alice.test" });
        let page = call(&hud, "describe_app", page, Some(&me)).await.unwrap();
        // Her galleries and favorites go on; her stories end at their first page.
        let nexts = own_nexts(&page.meta["ui"]["root"]);
        assert_eq!(nexts.len(), 2, "{nexts:#?}");
        let token = crate::more::token("favorites", "f2", Some(ALICE));
        assert_eq!(nexts[1]["args"]["more"], token);
        let favorites = nexts[1]["args"].clone();
        let more = call(&hud, "describe_app", favorites.clone(), Some(&me))
            .await
            .unwrap();
        let ui = &more.meta["ui"];
        assert_eq!(ui::check(ui), Ok(()), "{ui:#}");
        assert_eq!(ui["root"]["c"], "Covers");
        assert!(ui["root"]["p"].get("next").is_none(), "{ui:#}");
        let joins = more.structured["joins"].as_object().unwrap();
        assert_eq!(joins.keys().collect::<Vec<_>>(), ["favorites"]);
        let galleries = call(&hud, "describe_app", nexts[0]["args"].clone(), Some(&me))
            .await
            .unwrap();
        assert_eq!(
            galleries.meta["ui"]["root"]["p"]["next"]["args"]["more"],
            crate::more::token("galleries", "g2", Some(ALICE))
        );
        let refused = |args: Value, account: Option<Account>| {
            let hud = hud.clone();
            async move {
                call(&hud, "describe_app", args, account.as_ref())
                    .await
                    .err()
            }
        };
        let error = |why: String| Some(Refusal::Error(why));
        assert_eq!(
            refused(favorites, None).await,
            error("This page was read as another account: open it again".into())
        );
        let bobs = json!({ "domain": "grain.social", "actor": "bob.test", "more": token });
        assert_eq!(
            refused(bobs, Some(me.clone())).await,
            error(format!(
                "{name}'s page more did not answer (social.grain.actor.getFavorites)"
            ))
        );
        let nope = crate::more::token("nope", "x", Some(ALICE));
        let nope = json!({ "domain": "grain.social", "actor": "alice.test", "more": nope });
        assert_eq!(
            refused(nope, Some(me.clone())).await,
            error(format!("{name}'s page has no nope to page"))
        );
        // Signed in, Explore's recent galleries too, by a token made for her.
        let recent = crate::more::token("recent", "g1", Some(ALICE));
        let explore = json!({ "method": "social.grain.gallery.getLocations", "more": recent });
        let explore = call(&hud, "query", explore, Some(&me)).await.unwrap();
        assert_eq!(explore.meta["ui"]["root"]["c"], "Covers");
    }

    /// Explore's recent galleries page themselves: `query` with the
    /// token asks that join alone, the query itself not again, and draws
    /// its Covers with the next after it. Refused for a join the view has
    /// not and one that does not answer; a join no listing pages (its
    /// cameras, which the view cuts at ten) draws nothing to page. Drawn
    /// as an untrusted view, its accounts name no app to open in.
    #[tokio::test]
    async fn explore_pages_its_recent_galleries() {
        let (hud, asked, _) = served(alice(), |_| {}).await;
        let method = "social.grain.gallery.getLocations";
        let first = call(&hud, "query", json!({ "method": method }), None)
            .await
            .unwrap();
        let token = |join: &str, cursor: &str| crate::more::token(join, cursor, None);
        let more =
            |join: &str, cursor: &str| json!({ "method": method, "more": token(join, cursor) });
        let nexts = own_nexts(&first.meta["ui"]["root"]);
        assert_eq!(
            nexts,
            vec![json!({ "name": "query", "args": more("recent", "g2") })]
        );
        let page = call(&hud, "query", nexts[0]["args"].clone(), None)
            .await
            .unwrap();
        let ui = &page.meta["ui"];
        assert_eq!(ui::check(ui), Ok(()), "{ui:#}");
        assert_eq!(ui["root"]["c"], "Covers");
        assert_eq!(ui["root"]["p"]["next"]["args"], more("recent", "g2"));
        let path = format!("/xrpc/{method}");
        let times = asked.lock().unwrap().iter().filter(|p| **p == path).count();
        assert_eq!(times, 1);
        for ((join, cursor), why) in [
            (
                ("nope", "x"),
                format!("{method}'s view has no nope to page"),
            ),
            (
                ("recent", "broken"),
                format!("{method}'s recent did not answer (social.grain.feed.getFeed)"),
            ),
        ] {
            assert_eq!(
                call(&hud, "query", more(join, cursor), None).await.err(),
                Some(Refusal::Error(why))
            );
        }
        let v = view::for_method(method).unwrap();
        let scope = json!({ "params": {}, "joins": { "cameras": { "cameras": [] } } });
        let drawn = more_ui(v, true, &v.doc["query"], &scope, ("cameras", vec![]), None);
        assert_eq!(drawn, Err("Nothing on this screen pages cameras".into()));
        let recent = json!({ "params": {}, "joins": { "recent": { "items": [] } } });
        let untrusted = more_ui(v, false, &v.doc["query"], &recent, ("recent", vec![]), None);
        let untrusted = untrusted.unwrap();
        assert_eq!(untrusted["root"]["c"], "Covers");
        assert!(untrusted.get("people").is_none(), "{untrusted:#}");
    }
}