~ 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

The tests run under a 100% line and function coverage gate

Merged chadtmiller.com asked to merge into main from chadtmiller.com/hud:test/coverage-gate
.knotless/workflows/test.yml+16−8
@@ -1,10 +1,11 @@
# The tests, as `just check` and `just lex` run them: every crate's, then
# every XRPC answer hud-server's tests received, held to its method's
# lexicon (harness/answers.mjs), as the workspace's types are made from
# them. hud-server embeds the built pages, so they are built first.
# The tests, as `just check` and `just lex` run them: every crate's under
# `just cov`'s gate, failing under 100% of lines or functions, then every
# XRPC answer hud-server's tests received, held to its method's lexicon
# (harness/answers.mjs), as the workspace's types are made from them.
# hud-server embeds the built pages, so they are built first.
#
# The build, the toolchain, Node, the pages' packages and @atproto/lexicon
# are kept between runs.
# The build, the toolchain, cargo-llvm-cov, Node, the pages' packages and
# @atproto/lexicon are kept between runs.
image: rust:1.100
# A pre-flight, as check is: the merge queue takes a pull into a batch only
# once this has passed at its head.
@@ -13,7 +14,7 @@ runners: [runner.knotless.dev]
on:
push: {refs: [refs/heads/main]}
pull: {base: [refs/heads/main, refs/heads/feature/*]}
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/node, /opt/lexicon, web/node_modules]
cache: [target, /usr/local/cargo/registry, /usr/local/rustup, /opt/tools, /opt/node, /opt/lexicon, web/node_modules]
env:
# The image's toolchain, over the cached rustup's default (check.yml).
RUSTUP_TOOLCHAIN: "1.100.0"
@@ -23,12 +24,19 @@ steps:
- uses: chadtmiller.com/steps/npm-ci@1
name: pages' packages
with: {dir: web}
- uses: chadtmiller.com/steps/cargo-llvm-cov@1
with: {version: 0.9.1}
- name: pages
run: cd web && npm run build
- name: test
run: |
# As `just cov`, with its ignore. cargo-llvm-cov first removes the
# workspace's own old artifacts from target/llvm-cov-target, so
# another branch's binaries in the shared cache never count.
rm -rf target/answers
HUD_ANSWERS="$PWD/target/answers" cargo test --workspace --locked
HUD_ANSWERS="$PWD/target/answers" cargo llvm-cov --workspace --locked \
--ignore-filename-regex '(tests/|tests\.rs|harness/|examples/|rustlib/)' \
--fail-under-lines 100 --fail-under-functions 100 --show-missing-lines
- name: answers
run: |
# With the harness's @atproto/lexicon alone, rather than all of its
.knotless/uses.lock+4−0
@@ -1,4 +1,8 @@
# Written by `knotless workflow pin`. Commit it: runs read it.
chadtmiller.com/steps/cargo-llvm-cov@1:
version: 1.0.0
commit: 686cdbb38978730bb1ba5d1c999967e48497ce15
release: at://did:plc:bcgltzqazw5tb6k2g3ttenbj/dev.knotless.release/3mza7iq7tundv.tbnmqntp7ufhx7yd6i3rdqewys.sjjb7q6l3fsl3spvqsuzdoe73w
chadtmiller.com/steps/node@1:
version: 1.0.0
commit: 686cdbb38978730bb1ba5d1c999967e48497ce15
crates/hud/src/main.rs+23−19
@@ -271,6 +271,11 @@ fn config() -> Result<Config, String> {
})
}
/// What failed, said as `<what>: <the error>`.
fn failed(what: String) -> impl FnOnce(std::io::Error) -> String {
move |e| format!("{what}: {e}")
}
/// Resolves on SIGINT or SIGTERM.
async fn shutdown() {
let interrupt = tokio::signal::ctrl_c();
@@ -303,22 +308,21 @@ async fn serve() -> Result<(), String> {
tracing::info!(client_id = %format!("{public}/oauth/client-metadata.json"), "sign-in is on");
let sweeper = hud.clone();
tokio::spawn(async move {
let auth = sweeper.oauth.as_ref().expect("sign-in is on");
let mut every = tokio::time::interval(std::time::Duration::from_secs(3600));
loop {
every.tick().await;
if let Some(auth) = &sweeper.oauth {
auth.sweep().await;
}
auth.sweep().await;
}
});
}
let listener = tokio::net::TcpListener::bind(addr)
.await
.map_err(|e| format!("listening on {addr}: {e}"))?;
.map_err(failed(format!("listening on {addr}")))?;
tracing::info!(%addr, public = %public, "serving MCP at {public}/mcp");
let served = hud_server::serve(listener, hud.clone(), shutdown())
.await
.map_err(|e| format!("serving: {e}"));
.map_err(failed("serving".into()));
// The canvases' changes still waiting to be written, written.
hud.canvases.flush().await;
tracing::info!(caches = %hud.caches(), "caches at shutdown");
@@ -342,6 +346,19 @@ fn resolve(tool: Option<&str>, arguments: Option<&str>) -> Result<(), String> {
Ok(())
}
/// `hud serve`, its logs set up, on a runtime of its own. A runtime that
/// cannot be made is said before the logs are set up: on stderr alone.
fn run() -> Result<(), String> {
let runtime = tokio::runtime::Runtime::new().map_err(failed("a runtime".into()))?;
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
runtime.block_on(serve())
}
fn main() -> std::process::ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
match args
@@ -369,20 +386,7 @@ fn main() -> std::process::ExitCode {
return std::process::ExitCode::from(2);
}
}
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
let runtime = match tokio::runtime::Runtime::new() {
Ok(r) => r,
Err(e) => {
eprintln!("hud: a runtime: {e}");
return std::process::ExitCode::FAILURE;
}
};
match runtime.block_on(serve()) {
match run() {
Ok(()) => std::process::ExitCode::SUCCESS,
Err(e) => {
tracing::error!("{e}");
crates/hud/tests/cli.rsnew+543−0
543 lines changed: not loaded until asked for.
crates/hud-core/src/canvas/canonical.rs+95−0
@@ -134,4 +134,99 @@ mod tests {
let t = tidy(m.as_object().unwrap().clone());
assert_eq!(t.keys().collect::<Vec<_>>(), ["b", "f"]);
}
#[tokio::test]
async fn calls_written_otherwise_made_the_same() {
let dir = std::env::temp_dir().join(format!("hud-canonical-{}", atproto::jose::random(6)));
let h = Hud::new(crate::Config {
port: 0,
bind: "::".parse().unwrap(),
public_origin: "https://hud.test".into(),
cache_dir: dir.join("cache"),
blob_cache_bytes: 0,
cache_memory_bytes: 1 << 24,
data_dir: dir,
oauth: false,
oauth_scope: crate::scope::asked(false),
spaces: false,
plc_url: "http://127.0.0.1:9".into(),
handle_resolver: None,
allow_private: false,
backlinks: crate::backlinks::Backlinks::None,
favicons: None,
image_cdn: None,
relay: None,
})
.unwrap();
// What is not an object, as given.
assert_eq!(h.canonical_call("query", &json!("x")).await, json!("x"));
// An app's page's domain lowercased, its trailing dot dropped.
assert_eq!(
h.canonical_call(
"describe_app",
&json!({ "domain": " BSKY.App. ", "view": null })
)
.await,
json!({ "domain": "bsky.app" })
);
// A record named by no URI is left as given.
assert_eq!(
h.canonical_call("get_record", &json!({ "cid": "bafy", "view": {} }))
.await,
json!({ "cid": "bafy" })
);
// A query: its method trimmed, its bundled view's service named,
// its params tidied.
let feed = "at://did:plc:x/app.bsky.feed.generator/d";
let expected = json!({ "method": "app.bsky.feed.getFeed",
"params": { "feed": feed, "limit": 5 },
"service": "did:web:api.bsky.app#bsky_appview" });
assert_eq!(
h.canonical_call(
"query",
&json!({ "method": " app.bsky.feed.getFeed ",
"params": { "limit": 5, "cursor": "", "feed": feed } })
)
.await,
expected
);
// A service named stays; params of a method with no lexicon, tidied
// alone.
let named = json!({ "method": "app.bsky.feed.getFeed", "service": "did:web:x#y" });
assert_eq!(h.canonical_call("query", &named).await, named);
assert_eq!(
h.canonical_call(
"query",
&json!({ "method": "nope", "params": { "a": 1, "b": "" } })
)
.await,
json!({ "method": "nope", "params": { "a": 1 } })
);
// One with no method, as given, tidied.
assert_eq!(
h.canonical_call("query", &json!({ "params": { "a": 1 }, "view": null }))
.await,
json!({ "params": { "a": 1 } })
);
// A record's URI trimmed; an actor by DID as it is; any other tool
// tidied alone.
assert_eq!(
h.canonical_call("get_record", &json!({ "uri": " at://did:plc:a/a.b.c/1 " }))
.await,
json!({ "uri": "at://did:plc:a/a.b.c/1" })
);
assert_eq!(
h.canonical_call(
"list_records",
&json!({ "collection": "a.b.c", "actor": "did:plc:a" })
)
.await,
json!({ "actor": "did:plc:a", "collection": "a.b.c" })
);
assert_eq!(
h.canonical_call("describe_method", &json!({ "method": "a.b.c", "x": "" }))
.await,
json!({ "method": "a.b.c" })
);
}
}
crates/hud-core/src/canvas/engine.rs+586−79
665 lines changed: not loaded until asked for.
crates/hud-core/src/canvas/mod.rs+120−0
@@ -975,6 +975,24 @@ mod tests {
assert_eq!((read.from, read.stack, read.by), (None, None, By::Person));
assert!(Tile::from_json(&tile_json(None), "did:plc:a").is_none());
assert!(Tile::from_json(&tile_json(Some("1e3")), "did:plc:a").is_none());
// Made by neither a person nor an agent: no tile. No width: a third.
let mut robot = tile_json(Some("1"));
robot["by"] = json!("robot");
assert!(Tile::from_json(&robot, "did:plc:a").is_none());
let mut narrow = tile_json(Some("1"));
narrow.as_object_mut().unwrap().remove("width");
assert_eq!(
Tile::from_json(&narrow, "did:plc:a").unwrap().width,
Width::Third
);
// Arguments: an object, at most 64 KiB as JSON.
assert_eq!(checked_arguments(None), Ok(json!({})));
assert!(checked_arguments(Some(&json!([1]))).is_err());
let big = json!({ "q": "x".repeat(ARGUMENTS_MAX) });
assert_eq!(
checked_arguments(Some(&big)),
Err("arguments are too large: at most 64 KiB as JSON".into())
);
assert_eq!(checked_name(" Coast trip "), Ok("Coast trip".into()));
assert!(checked_name(&"n".repeat(81)).is_err());
assert!(checked_name(" ").is_err());
@@ -1148,6 +1166,37 @@ mod tests {
assert_eq!(tiles[4]["order"], "5");
}
#[test]
fn records_read_back() {
let mut tile = Tile::from_json(&tile_json(Some("1")), "did:plc:a").unwrap();
// Arrays in its arguments are as a record holds them.
tile.arguments = json!({ "uris": ["at://did:plc:a/a.b.c/1"], "limit": 5 });
let record = tile.record();
assert_eq!(record["arguments"], tile.arguments);
assert_eq!(
Tile::from_record(&tile.id, &record, "did:plc:a"),
Some(tile.clone())
);
// No width: a third. No arguments at all: no tile.
let mut narrow = record.clone();
narrow.as_object_mut().unwrap().remove("width");
assert_eq!(
Tile::from_record(&tile.id, &narrow, "did:plc:a").map(|t| t.width),
Some(Width::Third)
);
let mut bare = record;
bare.as_object_mut().unwrap().remove("arguments");
assert_eq!(Tile::from_record(&tile.id, &bare, "did:plc:a"), None);
// What is not a tile is left as it is as the rest are made columns.
let mut tiles = vec![
json!("not a tile"),
json!({ "id": "00000000000a", "x": 0.0, "y": 0.0, "w": 420.0 }),
];
assert!(migrated(&mut tiles));
assert_eq!(tiles[0], "not a tile");
assert_eq!(tiles[1]["order"], "2");
}
#[test]
fn titles_made_and_summaries() {
let t = |tool: &str, args: Value, text: Option<&str>| {
@@ -1181,6 +1230,36 @@ mod tests {
let mut theirs = grain("actor");
theirs["params"]["actor"] = json!("did:plc:someone");
assert_eq!(t("query", theirs, None), "Galleries");
assert_eq!(
t(
"list_records",
json!({ "collection": "app.bsky.feed.post" }),
None
),
"app.bsky.feed.post"
);
// Feeds as no launcher names the call: HUD's own names.
let generators = |f: &str| json!({ "method": "app.bsky.feed.getFeedGenerators", "params": { "feeds": f, "limit": 5 } });
assert_eq!(t("query", generators("saved"), None), "My feeds");
assert_eq!(t("query", generators("pinned"), None), "My pinned feeds");
assert_ne!(t("query", generators("other"), None), "My feeds");
assert_eq!(
t(
"get_record",
json!({ "uri": "at://did:plc:x/app.bsky.feed.post/1" }),
None
),
"app.bsky.feed.post · did:plc:x"
);
let call = |method: &str| json!({ "method": method, "params": { "limit": 5 } });
assert_eq!(
t("query", call("app.bsky.feed.getTimeline"), None),
"Following"
);
assert_eq!(
t("query", call("com.example.getThings"), Some("Things: 3")),
"Things"
);
assert_eq!(
t("describe_app", json!({ "domain": "plyr.fm" }), None),
"plyr.fm"
@@ -1190,6 +1269,36 @@ mod tests {
page["arguments"] = json!({ "domain": "bsky.app" });
let page = Tile::from_json(&page, "did:plc:a").unwrap();
assert_eq!(page.app().as_deref(), Some("bsky.app"));
// The app of what a tile shows, by the NSID it names.
let app = |tool: &str, arguments: Value| {
Tile {
tool: tool.into(),
arguments,
..page.clone()
}
.app()
};
let bsky = crate::apps::domain("app.bsky.feed.post");
assert!(bsky.is_some());
assert_eq!(
app(
"get_record",
json!({ "uri": "at://did:plc:x/app.bsky.feed.post/1" })
),
bsky
);
assert_eq!(
app(
"list_records",
json!({ "collection": "app.bsky.feed.post" })
),
bsky
);
assert_eq!(
app("query", json!({ "method": "app.bsky.feed.getFeed" })),
bsky
);
assert_eq!(app("describe_repo", json!({ "actor": "me" })), None);
assert_eq!(t("query", feed("following"), None), "Following");
assert_eq!(
t(
@@ -1239,6 +1348,13 @@ mod tests {
created_at: iso(0),
updated_at: iso(1),
};
let mut bad = info.to_json();
bad["members"] = json!({});
assert_eq!(CanvasInfo::from_json(&bad), None);
bad.as_object_mut().unwrap().remove("members");
assert_eq!(CanvasInfo::from_json(&bad), None);
bad["members"] = json!([{ "did": "did:plc:a", "role": "boss", "joined": true }]);
assert_eq!(CanvasInfo::from_json(&bad), None);
assert_eq!(CanvasInfo::from_json(&info.to_json()), Some(info.clone()));
let mut ownerless = info.to_json();
ownerless["owner"] = json!("did:plc:z");
@@ -1246,5 +1362,9 @@ mod tests {
// Others who are in it: an invite pending is not.
assert!(info.others("did:plc:a").is_empty());
assert_eq!(info.others("did:plc:b"), ["a.test"]);
// One who joined with no handle known: by DID.
let mut joined = info.clone();
joined.members[1].joined = true;
assert_eq!(joined.others("did:plc:a"), ["did:plc:b"]);
}
}
crates/hud-core/src/canvas/space.rs+399−133
532 lines changed: not loaded until asked for.
crates/hud-core/src/canvas/store.rs+136−0
@@ -304,3 +304,139 @@ impl Store for FileStore {
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::canvas::{Member, Role};
const ALICE: &str = "did:plc:alice";
fn dir() -> PathBuf {
let d = std::env::temp_dir().join(format!("hud-canvas-store-{}", jose::random(6)));
std::fs::create_dir_all(&d).unwrap();
d
}
fn info(id: &str) -> CanvasInfo {
CanvasInfo {
id: id.into(),
name: "Coast trip".into(),
owner: ALICE.into(),
members: vec![Member {
did: ALICE.into(),
handle: None,
role: Role::Owner,
joined: true,
invited_by: None,
}],
created_at: "2026-11-14T00:00:00.000Z".into(),
updated_at: "2026-11-14T00:00:00.000Z".into(),
}
}
/// A canvas's file as kept, with `tiles`.
fn file(info: &CanvasInfo, tiles: Value) -> String {
let mut doc = info.to_json();
doc["tiles"] = tiles;
doc.to_string()
}
#[tokio::test]
async fn what_cannot_be_read_or_written_is_left_as_it_is() {
let d = dir();
let store = FileStore::new(d.clone());
// A file with a tile HUD does not make: not a canvas.
let odd = info("00000000000a");
std::fs::write(
d.join("00000000000a.json"),
file(&odd, json!([{ "id": "nope" }])),
)
.unwrap();
// Nor is one whose tiles are not a list.
std::fs::write(
d.join("00000000000e.json"),
file(&info("00000000000e"), json!({})),
)
.unwrap();
// A canvas from before columns kept under another id's name, where
// its own file cannot be written: a directory is in its place.
let old = info("00000000000c");
let tile = json!({ "id": "000000000001", "tool": "describe_repo",
"arguments": { "actor": "alice.test" }, "title": "alice.test", "x": 0.0, "y": 0.0,
"w": 420.0, "h": 560.0, "by": "agent", "at": "2026-11-14T00:00:00.000Z" });
std::fs::write(
d.join("00000000000b.json"),
file(&old, json!([tile.clone()])),
)
.unwrap();
std::fs::create_dir_all(d.join("00000000000c.json").join("x")).unwrap();
// Another from before columns, written back up to date.
let mended = info("00000000000f");
let path = d.join("00000000000f.json");
std::fs::write(&path, file(&mended, json!([tile]))).unwrap();
// The indexes cannot be rebuilt: where they go leads nowhere.
std::os::unix::fs::symlink(d.join("nowhere"), d.join("by-did")).unwrap();
// The canvas read, brought up to date in memory; the rest left.
let mut found = store.canvases().await;
found.sort_by(|a, b| a.0.id.cmp(&b.0.id));
assert_eq!(found, vec![(old.clone(), 1), (mended, 1)]);
let kept: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(kept["tiles"][0]["order"], "1");
assert!(store.index(ALICE).await.is_none());
assert_eq!(
store.tiles(&odd).await,
Err(format!(
"{} is not a canvas",
d.join("00000000000a.json").display()
))
);
let kept = store.put(&old, &[]).unwrap_err();
assert!(kept.contains("00000000000c.json"), "{kept}");
// A canvas with no file has no tiles.
assert_eq!(store.tiles(&info("00000000000d")).await, Ok(Vec::new()));
// Put aside where the place it goes is taken: refused, the file kept.
std::fs::create_dir_all(d.join("00000000000a.json.moved").join("x")).unwrap();
assert!(store.put_aside("00000000000a").is_err());
assert!(store.has("00000000000a"));
std::fs::remove_dir_all(&d).unwrap();
}
#[tokio::test]
async fn another_persons_files_are_not_theirs() {
let d = dir();
let store = FileStore::new(d.clone());
// An index and a canvas from before, each another DID's under
// Alice's name.
let index = Index {
canvases: vec!["00000000000a".into()],
open: None,
current: None,
};
store.put_index("did:plc:bob", &index).await.unwrap();
std::fs::rename(store.index_path("did:plc:bob"), store.index_path(ALICE)).unwrap();
assert_eq!(store.index(ALICE).await, None);
let whose = json!({ "did": ALICE, "canvases": {} });
std::fs::write(store.index_path(ALICE), whose.to_string()).unwrap();
assert_eq!(store.index(ALICE).await, None);
let legacy = store.legacy_path(ALICE);
std::fs::write(
&legacy,
json!({ "did": "did:plc:bob", "tiles": [] }).to_string(),
)
.unwrap();
assert_eq!(store.legacy(ALICE).await, None);
// Put aside where the place it goes is taken: left where it is.
std::fs::create_dir_all(legacy.with_extension("json.moved").join("x")).unwrap();
store.retire_legacy(ALICE).await;
assert!(legacy.exists());
// Files are where canvases belong, and nothing waits to be written.
let mine = info("00000000000e");
store.put(&mine, &[]).unwrap();
assert!(!store.misplaced(&mine));
let before = std::fs::read(d.join("00000000000e.json")).unwrap();
store.flush().await;
assert_eq!(std::fs::read(d.join("00000000000e.json")).unwrap(), before);
std::fs::remove_dir_all(&d).unwrap();
}
}
crates/hud-core/src/canvas/strip.rs+20−1
@@ -93,10 +93,11 @@ fn find(tiles: &[Tile], cols: &[Column], id: &str) -> Result<(usize, usize), Ref
.iter()
.position(|t| t.id == id)
.ok_or_else(|| Refused::NoTile(id.to_string()))?;
// Every tile heads a column or is stacked in one (`columns`).
let c = cols
.iter()
.position(|c| c.tiles().any(|t| t == i))
.ok_or_else(|| Refused::NoTile(id.to_string()))?;
.expect("every tile is in a column");
Ok((i, c))
}
@@ -503,4 +504,22 @@ mod tests {
];
assert_eq!(strip(&tiles), [[1], [2], [3]]);
}
#[test]
fn stacked_tiles_move_alone_and_follow_a_new_head() {
let mut tiles = vec![
tile(1, 1.0, None, None),
tile(2, 2.0, None, Some(1)),
tile(3, 3.0, None, Some(1)),
tile(4, 4.0, None, None),
];
// A stacked tile stacked into another column goes alone.
stack(&mut tiles, &id(3), &id(4)).unwrap();
assert_eq!(strip(&tiles), [vec![1, 2], vec![4, 3]]);
// A head with two under it taken off: the next heads the rest.
stack(&mut tiles, &id(3), &id(1)).unwrap();
remove(&mut tiles, &id(1)).unwrap();
assert_eq!(strip(&tiles), [vec![2, 3], vec![4]]);
assert_eq!(tiles[1].stack.as_deref(), Some(id(2).as_str()));
}
}
crates/hud-core/src/canvas/tools.rs+149−22
@@ -163,18 +163,13 @@ impl Hud {
account: &Account,
args: &Args<'_>,
) -> Result<(String, String), Refusal> {
let id = self
.canvases
.resolve(who(account), args.text("canvas")?)
.await
.map_err(tool_error)?;
let info = self
.canvases
.info_of(&id)
.resolve_info(who(account), args.text("canvas")?)
.await
.ok_or_else(|| tool_error(Refused::NoCanvas(id.clone())))?;
.map_err(tool_error)?;
let shown = named(&info.name, &info.others(&account.did));
Ok((id, shown))
Ok((info.id, shown))
}
pub(crate) async fn canvas_list_tool(
@@ -228,13 +223,12 @@ impl Hud {
})
.unwrap_or_default();
let viewer = &c["viewer"];
let whose = match viewer["role"].as_str() {
Some("owner") => "yours".to_string(),
let whose = match viewer["role"].as_str().unwrap_or_default() {
"owner" => "yours".to_string(),
_ if viewer.get("invitedBy").is_some() => {
format!("an invitation from {owner}: accept it in the workspace")
}
Some(role) => format!("{owner}'s, you are an {role}"),
None => String::new(),
role => format!("{owner}'s, you are an {role}"),
};
let n = c["tileCount"].as_u64().unwrap_or(0) as usize;
let current = if cid == id { ", current" } else { "" };
@@ -318,10 +312,12 @@ impl Hud {
let me = account.handle.as_deref().unwrap_or(&account.did);
let title = match title {
Some(t) => t,
None => match self.feed_title(&tool, &tool_arguments).await {
Some(named) => named,
None => default_title(&tool, &tool_arguments, Some(&out.text), Some(me)),
},
None => self
.feed_title(&tool, &tool_arguments)
.await
.unwrap_or_else(|| {
default_title(&tool, &tool_arguments, Some(&out.text), Some(me))
}),
};
let op = Op::Add {
tool,
@@ -405,15 +401,11 @@ impl Hud {
.map_err(tool_error)?;
done.push(format!("its column {} wide", width.as_str()));
}
let tiles = self
let tile = self
.canvases
.tiles(who(account), &id)
.tile(who(account), &id, &tid)
.await
.map_err(tool_error)?;
let tile = tiles
.iter()
.find(|t| t.id == tid)
.ok_or_else(|| tool_error(Refused::NoTile(tid.clone())))?;
Ok(Output {
text: format!("\"{}\" on {shown}: {}.", tile.title, done.join(", ")),
structured: json!({ "canvas": id, "tile": tile.view(None, &self.config.public_origin) }),
@@ -749,4 +741,139 @@ mod tests {
Err(Refusal::Error(_))
));
}
#[test]
fn refusals_and_storage_as_text() {
use super::{Refused, kept, tool_error};
assert_eq!(
tool_error(Refused::Limit("Too many".into())),
Refusal::Error("Too many".into())
);
assert_eq!(
tool_error(Refused::NoCanvas("0123456789ab".into())),
Refusal::Error("You have no canvas 0123456789ab; canvas_list lists them".into())
);
assert_eq!(
kept(&json!({ "kind": "space", "uri": "at://did:plc:a/space/t/k" })),
" It is kept in your space at at://did:plc:a/space/t/k."
);
assert_eq!(
kept(
&json!({ "kind": "file", "reason": "a canvas shared with others stays on this HUD server" })
),
" It is kept on this HUD server: a canvas shared with others stays on this HUD server."
);
}
#[tokio::test]
async fn titles_stacks_places_and_invitations() {
let h = hud();
let auth = h.auth().unwrap();
let alice = auth
.account(&auth.signed_in_offline("did:plc:alice", Some("alice.test"), false))
.unwrap();
let bob = auth
.account(&auth.signed_in_offline("did:plc:bob", Some("bob.test"), false))
.unwrap();
let call = |name: &'static str, args: Value, who: &crate::oauth::Account| {
let (h, who) = (&h, who.clone());
async move { h.call_tool(name, Some(&args), Some(&who)).await.unwrap() }
};
let describe =
|method: &str| json!({ "tool": "describe_method", "arguments": { "method": method } });
// An argument it does not take: refused.
let mut odd = describe("app.bsky.feed.getFeed");
odd["colour"] = json!("red");
assert!(matches!(
call("canvas_add", odd, &alice).await,
Err(Refusal::Error(_))
));
// A title given is the tile's.
let mut named = describe("app.bsky.feed.getFeed");
named["title"] = json!("Feeds");
let out = call("canvas_add", named, &alice).await.unwrap();
assert!(out.text.starts_with("Added \"Feeds\" to"), "{}", out.text);
let head = out.structured["tile"]["key"].as_str().unwrap().to_string();
let canvas = out.structured["canvas"].as_str().unwrap().to_string();
let out = call("canvas_add", describe("app.bsky.feed.getTimeline"), &alice)
.await
.unwrap();
let under = out.structured["tile"]["key"].as_str().unwrap().to_string();
// Placed after another, its width as it was; then its width alone.
let placed = call(
"canvas_place",
json!({ "id": head, "after": under }),
&alice,
)
.await
.unwrap();
assert!(
placed.text.ends_with(&format!(": placed after {under}.")),
"{}",
placed.text
);
let wide = call(
"canvas_place",
json!({ "id": head, "width": "half" }),
&alice,
)
.await
.unwrap();
assert!(
wide.text.ends_with(": its column half wide."),
"{}",
wide.text
);
// Stacked under another: listed so.
let me = crate::canvas::Who {
did: "did:plc:alice",
handle: Some("alice.test"),
};
let stack = crate::canvas::Op::Stack {
id: under.clone(),
into: head.clone(),
};
h.canvases
.apply(me, &canvas, stack, crate::canvas::By::Person)
.await
.unwrap();
let list = call("canvas_list", json!({ "canvas": canvas }), &alice)
.await
.unwrap();
assert!(
list.text.contains(&format!("\n{under} · "))
&& list.text.contains(&format!(" · stacked under {head} · ")),
"{}",
list.text
);
// Invited, not yet joined: an invitation, listed so.
h.canvases
.invite(
me,
&canvas,
"did:plc:bob",
Some("bob.test"),
crate::canvas::Role::Viewer,
)
.await
.unwrap();
let bobs = call("canvas_list", json!({}), &bob).await.unwrap();
assert!(
bobs.text.contains(&format!(
"({canvas}), an invitation from alice.test: accept it in the workspace"
)),
"{}",
bobs.text
);
// Two of a name: which is refused.
for _ in 0..2 {
call("canvas_create", json!({ "name": "Twin" }), &alice)
.await
.unwrap();
}
assert!(matches!(
call("canvas_list", json!({ "canvas": "twin" }), &alice).await,
Err(Refusal::Error(e)) if e.starts_with("2 canvases are named \"twin\"")
));
}
}
crates/hud-core/src/oauth/tests/spaces.rs+579−1
580 lines changed: not loaded until asked for.
crates/hud-core/src/oauth/client.rs+39−40
@@ -21,7 +21,7 @@
//! when the PDS refuses it as `invalid_token`, one refresh at a time per
//! session; a refresh the server refuses ends the session.
use super::issuer::{unissued, with_query};
use super::issuer::{Pending, unissued, with_query};
use super::store::{Kind, Session};
use super::{Account, Asker, Auth, Flow, PENDING_LIFE, PENDING_MAX, now};
use crate::Hud;
@@ -61,8 +61,9 @@ pub struct Server {
pub enum SignIn {
/// Its request is gone: expired, or already used.
Expired,
/// A line for the page to show.
Failed(String),
/// The page again, its request as it shows it with the handle as
/// typed, and a line saying why.
Failed(Pending, String),
}
/// Where `/oauth/callback` sends the person on to.
@@ -228,7 +229,7 @@ impl Auth {
impl Hud {
/// A JSON object at `url`, answered there, not by a redirect.
async fn get_json(&self, url: &str) -> Result<Value, String> {
let url = Url::parse(url).map_err(|_| "not a URL".to_string())?;
let url = Url::parse(url).ok().ok_or("not a URL")?;
let got = self.net.fetch_json(&url, WAIT, META_MAX).await?;
if got.redirected || got.status != 200 {
return Err(format!("it answered {}", got.status));
@@ -353,12 +354,27 @@ impl Hud {
}
/// The sign-in page's form: the account named, its server found, the
/// request pushed; the URL of the server's authorization page.
/// request pushed; the URL of the server's authorization page. Else its
/// page again, saying why, while its request still waits.
pub async fn sign_in(&self, request_id: &str, login: &str) -> Result<String, SignIn> {
let auth = self.auth().map_err(SignIn::Failed)?;
let Ok(auth) = self.auth() else {
return Err(SignIn::Expired);
};
if auth.pending(request_id).is_none() {
return Err(SignIn::Expired);
}
let why = match self.push(auth, request_id, login).await {
Ok(to) => return Ok(to),
Err(why) => why,
};
let mut page = auth.pending(request_id).ok_or(SignIn::Expired)?;
page.login_hint = Some(login.trim().to_string()).filter(|h| !h.is_empty());
Err(SignIn::Failed(page, why))
}
/// The account named resolved, its server found, the request pushed
/// and taken; the URL of the server's authorization page, else why not.
async fn push(&self, auth: &Auth, request_id: &str, login: &str) -> Result<String, String> {
let login = login.trim().trim_start_matches('@');
let login = if atproto::syntax::is_did(login) {
login.to_string()
@@ -366,21 +382,16 @@ impl Hud {
login.to_ascii_lowercase()
};
if login.is_empty() {
return Err(SignIn::Failed(
"Enter your handle, as alice.bsky.social".into(),
));
return Err("Enter your handle, as alice.bsky.social".into());
}
if !atproto::syntax::is_handle(&login) && !atproto::syntax::is_did(&login) {
return Err(SignIn::Failed(format!("{login} is not a handle or a DID")));
return Err(format!("{login} is not a handle or a DID"));
}
let who = self
.resolve_actor(&login)
.await
.map_err(|_| SignIn::Failed(format!("{login} does not resolve to an account")))?;
let server = self
.authorization_server(&who.pds)
.await
.map_err(SignIn::Failed)?;
.map_err(|_| format!("{login} does not resolve to an account"))?;
let server = self.authorization_server(&who.pds).await?;
let state = jose::random(16);
let verifier = jose::random(32);
let dpop = Keypair::generate(Curve::P256);
@@ -405,25 +416,21 @@ impl Hud {
],
)
.await;
let (status, body) = pushed.map_err(|why| {
SignIn::Failed(format!("Your account's server could not be reached: {why}"))
})?;
let (status, body) =
pushed.map_err(|why| format!("Your account's server could not be reached: {why}"))?;
let request_uri = body["request_uri"]
.as_str()
.filter(|_| (200..300).contains(&status));
let Some(request_uri) = request_uri else {
tracing::warn!(
status,
error = safe_name(&body),
issuer = server.issuer,
"PAR refused"
);
return Err(SignIn::Failed(match safe_name(&body) {
let error = safe_name(&body);
tracing::warn!(status, error, issuer = server.issuer, "PAR refused");
return Err(match error {
Some(e) => format!("Your account's server refused the sign-in: {e}"),
None => format!("Your account's server refused the sign-in ({status})"),
}));
});
};
let asker = auth.take_request(request_id).ok_or(SignIn::Expired)?;
// Gone meanwhile, it is told as expired, whatever this says.
let asker = auth.take_request(request_id).ok_or(String::new())?;
let to = with_query(
&server.authorization,
&[
@@ -442,8 +449,7 @@ impl Hud {
nonce,
created: now(),
},
)
.map_err(SignIn::Failed)?;
)?;
Ok(to)
}
@@ -600,12 +606,8 @@ impl Hud {
let t = match tokens_of(&body) {
Ok(t) if status == 200 && t.sub == s.did => t,
_ => {
tracing::info!(
did = s.did,
status,
error = safe_name(&body),
"refresh refused"
);
let error = safe_name(&body);
tracing::info!(did = s.did, status, error, "refresh refused");
return Err(Unrefreshed::Refused);
}
};
@@ -778,11 +780,8 @@ impl Hud {
)
.await;
if let Err(why) = done {
tracing::info!(
did = s.did,
why,
"revocation at the account's server failed"
);
let did = &s.did;
tracing::info!(did, why, "revocation at the account's server failed");
}
}
}
crates/hud-core/src/oauth/issuer.rs+77−42
@@ -15,10 +15,10 @@ use super::{
SPENT_LIFE, index, now,
};
use crate::Hud;
use crate::net::{Failure, Fetched};
use atproto::jose;
use serde_json::{Map, Value, json};
use std::collections::HashMap;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use url::{Host, Url};
@@ -206,15 +206,10 @@ fn strings(v: Option<&Value>) -> Option<Vec<String>> {
.collect()
}
/// An `http:` URL on `127.0.0.1`, `[::1]` or `localhost`.
/// An `http:` URL on `127.0.0.1`, `[::1]` or `localhost`, as the URL
/// standard writes each host.
fn loopback(u: &Url) -> bool {
u.scheme() == "http"
&& match u.host() {
Some(Host::Ipv4(a)) => a == Ipv4Addr::LOCALHOST,
Some(Host::Ipv6(a)) => a == Ipv6Addr::LOCALHOST,
Some(Host::Domain(d)) => d == "localhost",
None => false,
}
u.scheme() == "http" && matches!(u.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"))
}
/// Whether a redirect URI is of a form a client may name: an `https:` URL;
@@ -442,7 +437,7 @@ fn answer(access: &str, refresh: Option<&str>, sub: &str) -> Value {
impl Auth {
/// A client's metadata document still kept.
fn kept_document(&self, id: &str) -> Option<Client> {
pub(super) fn kept_document(&self, id: &str) -> Option<Client> {
let st = self.lock();
st.documents
.get(id)
@@ -462,6 +457,35 @@ impl Auth {
}
}
/// A client of the metadata document fetched for `id`, its answer
/// checked: its own, JSON, a document of MCP's rules. Kept an hour.
pub(super) fn fetched_document(
&self,
id: &str,
got: Result<Fetched, Failure>,
) -> Result<Client, String> {
let got = got.map_err(|why| format!("its metadata could not be read: {why}"))?;
if got.redirected || got.status != 200 {
return Err(format!(
"its metadata could not be read (answered {}{})",
got.status,
if got.redirected { ", redirected" } else { "" }
));
}
let json_type = got
.header("content-type")
.and_then(|t| t.split(';').next())
.is_some_and(|t| t.trim().eq_ignore_ascii_case("application/json"));
if !json_type {
return Err("its metadata is not application/json".into());
}
let doc: Value = serde_json::from_slice(&got.body)
.map_err(|_| "its metadata is not JSON".to_string())?;
let c = document_client(id, &doc)?;
self.keep_document(c.clone());
Ok(c)
}
/// Keep a sign-in waiting for its account to be named; its id.
pub(crate) fn keep_request(&self, r: Asker) -> Result<String, String> {
let mut st = self.lock();
@@ -608,19 +632,23 @@ impl Auth {
async fn refresh_grant(&self, client: &Client, token: &str) -> Result<Value, Refused> {
let bad = |why: &str| refused(400, "invalid_grant", why);
let hash = jose::sha256(token);
let kept = self.lock().tokens.get(&hash).cloned();
let sid = match kept {
Some(Kept::Refresh { sid }) => sid,
Some(Kept::Replaced { sid }) => {
// A token and its session are kept and forgotten together, under
// one lock.
let kept = {
let st = self.lock();
st.tokens.get(&hash).cloned().map(|k| {
let cell = st.sessions.get(super::kept_sid(&k)).map(|l| l.cell.clone());
(k, cell)
})
};
let cell = match kept {
Some((Kept::Refresh { .. }, Some(cell))) => cell,
Some((Kept::Replaced { sid }, _)) => {
self.end(&sid).await;
return Err(bad("The refresh token was replaced; its session is ended"));
}
_ => return Err(bad("The refresh token is not one HUD gave, or expired")),
};
let cell = self.lock().sessions.get(&sid).map(|l| l.cell.clone());
let Some(cell) = cell else {
return Err(bad("The session is ended"));
};
let mut s = cell.lock().await;
let now = now();
if s.ended {
@@ -678,30 +706,8 @@ impl Hud {
return Ok(c);
}
let url = document_url(id).ok_or("it is not a client metadata document's URL")?;
let got = self
.net
.fetch_json(&url, DOCUMENT_WAIT, DOCUMENT_MAX)
.await
.map_err(|why| format!("its metadata could not be read: {why}"))?;
if got.redirected || got.status != 200 {
return Err(format!(
"its metadata could not be read (answered {}{})",
got.status,
if got.redirected { ", redirected" } else { "" }
));
}
let json_type = got
.header("content-type")
.and_then(|t| t.split(';').next())
.is_some_and(|t| t.trim().eq_ignore_ascii_case("application/json"));
if !json_type {
return Err("its metadata is not application/json".into());
}
let doc: Value = serde_json::from_slice(&got.body)
.map_err(|_| "its metadata is not JSON".to_string())?;
let c = document_client(id, &doc)?;
auth.keep_document(c.clone());
Ok(c)
let got = self.net.fetch_json(&url, DOCUMENT_WAIT, DOCUMENT_MAX).await;
auth.fetched_document(id, got)
}
/// `GET /oauth/authorize`: the request checked in order (its client,
@@ -1063,6 +1069,7 @@ pub(crate) mod tests {
"invalid_redirect_uri"
);
assert_eq!(err(json!({})), "invalid_client_metadata");
assert_eq!(err(json!([])), "invalid_client_metadata");
assert_eq!(
err(json!({ "redirect_uris": ["https://a.example/cb"],
"token_endpoint_auth_method": "client_secret_basic" })),
@@ -1076,6 +1083,26 @@ pub(crate) mod tests {
err(json!({ "redirect_uris": ["https://a.example/cb"], "client_name": "a\nb" })),
"invalid_client_metadata"
);
assert_eq!(
err(json!({ "redirect_uris": ["https://a.example/cb"], "response_types": ["token"] })),
"invalid_client_metadata"
);
// Loopback is 127.0.0.1, [::1] or localhost, as the URL standard
// writes each, by any port.
for uri in [
"http://[::1]:8080/cb",
"http://127.1/cb",
"http://LOCALHOST/cb",
] {
assert!(
registration(&json!({ "redirect_uris": [uri] })).is_ok(),
"{uri}"
);
}
assert_eq!(
err(json!({ "redirect_uris": ["http://[::2]/cb"] })),
"invalid_redirect_uri"
);
}
#[test]
@@ -1097,6 +1124,7 @@ pub(crate) mod tests {
"https://hud.example",
"https://other.example/mcp"
));
assert!(!is_resource("https://hud.example", "hud.example/mcp"));
let pairs = |p: &[(&str, &str)]| -> Vec<(String, String)> {
p.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
@@ -1107,6 +1135,7 @@ pub(crate) mod tests {
with_query("https://c.example/cb?x=1", &[("code", "c d")]),
"https://c.example/cb?x=1&code=c+d"
);
assert_eq!(with_query("not a url", &[("code", "c")]), "not a url");
assert_eq!(
body_params(
Some("application/json; charset=utf-8"),
@@ -1120,5 +1149,11 @@ pub(crate) mod tests {
pairs(&[("a", "1"), ("b", " ")])
);
assert!(body_params(Some("text/plain"), b"").is_err());
assert_eq!(
body_params(Some("application/json"), b"[\"a\"]")
.unwrap_err()
.description,
"The body is not a JSON object"
);
}
}
crates/hud-core/src/oauth/mod.rs+20−17
crates/hud-core/src/oauth/store.rs+39−0
crates/hud-core/src/oauth/tests.rs+1309−32
1341 lines changed: not loaded until asked for.
crates/hud-core/src/ui/check.rs+13−13
crates/hud-core/src/ui/diff.rs+36−0
crates/hud-core/src/ui/document.rs+411−191
602 lines changed: not loaded until asked for.
crates/hud-core/src/ui/embed.rs+319−5
crates/hud-core/src/ui/feed.rs+165−0
crates/hud-core/src/ui/fields.rs+174−0
crates/hud-core/src/ui/layout.rs+10−0
crates/hud-core/src/ui/marks.rs+48−0
crates/hud-core/src/ui/media.rs+74−0
crates/hud-core/src/ui/mod.rs+560−13
573 lines changed: not loaded until asked for.
crates/hud-core/src/ui/thread.rs+36−0
crates/hud-core/src/apps.rs+4−4
crates/hud-core/src/backlinks.rs+90−0
crates/hud-core/src/blobcache.rs+65−0
crates/hud-core/src/cache.rs+56−6
crates/hud-core/src/cards.rs+162−7
crates/hud-core/src/catalog.rs+195−166
crates/hud-core/src/compose.rs+168−4
crates/hud-core/src/feeds.rs+70−2
crates/hud-core/src/icons.rs+68−7
crates/hud-core/src/identity.rs+346−32
crates/hud-core/src/interactions.rs+116−0
crates/hud-core/src/join.rs+355−40
crates/hud-core/src/lexicon.rs+158−16
crates/hud-core/src/lib.rs+83−1
crates/hud-core/src/net.rs+312−21
crates/hud-core/src/pds.rs+196−0
crates/hud-core/src/places.rs+83−5
crates/hud-core/src/procedures.rs+88−17
crates/hud-core/src/space.rs+17−0
crates/hud-core/src/summary.rs+16−0
crates/hud-core/src/theme.rs+239−12
crates/hud-core/src/tools.rs+998−78
1076 lines changed: not loaded until asked for.
crates/hud-core/src/view.rs+621−90
711 lines changed: not loaded until asked for.
crates/hud-core/src/writes.rs+547−7
554 lines changed: not loaded until asked for.
crates/hud-core/src/xrpc.rs+290−12
crates/hud-core/Cargo.toml+3−0
crates/hud-server/src/xrpc/tests.rs+279−5
crates/hud-server/src/blob.rs+462−51
513 lines changed: not loaded until asked for.
crates/hud-server/src/mcp.rs+276−16
crates/hud-server/src/oauth.rs+467−25
492 lines changed: not loaded until asked for.
crates/hud-server/src/workspace.rs+38−0
crates/hud-server/src/xrpc.rs+27−35
crates/hud-server/Cargo.toml+2−0
docs/internals.md+1−1
docs/tools.md+1−1
AGENTS.md+12−1
Cargo.lock+1−0
Cargo.toml+3−0
Justfile+8−2