Skip to main content

byob_protocol/
sites.rs

1//! Render sites: where plugins' live views show in a client (13.3+, cap
2//! [`CAP_VIEW_SITES`]).
3//!
4//! A plugin declares its views in its manifest (`views: [{site, id, title, icon}]`), and
5//! clients learn them from [`crate::PluginInfo::views`]. A site is a place in the client's UI:
6//! the side **pane** (a tab beside the chat), a **settings** section (under the plugin in
7//! Settings → Plugins), a header **status** item (a chip or a short text) and step **card**s
8//! (a backend tool attaches one to its step).
9//!
10//! The engine owns each view's tree; clients keep only transient state (typed text, scroll)
11//! — the ipywidgets rule. A client that starts showing a view sends
12//! [`crate::ClientMsg::OpenView`]; the engine answers with a [`LiveView`] carrying the whole
13//! tree (from its cache, or after asking the plugin's backend), then sends patches whenever
14//! the plugin changes it, to every client that has it open. What the user does in it is a
15//! [`crate::ClientMsg::ViewEvent`], which the engine hands to the backend; the backend
16//! answers with a new view (or patches), which the engine diffs against the last one.
17//! A [`ViewRef`] names a view: the plugin, the declared view id, and a key (`""` for the
18//! single instance at pane, settings and status sites; one per card).
19
20use serde::{Deserialize, Serialize};
21use serde_json::{Map, Value};
22
23use crate::tree::{Event, Node, Patch};
24
25/// Cap: the peer handles live views at render sites ([`crate::ClientMsg::OpenView`],
26/// [`crate::ServerMsg::LiveView`], [`crate::View::owner`]).
27pub const CAP_VIEW_SITES: &str = "view_sites";
28
29/// Most views one plugin declares.
30pub const MAX_VIEWS: usize = 16;
31/// Longest view id.
32pub const MAX_VIEW_ID_CHARS: usize = 48;
33/// Longest view key.
34pub const MAX_VIEW_KEY_CHARS: usize = 128;
35/// Largest event (its JSON).
36pub const MAX_EVENT_BYTES: usize = 256 * 1024;
37/// Longest view title.
38pub const MAX_TITLE_CHARS: usize = 80;
39
40/// Where a view shows.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
42#[serde(rename_all = "snake_case")]
43pub enum Site {
44    /// A tab of the side pane beside the chat.
45    Pane,
46    /// A section under the plugin in Settings → Plugins.
47    Settings,
48    /// A small item in the header (a chip, a few words).
49    Status,
50    /// A card on a step (a backend tool attaches it).
51    Card,
52    /// An artifact's body (13.5): the view a renderer `{"renderer": "view:<id>"}` names,
53    /// drawn in the artifact's card and pane, one instance per version (key
54    /// `"<artifact id>@<version>"`, see [`artifact_key`]).
55    Artifact,
56    /// A site a newer engine knows (not shown).
57    #[serde(other)]
58    Other,
59}
60
61impl Site {
62    pub const ALL: [Site; 5] = [Site::Pane, Site::Settings, Site::Status, Site::Card, Site::Artifact];
63
64    pub fn label(self) -> &'static str {
65        match self {
66            Self::Pane => "pane",
67            Self::Settings => "settings",
68            Self::Status => "status",
69            Self::Card => "card",
70            Self::Artifact => "artifact",
71            Self::Other => "other",
72        }
73    }
74
75    pub fn parse(s: &str) -> Option<Self> {
76        Self::ALL.into_iter().find(|x| x.label() == s)
77    }
78}
79
80/// A view a plugin declares (`views` in its manifest).
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82pub struct ViewDecl {
83    /// `[a-z0-9_-]{1,48}`, unique in the plugin.
84    pub id: String,
85    pub site: Site,
86    #[serde(default)]
87    pub title: String,
88    /// A lucide icon name (may be empty).
89    #[serde(default, skip_serializing_if = "String::is_empty")]
90    pub icon: String,
91    /// A web view (13.5+): the HTML file (in the plugin folder) shown on a web surface
92    /// instead of a view tree (see [`crate::web`]). Empty for tree views.
93    #[serde(default, skip_serializing_if = "String::is_empty")]
94    pub html: String,
95}
96
97/// Names one live view: the plugin, its declared view id and an instance key.
98#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
99pub struct ViewRef {
100    pub plugin: String,
101    /// The declared view's id.
102    pub view: String,
103    /// `""`: the only instance (pane, settings, status); a card's own key.
104    #[serde(default, skip_serializing_if = "String::is_empty")]
105    pub key: String,
106}
107
108impl ViewRef {
109    pub fn new(plugin: impl Into<String>, view: impl Into<String>, key: impl Into<String>) -> Self {
110        Self { plugin: plugin.into(), view: view.into(), key: key.into() }
111    }
112
113    /// Check an untrusted reference's ids and sizes.
114    pub fn check(&self) -> Result<(), String> {
115        if !byob_types::config::plugin_id_ok(&self.plugin) {
116            return Err(format!("{:?} isn't a plugin id", self.plugin.chars().take(60).collect::<String>()));
117        }
118        if !view_id_ok(&self.view) {
119            return Err(format!("{:?} isn't a view id", self.view.chars().take(60).collect::<String>()));
120        }
121        if self.key.chars().count() > MAX_VIEW_KEY_CHARS {
122            return Err(format!("a view key can be at most {MAX_VIEW_KEY_CHARS} characters"));
123        }
124        Ok(())
125    }
126}
127
128/// The key of an artifact-site view showing version `version` of artifact `id`.
129pub fn artifact_key(id: &str, version: u32) -> String {
130    format!("{id}@{version}")
131}
132
133/// An artifact-site view key back to (artifact id, version).
134pub fn parse_artifact_key(key: &str) -> Option<(&str, u32)> {
135    let (id, v) = key.rsplit_once('@')?;
136    let v: u32 = v.parse().ok()?;
137    (crate::artifact::valid_id(id) && v > 0).then_some((id, v))
138}
139
140/// A view id: `[a-z0-9_-]{1,48}`.
141pub fn view_id_ok(id: &str) -> bool {
142    (1..=MAX_VIEW_ID_CHARS).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'-'))
143}
144
145/// A live view's tree or a change to it ([`crate::ServerMsg::LiveView`]). Exactly one of:
146/// `tree` (replace what the client has), `patch` (apply to it, in order), `error` (the
147/// view couldn't be had: show it at the site), `reset` (forget it; open it again to get
148/// the new one, e.g. after the plugin reloaded). `values` force field values over what the
149/// user typed (only to the client whose event caused the reply). `faults` are what the
150/// engine had to fix in the plugin's tree (also in the plugin's status for the model).
151#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
152pub struct LiveView {
153    pub view: ViewRef,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub tree: Option<Node>,
156    #[serde(default, skip_serializing_if = "Vec::is_empty")]
157    pub patch: Vec<Patch>,
158    #[serde(default, skip_serializing_if = "Map::is_empty")]
159    pub values: Map<String, Value>,
160    #[serde(default, skip_serializing_if = "Option::is_none")]
161    pub error: Option<String>,
162    #[serde(default, skip_serializing_if = "Vec::is_empty")]
163    pub faults: Vec<String>,
164    #[serde(default, skip_serializing_if = "is_false")]
165    pub reset: bool,
166}
167
168fn is_false(b: &bool) -> bool {
169    !*b
170}
171
172/// Size checks of the view messages (see [`crate::ClientMsg::check_sizes`]).
173pub(crate) fn check_sizes(msg: &crate::ClientMsg) -> Result<(), String> {
174    use crate::ClientMsg;
175    match msg {
176        ClientMsg::OpenView { view } | ClientMsg::CloseView { view } => view.check(),
177        ClientMsg::ViewEvent { view, event } => {
178            view.check()?;
179            check_event(event)
180        }
181        _ => Ok(()),
182    }
183}
184
185fn check_event(e: &Event) -> Result<(), String> {
186    if e.action.chars().count() > crate::tree::MAX_TEXT_CHARS {
187        return Err("the event's action is too long".into());
188    }
189    if e.values.len() > crate::tree::MAX_VALUES {
190        return Err(format!("an event carries at most {} values", crate::tree::MAX_VALUES));
191    }
192    let size = serde_json::to_string(e).map_or(usize::MAX, |s| s.len());
193    if size > MAX_EVENT_BYTES {
194        return Err(format!("event too large ({size} bytes, at most {MAX_EVENT_BYTES})"));
195    }
196    Ok(())
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::tree::{Kind, Target};
203    use crate::{ClientMsg, ServerMsg};
204
205    #[test]
206    fn view_messages_round_trip_and_are_checked() {
207        let r = ViewRef::new("todo", "list", "");
208        let event = Event { action: "add".into(), values: serde_json::json!({"new": "milk"}).as_object().cloned().unwrap_or_default(), edit: None, grid: None };
209        for m in [ClientMsg::OpenView { view: r.clone() }, ClientMsg::CloseView { view: r.clone() }, ClientMsg::ViewEvent { view: r.clone(), event }] {
210            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
211            assert!(m.check_sizes().is_ok());
212        }
213        assert_eq!(ClientMsg::OpenView { view: r.clone() }.to_json(), r#"{"type":"open_view","view":{"plugin":"todo","view":"list"}}"#);
214        for bad in [ViewRef::new("Todo", "list", ""), ViewRef::new("todo", "a b", ""), ViewRef::new("todo", "list", "k".repeat(MAX_VIEW_KEY_CHARS + 1))] {
215            assert!(ClientMsg::OpenView { view: bad }.check_sizes().is_err());
216        }
217        let big =
218            Event { action: "x".into(), values: [("t".to_owned(), Value::String("x".repeat(MAX_EVENT_BYTES)))].into_iter().collect(), edit: None, grid: None };
219        assert!(ClientMsg::ViewEvent { view: r.clone(), event: big }.check_sizes().is_err());
220
221        let tree = Node::new(Kind::Text { text: "3 left".into(), style: Default::default(), tone: Default::default() });
222        let msgs = [
223            ServerMsg::LiveView(LiveView { view: r.clone(), tree: Some(tree), faults: vec!["/x: y".into()], ..Default::default() }),
224            ServerMsg::LiveView(LiveView {
225                view: r.clone(),
226                patch: vec![Patch::Remove { at: Target::key("a") }],
227                values: serde_json::json!({"new": ""}).as_object().cloned().unwrap_or_default(),
228                ..Default::default()
229            }),
230            ServerMsg::LiveView(LiveView { view: r.clone(), error: Some("no backend".into()), ..Default::default() }),
231            ServerMsg::LiveView(LiveView { view: r, reset: true, ..Default::default() }),
232        ];
233        for m in msgs {
234            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
235        }
236    }
237
238    #[test]
239    fn sites_and_ids() {
240        for s in Site::ALL {
241            assert_eq!(Site::parse(s.label()), Some(s));
242        }
243        assert_eq!(serde_json::from_str::<Site>(r#""sidebar""#).unwrap(), Site::Other);
244        assert!(view_id_ok("todo_list-2") && !view_id_ok("") && !view_id_ok("Todo") && !view_id_ok(&"x".repeat(49)));
245        // A 13.2 plugin list (no views) still parses, and views travel when there are some.
246        let d: ViewDecl = serde_json::from_str(r#"{"id":"list","site":"pane"}"#).unwrap();
247        assert_eq!((d.title.as_str(), d.icon.as_str()), ("", ""));
248    }
249
250    /// 13.3 additions are optional on the wire both ways: a 13.2 peer's messages parse here,
251    /// and what 13.3 adds is left out when empty (so 13.2 peers see the same JSON as before).
252    #[test]
253    fn minor_3_is_compatible_with_minor_2() {
254        let card = crate::PluginCard {
255            plugin: "p".into(),
256            scope: crate::PluginScope::Chat,
257            action: crate::PluginAction::Made,
258            tools: vec![],
259            added: vec![],
260            removed: vec![],
261            test: None,
262            problems: vec![],
263            missing_settings: vec![],
264        };
265        let v = crate::View::of(&card);
266        assert!(!serde_json::to_string(&v).unwrap().contains("owner"));
267        let old: crate::View = serde_json::from_str(r#"{"kind":"byob.tree","v":1,"data":{"type":"text","text":"x"},"fallback":"x"}"#).unwrap();
268        assert_eq!(old.owner, None);
269        let mut owned = old.clone();
270        owned.owner = Some(ViewRef::new("todo", "item", "3"));
271        let back: crate::View = serde_json::from_str(&serde_json::to_string(&owned).unwrap()).unwrap();
272        assert_eq!(back, owned);
273        // a 13.2 client doesn't know LiveView: it skips it
274        let lv = ServerMsg::LiveView(LiveView { view: ViewRef::new("todo", "list", ""), reset: true, ..Default::default() }).to_json();
275        assert!(lv.starts_with(r#"{"type":"live_view""#), "{lv}");
276    }
277}