~ 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
285 lines · 11.2 KB Raw History
//! A Bluesky feed item's context, as the web renderer's FeedContextNode read
//! it: why it is in the feed, and the posts it replies to.

use super::*;

pub(super) const POST: &str = "app.bsky.feed.defs#postView";
const BLOCKED: &str = "app.bsky.feed.defs#blockedPost";

/// A context post: the node's children drawn with `{post}` as their scope,
/// opening what `open` names for it.
fn context_item(n: &Value, post: &Value, ctx: &Ctx) -> R<Value> {
    let scope = json!({ "post": post });
    let mut o = Map::new();
    if let Some(open) = opens(&n["props"]["open"], &scope, ctx, None)? {
        o.insert("open".into(), open);
    }
    o.insert("k".into(), Value::Array(children(n, &scope, ctx)));
    Ok(Value::Object(o))
}

/// `FeedContext`: `part` above: `reason` (`{kind: "repost", name, open?}`
/// or `{kind: "pin"}`) and `thread` (`{top?, gap?: {open?}, repliedTo?,
/// parent}`, each post `{open?, k}`); `part` replyTo: `replyTo` (`{label,
/// open?}`). Nothing to say draws nothing.
pub(super) fn feed_context(n: &Value, scope: &Value, ctx: &Ctx) -> R<Option<Value>> {
    let p = &n["props"];
    let item = required("item", &p["item"], scope, Value::is_object)?;
    let part = if p["part"].as_str() == Some("replyTo") {
        "replyTo"
    } else {
        "above"
    };
    let reason = Some(&item["reason"]).filter(|r| r.is_object());
    let reply = Some(&item["reply"]).filter(|r| r.is_object());
    let parent_uri = str_at(&item["post"]["record"]["reply"]["parent"], "uri");
    let is_post = |v: &Value| v["$type"] == POST;
    let parent = reply.map(|r| &r["parent"]).filter(|v| is_post(v));
    let thread_root = reply.map(|r| &r["root"]).filter(|v| is_post(v));

    let mut thread = None;
    if reason.is_none()
        && let Some(parent) = parent
    {
        let top = thread_root.filter(|t| t["uri"] != parent["uri"]);
        let grandparent = str_at(&parent["record"]["reply"]["parent"], "uri");
        let gap = top.is_some_and(|t| t["uri"].as_str() != grandparent);
        let author = reply
            .map(|r| &r["grandparentAuthor"])
            .filter(|a| a.is_object());
        let said = if top.is_none()
            || (gap && author.and_then(|a| str_at(a, "did")) != str_at(&parent["author"], "did"))
        {
            author
        } else {
            None
        };
        let mut t = Map::new();
        if let Some(top) = top {
            t.insert("top".into(), context_item(n, top, ctx)?);
        }
        let parent_item = context_item(n, parent, ctx)?;
        if gap {
            let open = parent_item.get("open").cloned();
            t.insert("gap".into(), json!({ "open": open }));
        }
        if let Some(name) = said.and_then(name_of) {
            t.insert("repliedTo".into(), name.into());
        }
        t.insert("parent".into(), parent_item);
        thread = Some(Value::Object(t));
    }

    let mut o = Map::new();
    if part == "above" {
        match reason.and_then(|r| r["$type"].as_str()) {
            Some("app.bsky.feed.defs#reasonRepost")
                if reason.is_some_and(|r| r["by"].is_object()) =>
            {
                let by = &reason.unwrap()["by"];
                let mut r = json!({ "kind": "repost", "name": name_of(by).unwrap_or("") });
                if let Some(actor) = str_at(by, "did").or_else(|| str_at(by, "handle")) {
                    r["open"] = ctx.actor_call(actor);
                }
                o.insert("reason".into(), r);
            }
            Some("app.bsky.feed.defs#reasonPin") => {
                o.insert("reason".into(), json!({ "kind": "pin" }));
            }
            _ => {}
        }
        if let Some(t) = thread {
            o.insert("thread".into(), t);
        }
    } else if thread.is_none()
        && let Some(parent_uri) = parent_uri
    {
        let kind = reply.and_then(|r| r["parent"]["$type"].as_str());
        let name = if kind == Some(POST) {
            parent.and_then(|p| name_of(&p["author"]))
        } else {
            None
        };
        let label = match (kind, name) {
            (Some(BLOCKED), _) => "Replied to a blocked post".to_string(),
            (_, Some(name)) => format!("Replied to {name}"),
            _ => "Replied to a post".to_string(),
        };
        let at = json!({ "post": parent.cloned().unwrap_or_else(|| json!({ "uri": parent_uri })) });
        let mut r = json!({ "label": label });
        if let Some(open) = opens(&p["open"], &at, ctx, None)? {
            r["open"] = open;
        }
        o.insert("replyTo".into(), r);
    }
    if o.is_empty() {
        return Err(Fail::Missing);
    }
    Ok(Some(make("FeedContext", o, vec![])))
}

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

    fn ctx(root: &Value) -> Ctx<'_> {
        Ctx {
            origins: &[],
            thumbnails: vec![],
            trusted: true,
            root,
            report: None,
            inline: None,
            lexicon: None,
            handles: None,
            paged: Vec::new(),
            more: More::default(),
            me: None,
            people: None,
        }
    }

    fn post(uri: &str, did: &str, name: &str, parent: Option<&str>) -> Value {
        let mut p = json!({ "$type": POST, "uri": uri, "author": { "did": did, "handle": format!("{name}.test"), "displayName": name }, "record": {} });
        if let Some(parent) = parent {
            p["record"]["reply"] = json!({ "parent": { "uri": parent } });
        }
        p
    }

    /// A feed item replying to `parent`, in the thread `reply` names.
    fn item(parent: &str, reply: Value) -> Value {
        json!({ "post": { "uri": "at://did:plc:me/app.bsky.feed.post/me", "record": { "reply": { "parent": { "uri": parent } } } },
                "reply": reply })
    }

    /// The FeedContext drawn for `item`, held to the lexicon, its posts
    /// drawn as their uris and opening them.
    fn context(item: &Value, part: &str, c: &Ctx) -> Option<Value> {
        let layout = json!({ "component": "FeedContext",
            "props": { "item": { "$": "." }, "part": part, "open": { "$": "post.uri" } },
            "children": [{ "component": "Text", "props": { "value": { "$": "post.uri" } } }] });
        let tree = resolve(&layout, item, c)?;
        check::checked(&tree);
        Some(tree["p"].clone())
    }

    /// The drawing of a context post: its uri, opening it.
    fn drawn(uri: &str, c: &Ctx) -> Value {
        json!({ "open": c.record_call(uri),
                "k": [{ "c": "Text", "p": { "runs": [{ "text": uri }], "style": "body" } }] })
    }

    #[test]
    fn a_reply_deep_in_a_thread_shows_its_root_a_gap_and_whom_its_parent_replied_to() {
        let root = json!({});
        let c = ctx(&root);
        let (r, p, g) = (
            "at://did:plc:r/p/r",
            "at://did:plc:p/p/p",
            "at://did:plc:g/p/g",
        );
        let thread = json!({ "root": post(r, "did:plc:r", "Root", None),
                             "parent": post(p, "did:plc:p", "Parent", Some(g)),
                             "grandparentAuthor": { "did": "did:plc:g", "displayName": "Gee" } });
        let shown = context(&item(p, thread.clone()), "above", &c).unwrap();
        assert_eq!(
            shown["thread"],
            json!({ "top": drawn(r, &c), "gap": { "open": c.record_call(p) },
                    "repliedTo": "Gee", "parent": drawn(p, &c) })
        );

        // A parent replying to itself across the gap: no one else to name.
        let mut same = thread.clone();
        same["grandparentAuthor"] = json!({ "did": "did:plc:p", "displayName": "Parent" });
        let shown = context(&item(p, same), "above", &c).unwrap();
        assert!(shown["thread"].get("gap").is_some());
        assert!(shown["thread"].get("repliedTo").is_none());

        // A parent replying to the root: no gap, and the root says who it is.
        let mut direct = thread;
        direct["parent"] = post(p, "did:plc:p", "Parent", Some(r));
        let shown = context(&item(p, direct), "above", &c).unwrap();
        assert_eq!(
            shown["thread"],
            json!({ "top": drawn(r, &c), "parent": drawn(p, &c) })
        );
    }

    #[test]
    fn a_repost_or_a_pin_is_why_an_item_is_there_and_hides_its_thread() {
        let root = json!({});
        let c = ctx(&root);
        let p = "at://did:plc:p/p/p";
        let mut reposted = item(
            p,
            json!({ "root": post(p, "did:plc:p", "Parent", None), "parent": post(p, "did:plc:p", "Parent", None) }),
        );
        reposted["reason"] = json!({ "$type": "app.bsky.feed.defs#reasonRepost", "by": { "did": "did:plc:by", "handle": "by.test" } });
        assert_eq!(
            context(&reposted, "above", &c).unwrap(),
            json!({ "reason": { "kind": "repost", "name": "by.test", "open": c.actor_call("did:plc:by") } })
        );
        // Under the author, the parent it replied to, by name.
        assert_eq!(
            context(&reposted, "replyTo", &c).unwrap(),
            json!({ "replyTo": { "label": "Replied to Parent", "open": c.record_call(p) } })
        );

        let mut pinned = json!({ "post": { "uri": "at://did:plc:me/p/1", "record": {} } });
        pinned["reason"] = json!({ "$type": "app.bsky.feed.defs#reasonPin" });
        assert_eq!(
            context(&pinned, "above", &c).unwrap(),
            json!({ "reason": { "kind": "pin" } })
        );
        assert_eq!(context(&pinned, "replyTo", &c), None, "nothing to say");

        // A reposter known by handle alone opens by it; one known by
        // neither opens nothing.
        reposted["reason"]["by"] = json!({ "handle": "by.test" });
        assert_eq!(
            context(&reposted, "above", &c).unwrap()["reason"]["open"],
            c.actor_call("by.test")
        );
        reposted["reason"]["by"] = json!({ "displayName": "Nobody" });
        assert_eq!(
            context(&reposted, "above", &c).unwrap(),
            json!({ "reason": { "kind": "repost", "name": "Nobody" } })
        );
    }

    #[test]
    fn a_reply_to_a_post_not_drawn_says_what_it_can() {
        let root = json!({});
        let c = ctx(&root);
        let p = "at://did:plc:p/p/p";
        let blocked = item(p, json!({ "parent": { "$type": BLOCKED, "uri": p } }));
        assert_eq!(
            context(&blocked, "replyTo", &c).unwrap(),
            json!({ "replyTo": { "label": "Replied to a blocked post", "open": c.record_call(p) } })
        );
        let unknown = item(
            p,
            json!({ "parent": { "$type": "app.bsky.feed.defs#notFoundPost", "uri": p } }),
        );
        assert_eq!(
            context(&unknown, "replyTo", &c).unwrap()["replyTo"]["label"],
            "Replied to a post"
        );
        // With no thread in the item at all, its record's parent alone.
        let mut bare = item(p, Value::Null);
        bare.as_object_mut().unwrap().remove("reply");
        assert_eq!(
            context(&bare, "replyTo", &c).unwrap(),
            json!({ "replyTo": { "label": "Replied to a post", "open": c.record_call(p) } })
        );
        // A view that opens nothing: the label alone.
        let layout = json!({ "component": "FeedContext", "props": { "item": { "$": "." }, "part": "replyTo" } });
        let tree = resolve(&layout, &bare, &c).unwrap();
        check::checked(&tree);
        assert_eq!(
            tree["p"],
            json!({ "replyTo": { "label": "Replied to a post" } })
        );
    }
}