chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.5.0 Latest 5 packages
0
0
//! A resolved tree held to its lexicon (`schemas/place.hud.ui.json`)
//! with the `atproto` crate's lexicon validation: the tree against `main`,
//! then each node's props against the def its component names
//! (`#<component>Props`, its first letter lower case) and its items against
//! their component's item def, wherever nodes are: a node's children, a
//! list's or a tree's items and theirs, a feed context's posts. Nodes are
//! told apart by `c`, which the validator cannot follow as it follows a
//! union's `$type`, so this does.
use atproto::lexicon::{LexiconError, Lexicons};
use serde_json::{Value, json};
use std::sync::LazyLock;
/// The tree's lexicon.
const NSID: &str = "place.hud.ui";
/// The def each component's items are, by component.
const ITEMS: &[(&str, &str)] = &[
("List", "listItem"),
("Messages", "messageItem"),
("Tree", "treeItem"),
("Chain", "treeItem"),
("Gallery", "galleryItem"),
("Covers", "coverItem"),
("Player", "playerItem"),
("Slides", "slideItem"),
("Map", "mapPin"),
];
static LEXICON: LazyLock<Lexicons> = LazyLock::new(|| {
let doc = crate::lexicon::bundled(NSID).expect("schemas/place.hud.ui.json is bundled");
Lexicons::new([(*doc).clone()])
});
/// Whether a tree is what its lexicon describes; else every problem found,
/// each where it is (`ui.root.k[0].p.runs`).
pub fn check(tree: &Value) -> Result<(), Vec<String>> {
let mut problems = Vec::new();
held(NSID, tree, "ui", &mut problems);
node(&tree["root"], "ui.root", &mut problems);
if problems.is_empty() {
Ok(())
} else {
Err(problems)
}
}
/// `value` checked against the def `reference` names, a failure said at `at`.
fn held(reference: &str, value: &Value, at: &str, problems: &mut Vec<String>) {
if let Err(e) = LEXICON.validate(reference, value) {
problems.push(said(&e, at));
}
}
/// A failure, its path from `at` rather than from the validator's top.
fn said(e: &LexiconError, at: &str) -> String {
let rest = ["object", "record"]
.into_iter()
.find_map(|top| e.path.strip_prefix(top))
.unwrap_or(&e.path);
format!("{at}{rest} {}", e.message)
}
/// A component's name with its first letter lower case, as its props' def
/// is named: `richText` for RichText.
fn lowered(c: &str) -> String {
let mut chars = c.chars();
chars
.next()
.map(|first| first.to_lowercase().chain(chars).collect())
.unwrap_or_default()
}
/// A node's props and items, and the nodes in it. What is not a node at all
/// is `main`'s to say, as `#node` refs reach it.
fn node(n: &Value, at: &str, problems: &mut Vec<String>) {
let Some(c) = n["c"].as_str() else {
return;
};
let props = format!("{NSID}#{}Props", lowered(c));
if LEXICON.def(&props).is_none() {
problems.push(format!("{at}.c {c} is no component the lexicon describes"));
return;
}
let none = json!({});
held(
&props,
n.get("p").unwrap_or(&none),
&format!("{at}.p"),
problems,
);
for (i, k) in n["k"].as_array().into_iter().flatten().enumerate() {
node(k, &format!("{at}.k[{i}]"), problems);
}
if let Some(fallback) = n.get("fallback") {
node(fallback, &format!("{at}.fallback"), problems);
}
if let Some(items) = n.get("items") {
let Some((_, def)) = ITEMS.iter().find(|(of, _)| *of == c) else {
problems.push(format!("{at}.items a {c} has no items"));
return;
};
let reference = format!("{NSID}#{def}");
for (i, item) in items.as_array().into_iter().flatten().enumerate() {
let at = format!("{at}.items[{i}]");
held(&reference, item, &at, problems);
within(item, &at, problems);
}
}
if c == "FeedContext" {
for part in ["top", "parent"] {
let post = &n["p"]["thread"][part];
if post.is_object() {
within(post, &format!("{at}.p.thread.{part}"), problems);
}
}
}
}
/// The nodes in an item: its children (`k`), and those of the items
/// nested under it (a tree's `children`).
fn within(item: &Value, at: &str, problems: &mut Vec<String>) {
for (i, k) in item["k"].as_array().into_iter().flatten().enumerate() {
node(k, &format!("{at}.k[{i}]"), problems);
}
let nested = item["children"].as_array().into_iter().flatten();
for (i, nested) in nested.enumerate() {
within(nested, &format!("{at}.children[{i}]"), problems);
}
}
/// A node the resolver drew, as the top of a tree, held to the lexicon:
/// for the resolver's tests.
#[cfg(test)]
pub(super) fn checked(node: &Value) {
let tree = json!({ "v": 1, "trusted": true, "root": node });
assert_eq!(check(&tree), Ok(()), "{node}");
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{tools, view};
#[test]
fn every_recorded_answer_resolves_to_a_tree_its_lexicon_holds() {
let text = include_str!("../../../../harness/look/tools.json");
let recorded: Value = serde_json::from_str(text).unwrap();
let calls = recorded["calls"].as_object().unwrap();
let mut drawn = 0;
for (call, answer) in calls {
let (tool, arguments) = call.split_once(' ').unwrap();
let arguments: Value = serde_json::from_str(arguments).unwrap();
let mut answer = answer.clone();
// Its bundled view as this checkout has it, as `just look` draws it.
let doc = &answer["_meta"]["view"]["doc"];
let now = doc["method"]
.as_str()
.and_then(view::for_method)
.or_else(|| doc["collection"].as_str().and_then(view::for_collection));
if let Some(v) = now {
answer["_meta"]["view"]["doc"] = v.doc.clone();
}
let resolved = tools::resolve_answer(&mut answer, Some(tool), Some(&arguments));
assert_eq!(resolved, Ok(()), "{call}");
let tree = &answer["_meta"]["ui"];
assert!(tree.is_object(), "{call}: no tree");
drawn += 1;
assert_eq!(check(tree), Ok(()), "{call}");
}
assert_eq!(drawn, calls.len());
}
#[test]
fn a_node_off_its_shape_is_said_where_it_is() {
let tree = json!({ "v": 1, "trusted": false, "root": { "c": "Stack", "p": { "gap": "md" }, "k": [
{ "c": "Text", "p": { "runs": [{ "text": 1 }], "style": "body" } },
{ "c": "List", "p": { "style": "rows" }, "items": [{ "k": [{ "c": "Badge", "p": {} }] }] },
{ "c": "Sparkle" },
{ "c": "Badge", "p": { "value": "x" }, "items": [] },
] } });
assert_eq!(
check(&tree).unwrap_err(),
[
"ui.root.k[0].p.runs[0].text must be a string",
"ui.root.k[1].items[0].k[0].p must have the property \"value\"",
"ui.root.k[2].c Sparkle is no component the lexicon describes",
"ui.root.k[3].items a Badge has no items",
]
);
let bare = json!({ "v": 1, "root": { "c": "Stack" } });
assert_eq!(
check(&bare).unwrap_err(),
["ui must have the property \"trusted\""]
);
let nameless = json!({ "v": 1, "trusted": true, "root": { "p": {} } });
assert_eq!(
check(&nameless).unwrap_err(),
["ui.root must have the property \"c\""],
"what is no node at all is main's to say, once"
);
}
}