chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.6.0 Latest 5 packages
0
0
A playground at /playground writes a view beside what it draws
crates/hud-core/src/catalog.rs+3−3
| @@ -441,7 +441,7 @@ pub const COMPONENTS: &[Component] = &[ | ||
lit!("size", Ty::OneOf(&["avatar", "face", "large", "icon"])), | ||
], | ||
children: false, | ||
notes: "One image: src is a blob ref (or an https URL of a trusted view's origins); size avatar draws it small and round, as beside an author's name; face larger and round, as a post's author in a column beside the post (a Row of it and a Stack); large largest and round, as a profile's own at its head; icon small as an avatar, a rounded square holding the picture whole, as an app's icon.", | ||
notes: "One image: src is a blob ref (or an https URL of the view's origins); size avatar draws it small and round, as beside an author's name; face larger and round, as a post's author in a column beside the post (a Row of it and a Stack); large largest and round, as a profile's own at its head; icon small as an avatar, a rounded square holding the picture whole, as an app's icon.", | ||
}, | ||
Component { | ||
name: "Stat", | ||
| @@ -859,7 +859,7 @@ pub fn to_json() -> Value { | ||
.collect(); | ||
json!({ | ||
"document": { | ||
"shape": "{ $type?: \"place.hud.view\", collection, description (one line), pageSize?: 1-100, list?: Mode, record?: Mode }, Mode = { join?: [Join or QueryJoin], summary?: Summary, layout: Node }; or, for a query's answers, { method, service: \"did:…#fragment\", description, query: { items?: path to the answer's array, cursor?: path to its cursor, join?: [QueryJoin], summary?: Summary, layout: Node } } (an answer that is one thing, as a thread, has no items: its scope's items and cursor are null, and layouts bind into response); unknown keys anywhere are refused; origins is for bundled views alone, and so is a method view's records: [{ collection, params: { <name>: literal | binding into the record's { uri, cid, did, value } }, activity?: { verb, noun: [singular, plural], label?: binding } }], the collections whose records get_record draws as that query (a post as its thread), where no collection view draws them", | ||
"shape": "{ $type?: \"place.hud.view\", collection, description (one line), pageSize?: 1-100, origins?: [https origin], thumbnails?: [{ from, to }], list?: Mode, record?: Mode }, Mode = { join?: [Join or QueryJoin], summary?: Summary, layout: Node }; or, for a query's answers, { method, service: \"did:…#fragment\", description, query: { items?: path to the answer's array, cursor?: path to its cursor, join?: [QueryJoin], summary?: Summary, layout: Node } } (an answer that is one thing, as a thread, has no items: its scope's items and cursor are null, and layouts bind into response); unknown keys anywhere are refused; origins are the https origins whose URLs media props load, an inline view's only those a bundled view names (as https://cdn.bsky.app), and thumbnails rewrite a URL prefix on them to a smaller picture's; a method view's records is for bundled views alone: [{ collection, params: { <name>: literal | binding into the record's { uri, cid, did, value } }, activity?: { verb, noun: [singular, plural], label?: binding } }], the collections whose records get_record draws as that query (a post as its thread), where no collection view draws them", | ||
"modes": "list draws a page of records (list_records), record one record (get_record), query a query's answer (query; its summary runs over the items, or, with no items, over the scope, as a record's does); a mode left out is drawn generically", | ||
"node": "{ component, props?, children? }: children only where the component takes them", | ||
}, | ||
| @@ -870,7 +870,7 @@ pub fn to_json() -> Value { | ||
"items": "a component with items draws each item with the item as its scope (a Rec, or an element of the array bound)", | ||
"rec": "{ uri, cid, did (the repository's, from uri), value, joins: { <as>: Rec | null | { total, records: [Rec] } } }; a blob ref in value carries a url when the server serves it", | ||
}, | ||
"bindings": "A prop is a literal JSON value or a binding {\"$\": \"path\"} or {\"$\": [\"pathA\", \"pathB\"]} (the first usable value wins). A path is keys joined by dots from the current scope, each [A-Za-z0-9_$]+, at most 10; an array takes a number as its key (records.0); \".\" is the scope itself (an item of an array of strings, such as a tag). No expressions. Media props take a blob ref; an https URL only of a bundled view's origins. Where a prop says orRoot, in an open's params, and as a value in a List's literal items, {\"$root\": \"path\"} reads from the view's own scope rather than the item's.", | ||
"bindings": "A prop is a literal JSON value or a binding {\"$\": \"path\"} or {\"$\": [\"pathA\", \"pathB\"]} (the first usable value wins). A path is keys joined by dots from the current scope, each [A-Za-z0-9_$]+, at most 10; an array takes a number as its key (records.0); \".\" is the scope itself (an item of an array of strings, such as a tag). No expressions. Media props take a blob ref; an https URL only of the view's origins. Where a prop says orRoot, in an open's params, and as a value in a List's literal items, {\"$root\": \"path\"} reads from the view's own scope rather than the item's.", | ||
"actions": "Action's create: { collection: NSID, record: { ... } }, the record at most 4096 bytes as JSON, its values at any depth literal JSON, a binding, {\"$now\": true} (the current time, ISO 8601) or {\"$strongRef\": \"path\"} ({ uri, cid } of what path names, as \".\" for a Rec or \"post\" for a feed item); keys starting with $ are those alone and $type. delete: { uri: binding }. As app.bsky.feed.like: { collection: \"app.bsky.feed.like\", record: { subject: { \"$strongRef\": \".\" }, createdAt: { \"$now\": true } } }.", | ||
"joins": { | ||
"ref": "{ as, ref: path to an at-uri or strongRef, collection? } -> Rec | null", | ||
crates/hud-core/src/tools.rs+231−54
| @@ -1577,18 +1577,8 @@ impl Hud { | ||
} | ||
let read = (&lexicon, &handles); | ||
let ui = self | ||
.call_ui( | ||
chosen.as_ref(), | ||
"list", | ||
&structured, | ||
arguments, | ||
account, | ||
read, | ||
) | ||
.await | ||
.unwrap_or_else(|| { | ||
generic_records_ui(true, &structured, arguments, &lexicon, &handles) | ||
}); | ||
.drawn_records(chosen.as_ref(), true, &structured, arguments, account, read) | ||
.await; | ||
Ok(Output { | ||
text, | ||
structured, | ||
| @@ -1669,18 +1659,15 @@ impl Hud { | ||
} | ||
let read = (&lexicon, &handles); | ||
let ui = self | ||
.call_ui( | ||
.drawn_records( | ||
chosen.as_ref(), | ||
"record", | ||
false, | ||
&structured, | ||
arguments, | ||
account, | ||
read, | ||
) | ||
.await | ||
.unwrap_or_else(|| { | ||
generic_records_ui(false, &structured, arguments, &lexicon, &handles) | ||
}); | ||
.await; | ||
Ok(Output { | ||
text, | ||
structured, | ||
| @@ -1919,31 +1906,111 @@ impl Hud { | ||
text = summary::with_said(text, &q.queries, &joined); | ||
structured["joins"] = Value::Object(joined); | ||
} | ||
let ui = self | ||
.drawn_query(chosen.as_ref(), &structured, arguments, account, def) | ||
.await; | ||
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.as_ref(), | ||
"query", | ||
&structured, | ||
arguments, | ||
account, | ||
none, | ||
) | ||
.call_ui(chosen, "query", structured, arguments, account, none) | ||
.await | ||
.unwrap_or_else(|| json_ui(&structured)); | ||
// What tells something newer came asks for the newest items alone, | ||
// where the method takes a limit (`peek_limit`). | ||
.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(); | ||
} | ||
} | ||
Ok(Output { | ||
text, | ||
structured, | ||
meta: json!({ "ui": ui }), | ||
}) | ||
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 | ||
| @@ -2245,27 +2312,23 @@ fn generic_records_ui( | ||
out | ||
} | ||
| ||
/// What a view's drawing is read with, beside its scope: a bundled view's | ||
/// origins and thumbnails, an inline one's none; an inline one's | ||
/// collection, a record of which opens with it. | ||
/// 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 = if trusted { | ||
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() | ||
} else { | ||
Vec::new() | ||
}; | ||
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: if trusted { v.origins.as_slice() } else { &[] }, | ||
origins: v.origins.as_slice(), | ||
thumbnails, | ||
trusted, | ||
root, | ||
| @@ -3470,6 +3533,16 @@ mod tests { | ||
); | ||
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( | ||
| @@ -3484,7 +3557,7 @@ mod tests { | ||
.err() | ||
.unwrap(); | ||
assert!( | ||
err.starts_with("Invalid view: 2 problems: view.origins: "), | ||
err.starts_with("Invalid view: 2 problems: view.origins[0]: "), | ||
"{err}" | ||
); | ||
// A query's view: inline, of that method alone; else the bundled one. | ||
| @@ -4747,6 +4820,110 @@ mod tests { | ||
); | ||
} | ||
| ||
/// 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. | ||
crates/hud-core/src/view.rs+92−31
| @@ -543,6 +543,29 @@ impl Problems { | ||
} | ||
} | ||
| ||
/// What only a bundled view may say at its top, which a view given inline | ||
/// may not. | ||
const BUNDLED_ONLY: [&str; 7] = [ | ||
"interactions", | ||
"signIn", | ||
"launch", | ||
"records", | ||
"app", | ||
"profile", | ||
"activity", | ||
]; | ||
| ||
/// A bundled view's document as a view given inline may be, for the | ||
/// playground to start from: less what only a bundled view may say at its | ||
/// top. What its layout does that only a bundled view may (a procedure | ||
/// called, a feed told what was read) stays, a problem to take out. | ||
pub fn inline_copy(doc: &Value) -> Value { | ||
let mut copy = doc.clone(); | ||
let top = copy.as_object_mut().into_iter(); | ||
top.for_each(|o| o.retain(|k, _| !BUNDLED_ONLY.contains(&k.as_str()))); | ||
copy | ||
} | ||
| ||
/// Check a document; a view, or every problem with it. An untrusted | ||
/// view may not name origins. | ||
pub fn parse(doc: &Value, trusted: bool) -> Result<View, Vec<String>> { | ||
| @@ -640,19 +663,10 @@ fn parse_view(p: &mut Problems, doc: &Value, trusted: bool) -> Option<View> { | ||
let description = p.line(o.get("description"), "view.description", 200); | ||
let origins = match o.get("origins") { | ||
None => Vec::new(), | ||
Some(_) if !trusted => { | ||
p.add( | ||
"view.origins", | ||
"only a bundled view may name origins; load media through blob refs", | ||
); | ||
Vec::new() | ||
} | ||
Some(v) => origins(p, v), | ||
Some(v) => origins(p, v, trusted), | ||
}; | ||
match o.get("thumbnails") { | ||
None => {} | ||
Some(_) if !trusted => p.add("view.thumbnails", "only a bundled view may name thumbnails"), | ||
Some(v) => thumbnails(p, v, &origins), | ||
if let Some(v) = o.get("thumbnails") { | ||
thumbnails(p, v, &origins); | ||
} | ||
let refuse = |p: &mut Problems, k: &str, why: &str| { | ||
if o.contains_key(k) { | ||
| @@ -1447,10 +1461,12 @@ fn layout(p: &mut Problems, v: Option<&Value>, at: &str) { | ||
} | ||
} | ||
| ||
/// A trusted view's origins: `https://host[:port]` each, written as the URL | ||
/// A view's origins: `https://host[:port]` each, written as the URL | ||
/// standard serializes it (lower case, no default port, at most a trailing | ||
/// `/`). | ||
fn origins(p: &mut Problems, v: &Value) -> Vec<String> { | ||
/// `/`). A bundled view may name any; a view given inline only those a | ||
/// bundled view names, which every page that draws a view lets it load | ||
/// already (`csp_origins`), so its CSP is never wider. | ||
fn origins(p: &mut Problems, v: &Value, trusted: bool) -> Vec<String> { | ||
let Some(a) = v | ||
.as_array() | ||
.filter(|a| (1..=MAX_ORIGINS).contains(&a.len())) | ||
| @@ -1463,17 +1479,36 @@ fn origins(p: &mut Problems, v: &Value) -> Vec<String> { | ||
}; | ||
let mut out = Vec::new(); | ||
for (i, o) in a.iter().enumerate() { | ||
let at = format!("view.origins[{i}]"); | ||
match o.as_str().and_then(origin) { | ||
Some(o) => out.push(o), | ||
None => p.add( | ||
&format!("view.origins[{i}]"), | ||
"must be an origin, as https://host[:port]", | ||
Some(o) if !trusted && !bundled_origins().contains(&o) => p.add( | ||
&at, | ||
format_args!( | ||
"a view given inline names only origins a bundled view names: {}", | ||
bundled_origins().join(", ") | ||
), | ||
), | ||
Some(o) => out.push(o), | ||
None => p.add(&at, "must be an origin, as https://host[:port]"), | ||
} | ||
} | ||
out | ||
} | ||
| ||
/// Every origin the bundled views name, sorted, each once. | ||
fn bundled_origins() -> &'static [String] { | ||
static ALL: LazyLock<Vec<String>> = LazyLock::new(|| { | ||
let mut all: Vec<String> = bundled() | ||
.iter() | ||
.flat_map(|b| b.view.origins.iter().cloned()) | ||
.collect(); | ||
all.sort(); | ||
all.dedup(); | ||
all | ||
}); | ||
&ALL | ||
} | ||
| ||
/// An origin written as `https://host[:port]` and nothing more. | ||
pub fn origin(s: &str) -> Option<String> { | ||
let u = url::Url::parse(s).ok()?; | ||
| @@ -2964,6 +2999,25 @@ mod tests { | ||
"list": { "layout": layout } }) | ||
} | ||
| ||
/// A bundled view's inline copy says nothing at its top that only a | ||
/// bundled view may: what is left is in its layout, procedures called | ||
/// and interactions sent. | ||
#[test] | ||
fn bundled_views_copied_to_draw_inline() { | ||
for b in bundled().iter().filter(|b| b.view.page.is_none()) { | ||
let copy = inline_copy(&b.view.doc); | ||
for p in problems(©, false) { | ||
assert!( | ||
p.ends_with("only a bundled view calls procedures") | ||
|| p.ends_with("only a bundled view sends interactions"), | ||
"{}: {p}", | ||
b.id | ||
); | ||
} | ||
} | ||
assert_eq!(inline_copy(&json!(1)), json!(1)); | ||
} | ||
| ||
#[test] | ||
fn every_bundled_view_validates() { | ||
assert_eq!(bundled().len(), VIEWS.len()); | ||
| @@ -3381,11 +3435,12 @@ mod tests { | ||
| ||
#[test] | ||
fn documents() { | ||
// Unknown keys, a missing collection and modes, a bad type, origins inline. | ||
// Unknown keys, a missing collection and modes, a bad type, an | ||
// origin no bundled view names. | ||
let doc = json!({ "$type": "x.y.z", "description": "d", "extra": 1, "origins": ["https://a.example"] }); | ||
assert_eq!( | ||
wheres(&doc), | ||
["view", "view.$type", "view", "view.origins", "view"] | ||
["view", "view.$type", "view", "view.origins[0]", "view"] | ||
); | ||
// Trusted, origins are checked and kept. | ||
let mut trusted = posts(json!({ "component": "Badge", "props": { "value": "x" } })); | ||
| @@ -3403,10 +3458,16 @@ mod tests { | ||
trusted["origins"] = json!([bad]); | ||
assert_eq!(problems(&trusted, true).len(), 1, "{bad}"); | ||
} | ||
// Inline, only the origins a bundled view names: those load where | ||
// any view is drawn already. | ||
trusted["origins"] = json!(["https://a.example"]); | ||
assert_eq!( | ||
problems(&trusted, false), | ||
["view.origins: only a bundled view may name origins; load media through blob refs"] | ||
let refused = problems(&trusted, false); | ||
assert_eq!(refused.len(), 1); | ||
assert!( | ||
refused[0].starts_with( | ||
"view.origins[0]: a view given inline names only origins a bundled view names: " | ||
) && refused[0].contains("https://cdn.bsky.app"), | ||
"{refused:?}" | ||
); | ||
// Thumbnails: a trusted view's, on its origins. | ||
trusted["thumbnails"] = | ||
| @@ -3421,14 +3482,14 @@ mod tests { | ||
trusted["thumbnails"] = bad.clone(); | ||
assert_eq!(problems(&trusted, true).len(), 1, "{bad}"); | ||
} | ||
trusted["thumbnails"] = | ||
json!([{ "from": "https://a.example/big/", "to": "https://a.example/small/" }]); | ||
// Inline, thumbnails on origins a bundled view names are kept. | ||
let mut inline = trusted.clone(); | ||
inline["origins"] = json!(["https://cdn.bsky.app"]); | ||
inline["thumbnails"] = json!([{ "from": "https://cdn.bsky.app/img/avatar/plain/", | ||
"to": "https://cdn.bsky.app/img/avatar_thumbnail/plain/" }]); | ||
assert_eq!( | ||
problems(&trusted, false), | ||
[ | ||
"view.origins: only a bundled view may name origins; load media through blob refs", | ||
"view.thumbnails: only a bundled view may name thumbnails" | ||
] | ||
parse(&inline, false).unwrap().origins, | ||
["https://cdn.bsky.app"] | ||
); | ||
// A mode needs its layout. | ||
let doc = json!({ "collection": "a.b.c", "description": "d", "record": {} }); | ||
crates/hud-server/src/xrpc/tests.rs+131−3
| @@ -483,12 +483,17 @@ fn err(status: StatusCode, error: &str) -> (StatusCode, String) { | ||
async fn signed_in_by_cookie_or_token() { | ||
let (hud, _) = server(None).await; | ||
let (cookie, token) = sessions(&hud, ALICE, "alice.test"); | ||
// Signed out, every method asks for sign-in, but a sign-in's own | ||
// suggestions. | ||
// Signed out, every method asks for sign-in, but anyone's: a | ||
// sign-in's own suggestions and the playground's. | ||
let anyones = [ | ||
"place.hud.searchActors", | ||
"place.hud.getPlayground", | ||
"place.hud.previewView", | ||
]; | ||
for doc in hud_core::lexicon::all_bundled() { | ||
let Some(id) = doc["id"] | ||
.as_str() | ||
.filter(|id| id.starts_with(NS) && *id != "place.hud.searchActors") | ||
.filter(|id| id.starts_with(NS) && !anyones.contains(id)) | ||
else { | ||
continue; | ||
}; | ||
| @@ -1579,6 +1584,129 @@ async fn tools_called_as_the_mcp_endpoint_answers() { | ||
} | ||
} | ||
| ||
/// The playground's methods, anyone's: what it starts from; a view's | ||
/// problems, every one, nothing read; a view read afresh, as no one or as | ||
/// the page's account, then drawn again over that answer; and what is | ||
/// refused. | ||
#[tokio::test] | ||
async fn the_playground_draws_a_view() { | ||
let (hud, double) = server(None).await; | ||
let palette = hud_core::theme::builtin("paper").unwrap()["palette"].clone(); | ||
double.lock().unwrap().themes = vec![( | ||
BOB, | ||
"3lsand", | ||
json!({ "$type": "place.hud.theme", "name": "Sand", "colorScheme": "light", | ||
"palette": palette, "createdAt": "2026-11-17T00:00:00.000Z" }), | ||
)]; | ||
let (status, started) = get(&hud, As::Nobody)("getPlayground").await; | ||
assert_eq!(status, OK); | ||
let ids: Vec<&str> = started["views"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.map(|v| v["name"].as_str().unwrap()) | ||
.collect(); | ||
assert!(ids.contains(&"grain-gallery-view"), "{ids:?}"); | ||
// Each as a view given inline may be, with its app; no app pages. | ||
assert!(!ids.contains(&"bsky-app"), "{ids:?}"); | ||
let gallery = started["views"] | ||
.as_array() | ||
.unwrap() | ||
.iter() | ||
.find(|v| v["name"] == "grain-gallery-view") | ||
.unwrap(); | ||
assert_eq!(gallery["app"], "Grain"); | ||
assert!(gallery["view"].get("app").is_none()); | ||
assert_eq!( | ||
gallery["view"]["origins"], | ||
json!(["https://cdn.grain.social"]) | ||
); | ||
assert!(hud_core::view::parse(&gallery["view"], false).is_ok()); | ||
assert_eq!(started["themes"], json!(hud_core::theme::all())); | ||
assert!(started["catalog"].is_object()); | ||
let view = |path: &str| { | ||
json!({ "collection": "place.hud.theme", "description": "Themes", "list": { | ||
"layout": { "component": "Text", "props": { "value": { "$": path } } } } }) | ||
}; | ||
let call = |view: Json| { | ||
json!({ "tool": "list_records", | ||
"arguments": { "actor": BOB, "collection": "place.hud.theme", "view": view } }) | ||
}; | ||
let anyone = post(&hud, As::Nobody); | ||
let (status, read) = anyone("previewView", call(view("records.0.value.name"))).await; | ||
assert_eq!(status, OK); | ||
let result = &read["result"]; | ||
assert_eq!(result["isError"], false, "{result}"); | ||
assert!(result["_meta"]["ui"].to_string().contains("Sand")); | ||
assert!(result["_meta"].get("viewer").is_none()); | ||
// Drawn again over that answer, by another layout. | ||
let mut again = call(view("records.0.value.colorScheme")); | ||
again["answer"] = result["structuredContent"].clone(); | ||
let (status, drawn) = anyone("previewView", again.clone()).await; | ||
assert_eq!(status, OK); | ||
assert!(drawn["ui"].to_string().contains("light"), "{drawn}"); | ||
assert!(drawn.get("result").is_none()); | ||
// A view that is not valid: its problems, by where, nothing read. | ||
let mut bad = view("x"); | ||
bad["list"]["layout"]["component"] = json!("Nope"); | ||
let (status, checked) = anyone("previewView", call(bad)).await; | ||
assert_eq!(status, OK); | ||
assert_eq!(checked["problems"][0]["at"], "list.layout.component"); | ||
assert!(checked.get("result").is_none()); | ||
// As the page's account, its result says whose. | ||
let (alice, _) = sessions(&hud, ALICE, "alice.test"); | ||
let (status, mine) = post(&hud, As::Page(&alice))("previewView", call(view("did"))).await; | ||
assert_eq!(status, OK); | ||
assert_eq!(mine["result"]["_meta"]["viewer"]["did"], ALICE); | ||
// A tool's error is its result's. | ||
let (status, broken) = anyone( | ||
"previewView", | ||
json!({ "tool": "get_record", "arguments": { "uri": "nope", "view": view("did") } }), | ||
) | ||
.await; | ||
assert_eq!((status, &broken["result"]["isError"]), (OK, &json!(true))); | ||
// Signed out, a call that needs an account is the result's error. | ||
let (_, me) = anyone( | ||
"previewView", | ||
json!({ "tool": "list_records", "arguments": { "actor": "me", | ||
"collection": "place.hud.theme", "view": view("did") } }), | ||
) | ||
.await; | ||
assert_eq!( | ||
( | ||
&me["result"]["isError"], | ||
&me["result"]["content"][0]["text"] | ||
), | ||
(&json!(true), &json!("Sign in to HUD to read this")) | ||
); | ||
// Refused: the cookie from another site's page, a tool that draws no | ||
// view, no view, an answer not of the call, and too much. | ||
assert_eq!( | ||
failed(post(&hud, As::Cookie(&alice))("previewView", call(view("did"))).await), | ||
err(StatusCode::FORBIDDEN, "InvalidRequest") | ||
); | ||
let mut other = again.clone(); | ||
other["answer"] = json!({ "response": {} }); | ||
let huge = json!({ "tool": "query", "arguments": { "x": "a".repeat(5 << 20) } }); | ||
for (input, status) in [ | ||
( | ||
json!({ "tool": "describe_repo", "arguments": { "actor": BOB, "view": view("did") } }), | ||
StatusCode::BAD_REQUEST, | ||
), | ||
( | ||
json!({ "tool": "list_records", "arguments": { "actor": BOB } }), | ||
StatusCode::BAD_REQUEST, | ||
), | ||
(other, StatusCode::BAD_REQUEST), | ||
(huge, StatusCode::PAYLOAD_TOO_LARGE), | ||
] { | ||
assert_eq!( | ||
failed(anyone("previewView", input).await), | ||
err(status, "InvalidRequest") | ||
); | ||
} | ||
} | ||
| ||
#[tokio::test] | ||
async fn a_theme_chosen_follows_the_person() { | ||
let (hud, _) = server(None).await; | ||
crates/hud-server/src/lib.rs+13−11
| @@ -3,12 +3,13 @@ | ||
//! are loaded through, and public images when the CDN fails (`blob`); `GET | ||
//! /_health`, answering `ok`; apps' icons, `GET /icon/{domain}` (`icon`); | ||
//! the terms, privacy policy and guidelines, `GET /terms`, `/privacy` and | ||
//! `/guidelines` (`policies`); and, with sign-in on, `/oauth/*` and | ||
//! `/.well-known/oauth-*` (`oauth`), the workspace's page, `/workspace`, | ||
//! and its icon, `/favicon.svg` (`workspace`), and its methods, | ||
//! `/xrpc/place.hud.*` (`xrpc`). Each request is logged and counted, in | ||
//! its trace (`telemetry`), whose listener of its own answers `/metrics` | ||
//! and `PUT /log`. | ||
//! `/guidelines` (`policies`); HUD's icon, `/favicon.svg`, and the | ||
//! playground, `/playground` (`playground`); HUD's methods, | ||
//! `/xrpc/place.hud.*` (`xrpc`), the workspace's among them with sign-in | ||
//! on alone; and, with sign-in on, `/oauth/*` and `/.well-known/oauth-*` | ||
//! (`oauth`) and the workspace's page, `/workspace` (`workspace`). Each | ||
//! request is logged and counted, in its trace (`telemetry`), whose | ||
//! listener of its own answers `/metrics` and `PUT /log`. | ||
| ||
#![forbid(unsafe_code)] | ||
| ||
| @@ -16,6 +17,7 @@ mod blob; | ||
mod icon; | ||
mod mcp; | ||
mod oauth; | ||
mod playground; | ||
mod policies; | ||
pub mod telemetry; | ||
mod workspace; | ||
| @@ -35,12 +37,12 @@ pub fn router(hud: Arc<Hud>) -> Router { | ||
.route("/blob/{did}/{cid}", get(blob::blob)) | ||
.route("/_health", get(|| async { "ok" })) | ||
.route("/icon/{domain}", get(icon::icon)) | ||
.merge(policies::routes()); | ||
.route("/favicon.svg", get(workspace::favicon)) | ||
.merge(policies::routes()) | ||
.merge(playground::routes()) | ||
.merge(xrpc::routes()); | ||
if hud.oauth.is_some() { | ||
routes = routes | ||
.merge(oauth::routes()) | ||
.merge(workspace::routes()) | ||
.merge(xrpc::routes()); | ||
routes = routes.merge(oauth::routes()).merge(workspace::routes()); | ||
} | ||
telemetry::observed(routes.with_state(hud)) | ||
} | ||
crates/hud-server/src/playground.rsnew+105−0
| @@ -0,0 +1,105 @@ | ||
//! The playground, sign-in on or off: `GET /playground`, its page (one | ||
//! HTML file, `web/dist/playground.html`, embedded as `PLAYGROUND_HTML`), | ||
//! where a view is written beside what it draws. The page calls | ||
//! `getPlayground` and `previewView` (`crate::xrpc`), anyone's, as the web | ||
//! session where the browser has one. Its CSP is the workspace's. | ||
| ||
use crate::PLAYGROUND_HTML; | ||
use crate::workspace::csp; | ||
use axum::Router; | ||
use axum::extract::State; | ||
use axum::http::{StatusCode, header}; | ||
use axum::response::{IntoResponse, Response}; | ||
use axum::routing::get; | ||
use hud_core::Hud; | ||
use std::sync::Arc; | ||
| ||
/// The playground's route. | ||
pub fn routes() -> Router<Arc<Hud>> { | ||
Router::new().route("/playground", get(page)) | ||
} | ||
| ||
/// `GET /playground`: the page. | ||
async fn page(State(hud): State<Arc<Hud>>) -> Response { | ||
let policy = csp( | ||
&hud.config.public_origin, | ||
hud.config.image_cdn_origin().as_deref(), | ||
); | ||
( | ||
StatusCode::OK, | ||
[ | ||
(header::CONTENT_TYPE, "text/html; charset=utf-8".to_string()), | ||
(header::CONTENT_SECURITY_POLICY, policy), | ||
(header::CACHE_CONTROL, "no-cache".to_string()), | ||
(header::REFERRER_POLICY, "no-referrer".to_string()), | ||
(header::X_FRAME_OPTIONS, "DENY".to_string()), | ||
(header::X_CONTENT_TYPE_OPTIONS, "nosniff".to_string()), | ||
], | ||
PLAYGROUND_HTML, | ||
) | ||
.into_response() | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use axum::body::Body; | ||
use axum::http::{Request, StatusCode, header}; | ||
use hud_core::{Config, Hud}; | ||
use tower::ServiceExt; | ||
| ||
/// With sign-in off, the playground's page, its icon and its methods | ||
/// are there, the workspace's not. | ||
#[tokio::test] | ||
async fn the_playground_with_sign_in_off() { | ||
let dir = std::env::temp_dir().join(format!("hud-playground-{}", atproto::jose::random(6))); | ||
let hud = Hud::new(Config { | ||
port: 0, | ||
bind: "::".parse().unwrap(), | ||
public_origin: "http://localhost:8787".into(), | ||
cache_dir: dir.join("cache"), | ||
data_dir: dir, | ||
oauth: false, | ||
oauth_scope: hud_core::scope::asked(false), | ||
spaces: false, | ||
plc_url: "https://plc.directory".into(), | ||
handle_resolver: None, | ||
allow_private: false, | ||
blob_cache_bytes: 0, | ||
cache_memory_bytes: 1 << 20, | ||
backlinks: hud_core::backlinks::Backlinks::None, | ||
favicons: None, | ||
image_cdn: None, | ||
relay: None, | ||
sign_up_pds: hud_core::config::SIGN_UP_PDS.into(), | ||
operators: Vec::new(), | ||
logs: false, | ||
logs_keep: hud_core::logs::KEEP, | ||
}) | ||
.unwrap(); | ||
let got = async |path: &str| { | ||
let r = crate::router(hud.clone()) | ||
.oneshot(Request::get(path).body(Body::empty()).unwrap()) | ||
.await | ||
.unwrap(); | ||
let status = r.status(); | ||
let headers = r.headers().clone(); | ||
let body = axum::body::to_bytes(r.into_body(), usize::MAX) | ||
.await | ||
.unwrap(); | ||
(status, headers, String::from_utf8(body.to_vec()).unwrap()) | ||
}; | ||
let (status, headers, body) = got("/playground").await; | ||
assert_eq!(status, StatusCode::OK); | ||
assert_eq!(body, crate::PLAYGROUND_HTML); | ||
let policy = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap(); | ||
assert!(policy.contains("connect-src 'self'"), "{policy}"); | ||
assert_eq!(got("/favicon.svg").await.0, StatusCode::OK); | ||
let (status, _, body) = got("/xrpc/place.hud.getPlayground").await; | ||
assert_eq!(status, StatusCode::OK); | ||
assert!(body.contains("grain-gallery-view")); | ||
let (status, _, body) = got("/xrpc/place.hud.getWorkspace").await; | ||
assert_eq!(status, StatusCode::NOT_IMPLEMENTED, "{body}"); | ||
assert!(body.contains("sign-in off"), "{body}"); | ||
assert_eq!(got("/workspace").await.0, StatusCode::NOT_FOUND); | ||
} | ||
} | ||
crates/hud-server/src/workspace.rs+5−5
| @@ -1,7 +1,8 @@ | ||
//! The workspace, mounted with sign-in on: `GET /workspace`, its page (one | ||
//! HTML file, `web/dist/workspace.html`, embedded as `WORKSPACE_HTML`), | ||
//! where `GET /` sends a browser, signed out its landing page; | ||
//! `GET /favicon.svg`, its icon (`FAVICON_SVG`); `GET /workspace/atmo/{file}`, | ||
//! where `GET /` sends a browser, signed out its landing page; its icon, | ||
//! `GET /favicon.svg` (`FAVICON_SVG`, served with sign-in off too, by | ||
//! `crate::router`); `GET /workspace/atmo/{file}`, | ||
//! the apps' logos its sign-in dialog runs past (`ATMO`); `GET | ||
//! /workspace/hero/{file}`, the landing's picture of the workspace (`HERO`); | ||
//! and its sign-ins, each a | ||
| @@ -54,7 +55,6 @@ pub fn routes() -> Router<Arc<Hud>> { | ||
Router::new() | ||
.route("/", get(|| async { see_other("/workspace") })) | ||
.route("/workspace", get(app)) | ||
.route("/favicon.svg", get(favicon)) | ||
.route("/workspace/atmo/{file}", get(atmo)) | ||
.route("/workspace/hero/{file}", get(hero)) | ||
.route("/workspace/signin", post(sign_in)) | ||
| @@ -68,7 +68,7 @@ pub fn routes() -> Router<Arc<Hud>> { | ||
/// among them, for posts' videos' HLS), and images from Bluesky's CDN, for | ||
/// the AppView's avatars, and the image CDN (`image_cdn`, an origin), for | ||
/// public records' images. | ||
fn csp(public_origin: &str, image_cdn: Option<&str>) -> String { | ||
pub(crate) fn csp(public_origin: &str, image_cdn: Option<&str>) -> String { | ||
let trusted: Vec<String> = hud_core::view::csp_origins(public_origin) | ||
.into_iter() | ||
.filter(|o| o != public_origin) | ||
| @@ -304,7 +304,7 @@ async fn app(State(hud): State<Arc<Hud>>) -> Response { | ||
} | ||
| ||
/// `GET /favicon.svg`: HUD's icon, the page's favicon, kept a day. | ||
async fn favicon() -> Response { | ||
pub(crate) async fn favicon() -> Response { | ||
( | ||
StatusCode::OK, | ||
[ | ||
crates/hud-server/src/xrpc.rs+146−29
| @@ -1,28 +1,33 @@ | ||
//! The workspace's methods, with sign-in on: `/xrpc/place.hud.*`, | ||
//! each as its lexicon in `schemas/` says, as an atproto appview answers | ||
//! them: a query by `GET`, its params in the query string; a procedure by | ||
//! `POST`, its input a JSON object of at most 256 KiB, but `uploadBlob`'s, | ||
//! an image's bytes, at most 2,000,000, sent on to the caller's PDS. Input | ||
//! is checked against the lexicon, then by HUD's own rules, before anything | ||
//! is done; a name the lexicon does not take is refused. A failure is | ||
//! `{error, message}`, its error one the method's lexicon names: | ||
//! `NotFound`, `Forbidden`, `InvalidRequest`, `LimitReached`, | ||
//! `AuthRequired`, `UpstreamFailure`; a method HUD has not, | ||
//! `MethodNotImplemented` (501); the request's line names it too | ||
//! (`telemetry::Cause`). `deleteAccountData` called with the | ||
//! cookie answers as `POST /workspace/signout` does: the browser goes on | ||
//! as the account it used last before, else signed out. | ||
//! HUD's methods, `/xrpc/place.hud.*`, each as its lexicon in `schemas/` | ||
//! says, as an atproto appview answers them: a query by `GET`, its params | ||
//! in the query string; a procedure by `POST`, its input a JSON object of | ||
//! at most 256 KiB (`previewView`'s, which carries an answer read before, | ||
//! 4 MiB), but `uploadBlob`'s, an image's bytes, at most 2,000,000, sent | ||
//! on to the caller's PDS. Input is checked against the lexicon, then by | ||
//! HUD's own rules, before anything is done; a name the lexicon does not | ||
//! take is refused. A failure is `{error, message}`, its error one the | ||
//! method's lexicon names: `NotFound`, `Forbidden`, `InvalidRequest`, | ||
//! `LimitReached`, `AuthRequired`, `UpstreamFailure`; a method HUD has | ||
//! not, `MethodNotImplemented` (501); the request's line names it too | ||
//! (`telemetry::Cause`). `deleteAccountData` called with the cookie | ||
//! answers as `POST /workspace/signout` does: the browser goes on as the | ||
//! account it used last before, else signed out. | ||
//! | ||
//! A caller is the account of the workspace's web session (its cookie, | ||
//! The workspace's methods are there with sign-in on alone. A caller is | ||
//! the account of the workspace's web session (its cookie, | ||
//! `hud_session`), or of a HUD access token as `Bearer`, as MCP clients | ||
//! have: what an app of the person's or the bridge calls with. A | ||
//! procedure called with the cookie must also say `X-HUD: 1` and come from | ||
//! the server's own origin (`Origin`), else `403`: no other site's page can | ||
//! make one. A token that is not one HUD gave is `401` with the | ||
//! `invalid_token` challenge. `searchActors`, a sign-in's suggestions, is | ||
//! anyone's: it reads no session. `getLogs` is the operators' alone | ||
//! `invalid_token` challenge. `getLogs` is the operators' alone | ||
//! (`HUD_OPERATOR_DIDS`, `hud_core::logs`). | ||
//! | ||
//! Anyone's, sign-in on or off, reading no session: `searchActors`, a | ||
//! sign-in's suggestions, and the playground's (`crate::playground`): | ||
//! `getPlayground`, and `previewView`, which calls as the account where a | ||
//! session is good, else as no one. | ||
//! | ||
//! `getWorkspaceEvents` answers server-sent events: every change to the | ||
//! person's open canvases, who is on them, and their workspace's changes, | ||
//! as `place.hud.defs` types them, until their session ends. | ||
| @@ -53,6 +58,9 @@ use std::time::{Duration, Instant}; | ||
const NS: &str = "place.hud."; | ||
/// The most of a procedure's input read. | ||
const MAX_BODY: usize = 256 * 1024; | ||
/// The most of `previewView`'s input read: a view and the answer it | ||
/// draws over, which a feed's page with its joins makes large. | ||
const PREVIEW_BODY: usize = 4 * 1024 * 1024; | ||
/// How often an idle event stream says it is there. | ||
const PING: Duration = Duration::from_secs(25); | ||
/// How often an event stream checks that its session goes on. | ||
| @@ -323,22 +331,45 @@ async fn handle( | ||
.await; | ||
return Ok(answer(StatusCode::OK, &json!({ "actors": actors }))); | ||
} | ||
// What the playground starts from, the same for everyone. | ||
if name == "getPlayground" { | ||
query_params(method, def, query)?; | ||
return Ok(answer(StatusCode::OK, playground())); | ||
} | ||
// A view drawn for the playground: as the account where one is | ||
// signed in, else as no one. | ||
if name == "previewView" { | ||
let caller = caller(hud, headers).ok(); | ||
if caller | ||
.as_ref() | ||
.is_some_and(|c| matches!(c.proof, Proof::Cookie(_))) | ||
{ | ||
from_page(hud, headers)?; | ||
} | ||
let input = procedure_input(method, def, body, PREVIEW_BODY).await?; | ||
let account = caller.as_ref().map(|c| &c.account); | ||
return Ok(answer( | ||
StatusCode::OK, | ||
&preview(hud, account, &input).await?, | ||
)); | ||
} | ||
// The rest are the workspace's, which sign-in off has none of. | ||
if hud.oauth.is_none() { | ||
return Err(fail( | ||
StatusCode::NOT_IMPLEMENTED, | ||
"MethodNotImplemented", | ||
format!("HUD has sign-in off: no {method}"), | ||
)); | ||
} | ||
let caller = caller(hud, headers)?; | ||
// An image's bytes, for `uploadBlob`; else the input, as JSON. | ||
let (input, image) = if procedure { | ||
if let Proof::Cookie(_) = caller.proof { | ||
let said = headers.get("x-hud").and_then(|v| v.to_str().ok()) == Some("1"); | ||
if !said || !same_origin(hud, headers) { | ||
return Err(fail( | ||
StatusCode::FORBIDDEN, | ||
"InvalidRequest", | ||
"Only the workspace's own page may do this, with X-HUD: 1", | ||
)); | ||
} | ||
from_page(hud, headers)?; | ||
} | ||
match name { | ||
"uploadBlob" => (Map::new(), Some(body)), | ||
_ => (procedure_input(method, def, body).await?, None), | ||
_ => (procedure_input(method, def, body, MAX_BODY).await?, None), | ||
} | ||
} else { | ||
(query_params(method, def, query)?, None) | ||
| @@ -387,18 +418,19 @@ fn query_params( | ||
Ok(params) | ||
} | ||
| ||
/// A procedure's input: a JSON object of at most 256 KiB, valid for its | ||
/// A procedure's input: a JSON object of at most `max` bytes, valid for its | ||
/// lexicon, naming nothing it does not declare. | ||
async fn procedure_input( | ||
method: &str, | ||
def: &Json, | ||
body: Body, | ||
max: usize, | ||
) -> Result<Map<String, Json>, Failure> { | ||
let bytes = axum::body::to_bytes(body, MAX_BODY).await.map_err(|_| { | ||
let bytes = axum::body::to_bytes(body, max).await.map_err(|_| { | ||
fail( | ||
StatusCode::PAYLOAD_TOO_LARGE, | ||
"InvalidRequest", | ||
"The input is too large: at most 256 KiB", | ||
format!("The input is too large: at most {} KiB", max / 1024), | ||
) | ||
})?; | ||
let Ok(Json::Object(input)) = serde_json::from_slice::<Json>(&bytes) else { | ||
| @@ -417,6 +449,91 @@ async fn procedure_input( | ||
Ok(input) | ||
} | ||
| ||
/// A procedure called with the cookie: only from the server's own page, | ||
/// which says `X-HUD: 1`, from its own origin. | ||
fn from_page(hud: &Hud, headers: &HeaderMap) -> Result<(), Failure> { | ||
let said = headers.get("x-hud").and_then(|v| v.to_str().ok()) == Some("1"); | ||
if said && same_origin(hud, headers) { | ||
return Ok(()); | ||
} | ||
Err(fail( | ||
StatusCode::FORBIDDEN, | ||
"InvalidRequest", | ||
"Only the workspace's own page may do this, with X-HUD: 1", | ||
)) | ||
} | ||
| ||
/// `getPlayground`: the bundled views a read tool draws (not app pages), | ||
/// each as a view given inline may be (`view::inline_copy`) with the app | ||
/// it names, the component catalog and HUD's themes, made once. | ||
fn playground() -> &'static Json { | ||
static MADE: LazyLock<Json> = LazyLock::new(|| { | ||
let views: Vec<Json> = hud_core::view::bundled() | ||
.iter() | ||
.filter(|b| b.view.page.is_none()) | ||
.map(|b| { | ||
json!({ "name": b.id, "app": b.view.app.clone().unwrap_or_default(), | ||
"view": hud_core::view::inline_copy(&b.view.doc) }) | ||
}) | ||
.collect(); | ||
json!({ "views": views, "catalog": hud_core::catalog::to_json(), | ||
"themes": hud_core::theme::all() }) | ||
}); | ||
&MADE | ||
} | ||
| ||
/// `previewView`: the inline view's problems, every one, where it has | ||
/// any; else drawn again over the answer given (`Hud::redraw`); else the | ||
/// call made afresh, its result as `/mcp` gives it, logged as a tool | ||
/// call is. Signed out, a call that needs an account is the result's | ||
/// error. | ||
async fn preview( | ||
hud: &Hud, | ||
account: Option<&Account>, | ||
input: &Map<String, Json>, | ||
) -> Result<Json, Failure> { | ||
let tool = need(input, "tool"); | ||
if !matches!(tool, "list_records" | "get_record" | "query") { | ||
return Err(invalid(format!( | ||
"{tool} draws no view: list_records, get_record and query do" | ||
))); | ||
} | ||
let arguments = input.get("arguments"); | ||
let doc = arguments | ||
.and_then(|a| a.get("view")) | ||
.filter(|v| v.is_object()) | ||
.ok_or_else(|| invalid("The arguments give no view: give it as their view"))?; | ||
if let Err(problems) = hud_core::view::parse(doc, false) { | ||
let problems: Vec<Json> = problems | ||
.iter() | ||
.map(|p| { | ||
let (at, message) = p.split_once(": ").unwrap_or(("view", p)); | ||
json!({ "at": at, "message": message }) | ||
}) | ||
.collect(); | ||
return Ok(json!({ "problems": problems })); | ||
} | ||
if let Some(answer) = input.get("answer") { | ||
let ui = hud.redraw(tool, arguments, answer, account).await; | ||
return Ok(json!({ "ui": ui.map_err(invalid)? })); | ||
} | ||
let started = Instant::now(); | ||
let answered = match hud.call_tool(tool, arguments, account).await { | ||
Some(Ok(out)) => Ok(out), | ||
Some(Err(Refusal::Error(e))) => Err(e), | ||
// Asked for an account: the tool is one of the three, all known. | ||
_ => Err("Sign in to HUD to read this".to_string()), | ||
}; | ||
hud_core::telemetry::tool(&hud_core::telemetry::Tool { | ||
name: tool, | ||
did: account.map(|a| a.did.as_str()), | ||
error: answered.as_ref().err().map(String::as_str), | ||
reason: None, | ||
took: started.elapsed(), | ||
}); | ||
Ok(json!({ "result": tool_result(answered, false) })) | ||
} | ||
| ||
/// `uploadBlob`: an image (`Content-Type: image/*`, its bytes a JPEG, PNG, | ||
/// WebP or HEIC) of at most `BLOB_MAX` bytes sent to the caller's PDS as | ||
/// their blob, the blob ref it answered; the bytes never logged. | ||
crates/hud-server/build.rs+8−2
| @@ -1,8 +1,10 @@ | ||
//! Embeds what `web/` builds: the view, `web/dist/index.html`, one | ||
//! self-contained HTML file that `resources/read` of the view's URI answers | ||
//! with; the workspace's page, `web/dist/workspace.html`, which | ||
//! `GET /workspace` answers with; and HUD's icon, `web/dist/favicon.svg` | ||
//! (from `web/public/`), which `GET /favicon.svg` answers with. The view's | ||
//! `GET /workspace` answers with; the playground's, | ||
//! `web/dist/playground.html`, which `GET /playground` answers with; and | ||
//! HUD's icon, `web/dist/favicon.svg` (from `web/public/`), which | ||
//! `GET /favicon.svg` answers with. The view's | ||
//! URI carries a hash of its file (`ui://records/view/<hash>`), so a host | ||
//! that keeps a resource it read never draws a new server's results with an | ||
//! old view: a new view is a new resource. A build without any of these | ||
| @@ -34,6 +36,7 @@ fn built(name: &str) -> PathBuf { | ||
fn main() { | ||
let view = built("index.html"); | ||
let workspace = built("workspace.html"); | ||
let playground = built("playground.html"); | ||
let favicon = built("favicon.svg"); | ||
let hash = fnv1a(&fs::read(&view).unwrap()); | ||
let to = Path::new(&env::var("OUT_DIR").unwrap()).join("view.rs"); | ||
| @@ -46,10 +49,13 @@ fn main() { | ||
pub const VIEW_URI: &str = \"ui://records/view/{hash:016x}\";\n\ | ||
/// The workspace's page, as `web/` builds it: one HTML file, its script and styles inline.\n\ | ||
pub const WORKSPACE_HTML: &str = include_str!({:?});\n\ | ||
/// The playground's page, as `web/` builds it: one HTML file, its script and styles inline.\n\ | ||
pub const PLAYGROUND_HTML: &str = include_str!({:?});\n\ | ||
/// HUD's icon, as `web/` copies it from `web/public/`: an SVG.\n\ | ||
pub const FAVICON_SVG: &str = include_str!({:?});\n", | ||
view.display().to_string(), | ||
workspace.display().to_string(), | ||
playground.display().to_string(), | ||
favicon.display().to_string() | ||
), | ||
) | ||
docs/_style.md+1−0
| @@ -24,6 +24,7 @@ and tool text keep their own style. | ||
| `knotless.md` | knotless's views and how its queries are made | | ||
| `sign-in.md` | sign-in, feed interactions, saved feeds, chats, procedures | | ||
| `workspace.md` | the workspace: canvases, tiles, agents, music, themes, where canvases live | | ||
| `playground.md` | the playground: writing a view beside what it draws, sharing it | | ||
| `running.md` | running HUD: commands, environment variables, the image | | ||
| `memory.md` | what HUD holds in memory and how to measure it | | ||
| `observability.md` | what HUD logs, its traces and metrics, the lines it keeps for its operators, how to read them | | ||
docs/playground.mdnew+40−0
docs/running.md+2−0
docs/views.md+10−7
docs/workspace-api.md+3−1
harness/contrast.json+2−1
schemas/place.hud.getPlayground.jsonnew+69−0
schemas/place.hud.previewView.jsonnew+92−0
web/workspace/lib/atoms/CodeEditor.sveltenew+72−0
web/workspace/lib/molecules/ProblemList.sveltenew+77−0
web/workspace/lib/molecules/Segmented.sveltenew+92−0
web/workspace/lib/organisms/PlaygroundEditor.sveltenew+186−0
web/workspace/lib/organisms/PlaygroundPreview.sveltenew+438−0
438 lines changed: not loaded until asked for.