Skip to main content

byob_types/
layout.rs

1//! What byob's interface shows, and in what order: the **layout**.
2//!
3//! Every optional piece of the window's chrome has an id in [`ELEMENTS`] (`reply.tokens`,
4//! `header.usage`, …) and a [`Show`] mode: always, only while the pointer is on it, or never.
5//! A few regions ([`REGIONS`]) can be reordered: their elements, plus plugin views drawn
6//! there (`view:<plugin>/<view>`), which are placed and hidden the same way as byob's own.
7//!
8//! The engine keeps one layout (settings.json `layout`) and sends it to every client, so a
9//! change made in Settings or by the model (the `ui_layout` tool) shows everywhere at once.
10//! Only what differs from the defaults is stored; elements a newer build adds get their
11//! defaults, and ids this build doesn't know are kept (a newer build's, or a plugin's that
12//! isn't loaded).
13
14use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18/// How an element is shown.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Show {
22    /// Always there.
23    Shown,
24    /// Only while the pointer is on what it belongs to (the reply, the header, the row).
25    Hover,
26    /// Never.
27    Hidden,
28}
29
30impl Show {
31    pub const ALL: [Self; 3] = [Self::Shown, Self::Hover, Self::Hidden];
32
33    pub fn as_str(self) -> &'static str {
34        match self {
35            Self::Shown => "shown",
36            Self::Hover => "hover",
37            Self::Hidden => "hidden",
38        }
39    }
40
41    pub fn parse(s: &str) -> Option<Self> {
42        match s.trim().to_ascii_lowercase().as_str() {
43            "shown" | "show" | "always" | "visible" | "on" => Some(Self::Shown),
44            "hover" | "on_hover" | "on hover" | "hovered" => Some(Self::Hover),
45            "hidden" | "hide" | "never" | "off" | "none" => Some(Self::Hidden),
46            _ => None,
47        }
48    }
49
50    /// Whether it is drawn now, `hovered` being whether the pointer is on its owner.
51    pub fn visible(self, hovered: bool) -> bool {
52        match self {
53            Self::Shown => true,
54            Self::Hover => hovered,
55            Self::Hidden => false,
56        }
57    }
58}
59
60/// A region whose elements can be reordered.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct Region {
63    pub id: &'static str,
64    /// Where it is, for people (and the model).
65    pub describe: &'static str,
66    /// Whether plugin views (`view:…`) are drawn here.
67    pub plugin_views: bool,
68}
69
70/// An element of the interface that can be shown, hidden or moved.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct Element {
73    pub id: &'static str,
74    /// Its name in Settings.
75    pub label: &'static str,
76    /// What it is, for people (and the model).
77    pub describe: &'static str,
78    /// The region it can be moved within, if any.
79    pub region: Option<&'static str>,
80    pub default: Show,
81    /// Whether [`Show::Hover`] means something for it (else it acts as shown).
82    pub hover: bool,
83}
84
85pub const HEADER: &str = "header";
86pub const TOOLBAR: &str = "toolbar";
87pub const REPLY: &str = "reply";
88
89/// The regions that can be reordered, each listed left to right.
90pub const REGIONS: &[Region] = &[
91    Region { id: HEADER, describe: "the header after the chat's title, left to right", plugin_views: false },
92    Region { id: TOOLBAR, describe: "the header's buttons on the right, left to right (the More menu always stays last)", plugin_views: true },
93    Region { id: REPLY, describe: "the details under a reply, left to right", plugin_views: false },
94];
95
96const fn el(id: &'static str, label: &'static str, describe: &'static str, region: Option<&'static str>, default: Show, hover: bool) -> Element {
97    Element { id, label, describe, region, default, hover }
98}
99
100/// Everything the layout knows, in the order Settings lists them (and each region's default order).
101pub const ELEMENTS: &[Element] = &[
102    // Header, after the title.
103    el("header.model", "Model", "the model chip: which model this chat uses; click it to switch", Some(HEADER), Show::Shown, true),
104    el("header.usage", "Context meter", "the bar of how full the chat's context is; click it for details", Some(HEADER), Show::Shown, true),
105    el("header.server", "Server address", "the server's address inside the model chip, on wide windows", None, Show::Shown, false),
106    el("header.usage_numbers", "Context numbers", "tokens used out of the context window, next to the context meter", None, Show::Shown, true),
107    el("header.wordmark", "Wordmark", "the \"byob\" name on the left of the header, on wide windows", None, Show::Shown, false),
108    el("header.workspace", "Workspace name", "the workspace's name before the chat's title", None, Show::Shown, true),
109    // Header, right.
110    el("toolbar.panes", "Plugin panes", "buttons that open plugins' panes beside the chat", Some(TOOLBAR), Show::Shown, true),
111    el("toolbar.artifacts", "Artifacts button", "the button that shows or hides the artifact pane", Some(TOOLBAR), Show::Shown, true),
112    el("toolbar.plugins", "Plugins chip", "how many plugins are on, with a badge when one has trouble", Some(TOOLBAR), Show::Shown, true),
113    // Messages.
114    el("message.role", "Who said it", "\"You\" and \"byob\" above each message", None, Show::Shown, false),
115    el(
116        "message.thinking",
117        "Thinking",
118        "the \"Thought\" row that opens the model's thinking; hidden, it shows only while the model is still thinking",
119        None,
120        Show::Shown,
121        false,
122    ),
123    el("message.thought_size", "Thinking length", "how long the model's thinking was, next to \"Thought\" (\"1.1k chars\")", None, Show::Shown, false),
124    el(
125        "message.steps",
126        "Tool steps",
127        "a row for each tool the model ran (\"Read notes.md\", \"Made Rain haiku\"); hidden, they show only while running (failed ones are hidden too; questions and approvals always show)",
128        None,
129        Show::Shown,
130        false,
131    ),
132    el("message.step_files", "Files changed", "\"1 file\" (\"3 files\") on a tool's row when it changed files", None, Show::Shown, false),
133    el("message.subagent_details", "Subagent details", "the model and tokens on a subagent's row", None, Show::Shown, false),
134    el("message.edit", "Edit button", "\"Edit\" on your messages: change one and start the chat over from there", None, Show::Hover, true),
135    el("message.undo", "Undo button", "\"Undo changes\" under a reply that changed files", None, Show::Shown, true),
136    el(
137        "reply.tokens",
138        "Tokens",
139        "tokens under each reply: how full the context was at its end, what the model wrote, and what several requests read together",
140        Some(REPLY),
141        Show::Shown,
142        true,
143    ),
144    el("reply.time", "Time", "how long the reply took, under each reply", Some(REPLY), Show::Shown, true),
145    el("reply.speed", "Speed", "tokens per second the model wrote, under each reply", Some(REPLY), Show::Hidden, true),
146    // Artifacts and code in replies.
147    el("artifact.kind", "Artifact kind", "the kind badge on an artifact's card in a reply (\"DOCUMENT\", \"APP\", \"CHART\")", None, Show::Shown, false),
148    el("artifact.version", "Artifact version", "the version on an artifact's card in a reply (\"v1\") and its note", None, Show::Shown, false),
149    el(
150        "artifact.shown",
151        "Artifact shown note",
152        "\"Shown beside the chat\" on an artifact's card in a reply while it's open in the artifact pane",
153        None,
154        Show::Shown,
155        true,
156    ),
157    el("code.language", "Code language", "the language (\"rust\", \"code\") at the top left of a code block", None, Show::Shown, true),
158    el("code.copy", "Code copy button", "\"Copy\" at the top right of a code block", None, Show::Shown, true),
159    // Elsewhere.
160    el("chat.starters", "Suggestions", "the suggested prompts in an empty chat (\"Ask anything to get started, or try:\")", None, Show::Shown, false),
161    el(
162        "composer.attach",
163        "Attach button",
164        "the paperclip that attaches files, left of the message box (dropping or pasting files still works)",
165        None,
166        Show::Shown,
167        false,
168    ),
169    el("composer.keys", "Composer keys", "\"Enter to send, Shift+Enter for a new line\" in the empty message box", None, Show::Shown, false),
170    el("sidebar.shortcuts", "Sidebar shortcuts", "the keyboard shortcuts on New chat and the search field", None, Show::Shown, true),
171];
172
173/// Where elements that aren't in a region are, by id prefix, in the order Settings lists them.
174pub const GROUPS: &[(&str, &str)] = &[
175    ("header", "Header"),
176    ("message", "Messages"),
177    ("artifact", "Artifacts in replies"),
178    ("code", "Code blocks"),
179    ("chat", "Empty chat"),
180    ("composer", "Message box"),
181    ("sidebar", "Sidebar"),
182];
183
184/// The heading of the group element `id` is in ([`GROUPS`]).
185pub fn group(id: &str) -> &'static str {
186    let prefix = id.split('.').next().unwrap_or_default();
187    GROUPS.iter().find(|(p, _)| *p == prefix).map_or("Other", |(_, name)| name)
188}
189
190/// The element with id `id`.
191pub fn element(id: &str) -> Option<&'static Element> {
192    ELEMENTS.iter().find(|e| e.id == id)
193}
194
195/// The region with id `id`.
196pub fn region(id: &str) -> Option<&'static Region> {
197    REGIONS.iter().find(|r| r.id == id)
198}
199
200/// The id of plugin `plugin`'s view `view` in a layout.
201pub fn view_id(plugin: &str, view: &str) -> String {
202    format!("view:{plugin}/{view}")
203}
204
205/// Ready-made layouts.
206pub const PRESETS: &[(&str, &str)] = &[
207    ("everything", "every detail shown (byob's default)"),
208    ("balanced", "details of replies and the context numbers on hover; labels and shortcut hints hidden"),
209    ("minimal", "only what you need: details on hover, the rest hidden"),
210];
211
212/// Most entries kept per map (ids are few; the rest is a hostile or broken file).
213const MAX_ENTRIES: usize = 256;
214const MAX_ID: usize = 160;
215
216/// What the interface shows: the modes and orders that differ from the defaults.
217#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
218#[serde(default)]
219pub struct Layout {
220    /// Element id → how it is shown.
221    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
222    pub show: BTreeMap<String, Show>,
223    /// Region id → element ids in the order wanted. Ids a region doesn't have are skipped;
224    /// those it has but the list doesn't name follow, in their default order.
225    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
226    pub order: BTreeMap<String, Vec<String>>,
227}
228
229impl Layout {
230    pub fn is_default(&self) -> bool {
231        self.show.is_empty() && self.order.is_empty()
232    }
233
234    /// How element (or plugin view) `id` is shown. Unknown ids are shown.
235    pub fn show(&self, id: &str) -> Show {
236        let mode = self.show.get(id).copied().or_else(|| element(id).map(|e| e.default)).unwrap_or(Show::Shown);
237        match element(id) {
238            Some(e) if !e.hover && mode == Show::Hover => Show::Shown,
239            _ => mode,
240        }
241    }
242
243    /// Whether `id` is drawn now (`hovered`: the pointer is on what it belongs to).
244    pub fn visible(&self, id: &str, hovered: bool) -> bool {
245        self.show(id).visible(hovered)
246    }
247
248    /// Set how `id` is shown; back to the default stores nothing.
249    pub fn set_show(&mut self, id: &str, mode: Show) {
250        if element(id).is_some_and(|e| e.default == mode) {
251            self.show.remove(id);
252        } else {
253            self.show.insert(id.to_owned(), mode);
254        }
255    }
256
257    /// Region `region`'s elements in order: byob's own (in [`ELEMENTS`] order) and then
258    /// `extra` (plugin views drawn there, as found), arranged by the stored order. Hidden
259    /// ones are included; ask [`Self::show`].
260    pub fn arrange(&self, region: &str, extra: &[String]) -> Vec<String> {
261        let mut present: Vec<String> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id.to_owned()).collect();
262        for id in extra {
263            if !present.contains(id) {
264                present.push(id.clone());
265            }
266        }
267        let Some(wanted) = self.order.get(region) else { return present };
268        let mut out: Vec<String> = Vec::with_capacity(present.len());
269        for id in wanted {
270            if present.contains(id) && !out.contains(id) {
271                out.push(id.clone());
272            }
273        }
274        for id in present {
275            if !out.contains(&id) {
276                out.push(id);
277            }
278        }
279        out
280    }
281
282    /// Put region `region` in this order (see [`Self::order`]); the default order stores nothing.
283    pub fn set_order(&mut self, region: &str, ids: Vec<String>) {
284        let default: Vec<&str> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id).collect();
285        let mut ids: Vec<String> = ids.into_iter().filter(|id| !id.is_empty()).collect();
286        ids.dedup();
287        if ids.is_empty() || ids.iter().map(String::as_str).eq(default.iter().copied()) {
288            self.order.remove(region);
289        } else {
290            self.order.insert(region.to_owned(), ids);
291        }
292    }
293
294    /// Move `id` one place earlier (`dir` < 0) or later within region `region`, among `extra`.
295    pub fn nudge(&mut self, region: &str, extra: &[String], id: &str, dir: i32) {
296        let mut ids = self.arrange(region, extra);
297        let Some(i) = ids.iter().position(|x| x == id) else { return };
298        let j = if dir < 0 { i.checked_sub(1) } else { Some(i + 1).filter(|j| *j < ids.len()) };
299        if let Some(j) = j {
300            ids.swap(i, j);
301            self.set_order(region, ids);
302        }
303    }
304
305    /// A ready-made layout by name ([`PRESETS`]).
306    pub fn preset(name: &str) -> Option<Self> {
307        let mut l = Self::default();
308        let hover = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hover));
309        let hide = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hidden));
310        match name.trim().to_ascii_lowercase().as_str() {
311            "everything" | "default" | "full" => {}
312            "balanced" => {
313                hover(&mut l, &["reply.tokens", "reply.time", "header.usage_numbers", "sidebar.shortcuts"]);
314                hide(&mut l, &["message.role", "message.thought_size", "composer.keys"]);
315            }
316            "minimal" => {
317                hover(&mut l, &["reply.tokens", "reply.time", "sidebar.shortcuts", "toolbar.plugins", "artifact.shown", "message.undo", "code.copy"]);
318                hide(
319                    &mut l,
320                    &[
321                        "message.role",
322                        "message.thought_size",
323                        "message.step_files",
324                        "message.subagent_details",
325                        "artifact.version",
326                        "code.language",
327                        "composer.keys",
328                        "header.usage_numbers",
329                        "header.server",
330                        "header.wordmark",
331                    ],
332                );
333            }
334            _ => return None,
335        }
336        Some(l)
337    }
338
339    /// Drop what a broken or hostile file could hold: too many entries, absurd ids, empty orders.
340    #[must_use]
341    pub fn sanitized(mut self) -> Self {
342        let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
343        self.show.retain(|id, _| ok(id));
344        while self.show.len() > MAX_ENTRIES {
345            self.show.pop_last();
346        }
347        self.order.retain(|region, ids| {
348            ids.retain(&ok);
349            ids.truncate(MAX_ENTRIES);
350            ok(region) && !ids.is_empty()
351        });
352        while self.order.len() > MAX_ENTRIES {
353            self.order.pop_last();
354        }
355        self
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn defaults_show_everything_but_speed_and_store_nothing() {
365        let l = Layout::default();
366        for e in ELEMENTS {
367            assert_eq!(l.show(e.id), e.default, "{}", e.id);
368        }
369        assert_eq!(l.show("reply.speed"), Show::Hidden);
370        assert_eq!(l.show("view:todo/count"), Show::Shown);
371        let mut l = Layout::default();
372        l.set_show("reply.tokens", Show::Hover);
373        l.set_show("reply.tokens", Show::Shown);
374        assert!(l.is_default(), "back to the default stores nothing");
375        assert_eq!(serde_json::to_string(&l).unwrap(), "{}");
376    }
377
378    #[test]
379    fn hover_falls_back_to_shown_where_it_means_nothing() {
380        let mut l = Layout::default();
381        l.set_show("message.role", Show::Hover);
382        assert_eq!(l.show("message.role"), Show::Shown);
383        l.set_show("reply.time", Show::Hover);
384        assert!(!l.visible("reply.time", false));
385        assert!(l.visible("reply.time", true));
386    }
387
388    #[test]
389    fn arranging_puts_named_ids_first_and_keeps_the_rest_in_their_order() {
390        let views = vec!["view:todo/count".to_owned()];
391        let mut l = Layout::default();
392        assert_eq!(l.arrange(TOOLBAR, &views), ["toolbar.panes", "toolbar.artifacts", "toolbar.plugins", "view:todo/count"]);
393        l.set_order(TOOLBAR, vec!["view:todo/count".into(), "nope".into(), "toolbar.plugins".into()]);
394        assert_eq!(l.arrange(TOOLBAR, &views), ["view:todo/count", "toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
395        // A plugin view that isn't loaded is skipped (and kept for when it is).
396        assert_eq!(l.arrange(TOOLBAR, &[]), ["toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
397        assert!(l.order[TOOLBAR].contains(&"view:todo/count".to_owned()));
398    }
399
400    #[test]
401    fn nudging_moves_one_place_and_the_default_order_stores_nothing() {
402        let mut l = Layout::default();
403        l.nudge(REPLY, &[], "reply.time", -1);
404        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"]);
405        l.nudge(REPLY, &[], "reply.time", -1);
406        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"], "already first");
407        l.nudge(REPLY, &[], "reply.time", 1);
408        assert!(l.is_default());
409    }
410
411    #[test]
412    fn presets_are_named_and_known() {
413        for (name, _) in PRESETS {
414            assert!(Layout::preset(name).is_some(), "{name}");
415        }
416        assert!(Layout::preset("everything").unwrap().is_default());
417        assert!(Layout::preset("sparkly").is_none());
418        let min = Layout::preset("minimal").unwrap();
419        assert!(!min.visible("reply.tokens", false) && min.visible("reply.tokens", true));
420        for id in min.show.keys() {
421            assert!(element(id).is_some(), "{id}");
422        }
423    }
424
425    #[test]
426    fn modes_parse_loosely_and_sanitizing_drops_junk() {
427        assert_eq!(Show::parse(" Hide "), Some(Show::Hidden));
428        assert_eq!(Show::parse("on hover"), Some(Show::Hover));
429        assert_eq!(Show::parse("maybe"), None);
430        let l: Layout = serde_json::from_str(r#"{"show": {"": "hidden", "a\u0007": "hidden", "reply.time": "hover"}, "order": {"reply": []}}"#).unwrap();
431        let l = l.sanitized();
432        assert_eq!(l.show.len(), 1);
433        assert!(l.order.is_empty());
434    }
435
436    #[test]
437    fn every_element_is_unique_and_its_region_exists() {
438        for (i, e) in ELEMENTS.iter().enumerate() {
439            assert!(ELEMENTS[..i].iter().all(|o| o.id != e.id), "{}", e.id);
440            assert!(e.region.is_none_or(|r| region(r).is_some()), "{}", e.id);
441        }
442    }
443}