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