1use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum Show {
22 Shown,
24 Hover,
26 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62pub struct Region {
63 pub id: &'static str,
64 pub describe: &'static str,
66 pub plugin_views: bool,
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub struct Element {
73 pub id: &'static str,
74 pub label: &'static str,
76 pub describe: &'static str,
78 pub region: Option<&'static str>,
80 pub default: Show,
81 pub hover: bool,
83}
84
85pub const HEADER: &str = "header";
86pub const TOOLBAR: &str = "toolbar";
87pub const REPLY: &str = "reply";
88
89pub 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
100pub const ELEMENTS: &[Element] = &[
102 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 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 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("reply.tokens", "Tokens", "tokens in and out, under each reply", Some(REPLY), Show::Shown, true),
137 el("reply.time", "Time", "how long the reply took, under each reply", Some(REPLY), Show::Shown, true),
138 el("reply.speed", "Speed", "tokens per second the model wrote, under each reply", Some(REPLY), Show::Hidden, true),
139 el("artifact.kind", "Artifact kind", "the kind badge on an artifact's card in a reply (\"DOCUMENT\", \"APP\", \"CHART\")", None, Show::Shown, false),
141 el("artifact.version", "Artifact version", "the version on an artifact's card in a reply (\"v1\") and its note", None, Show::Shown, false),
142 el(
143 "artifact.shown",
144 "Artifact shown note",
145 "\"Shown beside the chat\" on an artifact's card in a reply while it's open in the artifact pane",
146 None,
147 Show::Shown,
148 true,
149 ),
150 el("code.language", "Code language", "the language (\"rust\", \"code\") at the top left of a code block", None, Show::Shown, true),
151 el("code.copy", "Code copy button", "\"Copy\" at the top right of a code block", None, Show::Shown, true),
152 el("chat.starters", "Suggestions", "the suggested prompts in an empty chat (\"Ask anything to get started, or try:\")", None, Show::Shown, false),
154 el(
155 "composer.attach",
156 "Attach button",
157 "the paperclip that attaches files, left of the message box (dropping or pasting files still works)",
158 None,
159 Show::Shown,
160 false,
161 ),
162 el("composer.keys", "Composer keys", "\"Enter to send, Shift+Enter for a new line\" in the empty message box", None, Show::Shown, false),
163 el("sidebar.shortcuts", "Sidebar shortcuts", "the keyboard shortcuts on New chat and the search field", None, Show::Shown, true),
164];
165
166pub const GROUPS: &[(&str, &str)] = &[
168 ("header", "Header"),
169 ("message", "Messages"),
170 ("artifact", "Artifacts in replies"),
171 ("code", "Code blocks"),
172 ("chat", "Empty chat"),
173 ("composer", "Message box"),
174 ("sidebar", "Sidebar"),
175];
176
177pub fn group(id: &str) -> &'static str {
179 let prefix = id.split('.').next().unwrap_or_default();
180 GROUPS.iter().find(|(p, _)| *p == prefix).map_or("Other", |(_, name)| name)
181}
182
183pub fn element(id: &str) -> Option<&'static Element> {
185 ELEMENTS.iter().find(|e| e.id == id)
186}
187
188pub fn region(id: &str) -> Option<&'static Region> {
190 REGIONS.iter().find(|r| r.id == id)
191}
192
193pub fn view_id(plugin: &str, view: &str) -> String {
195 format!("view:{plugin}/{view}")
196}
197
198pub const PRESETS: &[(&str, &str)] = &[
200 ("everything", "every detail shown (byob's default)"),
201 ("balanced", "details of replies and the context numbers on hover; labels and shortcut hints hidden"),
202 ("minimal", "only what you need: details on hover, the rest hidden"),
203];
204
205const MAX_ENTRIES: usize = 256;
207const MAX_ID: usize = 160;
208
209#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(default)]
212pub struct Layout {
213 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
215 pub show: BTreeMap<String, Show>,
216 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
219 pub order: BTreeMap<String, Vec<String>>,
220}
221
222impl Layout {
223 pub fn is_default(&self) -> bool {
224 self.show.is_empty() && self.order.is_empty()
225 }
226
227 pub fn show(&self, id: &str) -> Show {
229 let mode = self.show.get(id).copied().or_else(|| element(id).map(|e| e.default)).unwrap_or(Show::Shown);
230 match element(id) {
231 Some(e) if !e.hover && mode == Show::Hover => Show::Shown,
232 _ => mode,
233 }
234 }
235
236 pub fn visible(&self, id: &str, hovered: bool) -> bool {
238 self.show(id).visible(hovered)
239 }
240
241 pub fn set_show(&mut self, id: &str, mode: Show) {
243 if element(id).is_some_and(|e| e.default == mode) {
244 self.show.remove(id);
245 } else {
246 self.show.insert(id.to_owned(), mode);
247 }
248 }
249
250 pub fn arrange(&self, region: &str, extra: &[String]) -> Vec<String> {
254 let mut present: Vec<String> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id.to_owned()).collect();
255 for id in extra {
256 if !present.contains(id) {
257 present.push(id.clone());
258 }
259 }
260 let Some(wanted) = self.order.get(region) else { return present };
261 let mut out: Vec<String> = Vec::with_capacity(present.len());
262 for id in wanted {
263 if present.contains(id) && !out.contains(id) {
264 out.push(id.clone());
265 }
266 }
267 for id in present {
268 if !out.contains(&id) {
269 out.push(id);
270 }
271 }
272 out
273 }
274
275 pub fn set_order(&mut self, region: &str, ids: Vec<String>) {
277 let default: Vec<&str> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id).collect();
278 let mut ids: Vec<String> = ids.into_iter().filter(|id| !id.is_empty()).collect();
279 ids.dedup();
280 if ids.is_empty() || ids.iter().map(String::as_str).eq(default.iter().copied()) {
281 self.order.remove(region);
282 } else {
283 self.order.insert(region.to_owned(), ids);
284 }
285 }
286
287 pub fn nudge(&mut self, region: &str, extra: &[String], id: &str, dir: i32) {
289 let mut ids = self.arrange(region, extra);
290 let Some(i) = ids.iter().position(|x| x == id) else { return };
291 let j = if dir < 0 { i.checked_sub(1) } else { Some(i + 1).filter(|j| *j < ids.len()) };
292 if let Some(j) = j {
293 ids.swap(i, j);
294 self.set_order(region, ids);
295 }
296 }
297
298 pub fn preset(name: &str) -> Option<Self> {
300 let mut l = Self::default();
301 let hover = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hover));
302 let hide = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hidden));
303 match name.trim().to_ascii_lowercase().as_str() {
304 "everything" | "default" | "full" => {}
305 "balanced" => {
306 hover(&mut l, &["reply.tokens", "reply.time", "header.usage_numbers", "sidebar.shortcuts"]);
307 hide(&mut l, &["message.role", "message.thought_size", "composer.keys"]);
308 }
309 "minimal" => {
310 hover(&mut l, &["reply.tokens", "reply.time", "sidebar.shortcuts", "toolbar.plugins", "artifact.shown", "message.undo", "code.copy"]);
311 hide(
312 &mut l,
313 &[
314 "message.role",
315 "message.thought_size",
316 "message.step_files",
317 "message.subagent_details",
318 "artifact.version",
319 "code.language",
320 "composer.keys",
321 "header.usage_numbers",
322 "header.server",
323 "header.wordmark",
324 ],
325 );
326 }
327 _ => return None,
328 }
329 Some(l)
330 }
331
332 #[must_use]
334 pub fn sanitized(mut self) -> Self {
335 let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
336 self.show.retain(|id, _| ok(id));
337 while self.show.len() > MAX_ENTRIES {
338 self.show.pop_last();
339 }
340 self.order.retain(|region, ids| {
341 ids.retain(&ok);
342 ids.truncate(MAX_ENTRIES);
343 ok(region) && !ids.is_empty()
344 });
345 while self.order.len() > MAX_ENTRIES {
346 self.order.pop_last();
347 }
348 self
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn defaults_show_everything_but_speed_and_store_nothing() {
358 let l = Layout::default();
359 for e in ELEMENTS {
360 assert_eq!(l.show(e.id), e.default, "{}", e.id);
361 }
362 assert_eq!(l.show("reply.speed"), Show::Hidden);
363 assert_eq!(l.show("view:todo/count"), Show::Shown);
364 let mut l = Layout::default();
365 l.set_show("reply.tokens", Show::Hover);
366 l.set_show("reply.tokens", Show::Shown);
367 assert!(l.is_default(), "back to the default stores nothing");
368 assert_eq!(serde_json::to_string(&l).unwrap(), "{}");
369 }
370
371 #[test]
372 fn hover_falls_back_to_shown_where_it_means_nothing() {
373 let mut l = Layout::default();
374 l.set_show("message.role", Show::Hover);
375 assert_eq!(l.show("message.role"), Show::Shown);
376 l.set_show("reply.time", Show::Hover);
377 assert!(!l.visible("reply.time", false));
378 assert!(l.visible("reply.time", true));
379 }
380
381 #[test]
382 fn arranging_puts_named_ids_first_and_keeps_the_rest_in_their_order() {
383 let views = vec!["view:todo/count".to_owned()];
384 let mut l = Layout::default();
385 assert_eq!(l.arrange(TOOLBAR, &views), ["toolbar.panes", "toolbar.artifacts", "toolbar.plugins", "view:todo/count"]);
386 l.set_order(TOOLBAR, vec!["view:todo/count".into(), "nope".into(), "toolbar.plugins".into()]);
387 assert_eq!(l.arrange(TOOLBAR, &views), ["view:todo/count", "toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
388 assert_eq!(l.arrange(TOOLBAR, &[]), ["toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
390 assert!(l.order[TOOLBAR].contains(&"view:todo/count".to_owned()));
391 }
392
393 #[test]
394 fn nudging_moves_one_place_and_the_default_order_stores_nothing() {
395 let mut l = Layout::default();
396 l.nudge(REPLY, &[], "reply.time", -1);
397 assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"]);
398 l.nudge(REPLY, &[], "reply.time", -1);
399 assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"], "already first");
400 l.nudge(REPLY, &[], "reply.time", 1);
401 assert!(l.is_default());
402 }
403
404 #[test]
405 fn presets_are_named_and_known() {
406 for (name, _) in PRESETS {
407 assert!(Layout::preset(name).is_some(), "{name}");
408 }
409 assert!(Layout::preset("everything").unwrap().is_default());
410 assert!(Layout::preset("sparkly").is_none());
411 let min = Layout::preset("minimal").unwrap();
412 assert!(!min.visible("reply.tokens", false) && min.visible("reply.tokens", true));
413 for id in min.show.keys() {
414 assert!(element(id).is_some(), "{id}");
415 }
416 }
417
418 #[test]
419 fn modes_parse_loosely_and_sanitizing_drops_junk() {
420 assert_eq!(Show::parse(" Hide "), Some(Show::Hidden));
421 assert_eq!(Show::parse("on hover"), Some(Show::Hover));
422 assert_eq!(Show::parse("maybe"), None);
423 let l: Layout = serde_json::from_str(r#"{"show": {"": "hidden", "a\u0007": "hidden", "reply.time": "hover"}, "order": {"reply": []}}"#).unwrap();
424 let l = l.sanitized();
425 assert_eq!(l.show.len(), 1);
426 assert!(l.order.is_empty());
427 }
428
429 #[test]
430 fn every_element_is_unique_and_its_region_exists() {
431 for (i, e) in ELEMENTS.iter().enumerate() {
432 assert!(ELEMENTS[..i].iter().all(|o| o.id != e.id), "{}", e.id);
433 assert!(e.region.is_none_or(|r| region(r).is_some()), "{}", e.id);
434 }
435 }
436}