byob-types 0.3.13

Shared serde types: messages, steps, attachments, settings (L0)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! What byob's interface shows, and in what order: the **layout**.
//!
//! Every optional piece of the window's chrome has an id in [`ELEMENTS`] (`reply.tokens`,
//! `header.usage`, …) and a [`Show`] mode: always, only while the pointer is on it, or never.
//! A few regions ([`REGIONS`]) can be reordered: their elements, plus plugin views drawn
//! there (`view:<plugin>/<view>`), which are placed and hidden the same way as byob's own.
//!
//! The engine keeps one layout (settings.json `layout`) and sends it to every client, so a
//! change made in Settings or by the model (the `ui_layout` tool) shows everywhere at once.
//! Only what differs from the defaults is stored; elements a newer build adds get their
//! defaults, and ids this build doesn't know are kept (a newer build's, or a plugin's that
//! isn't loaded).

use std::collections::BTreeMap;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Value;

// Reading is forgiving: a value this build can't read (a newer build's, a hand edit) is
// dropped alone, so the rest of the layout (Spaces, sections, pins) survives.

/// A field of the wrong shape is its default.
fn lenient<'de, D: Deserializer<'de>, T: DeserializeOwned + Default>(d: D) -> Result<T, D::Error> {
    Ok(serde_json::from_value(Value::deserialize(d)?).unwrap_or_default())
}

/// A list whose entries are read one by one: those that can't be are dropped.
fn lenient_list<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<Vec<T>, D::Error> {
    match Value::deserialize(d)? {
        Value::Array(items) => Ok(items.into_iter().filter_map(|v| serde_json::from_value(v).ok()).collect()),
        _ => Ok(Vec::new()),
    }
}

/// A map whose entries are read one by one: those that can't be are dropped.
fn lenient_map<'de, D: Deserializer<'de>, T: DeserializeOwned>(d: D) -> Result<BTreeMap<String, T>, D::Error> {
    match Value::deserialize(d)? {
        Value::Object(map) => Ok(map.into_iter().filter_map(|(k, v)| serde_json::from_value(v).ok().map(|v| (k, v))).collect()),
        _ => Ok(BTreeMap::new()),
    }
}

/// How an element is shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Show {
    /// Always there.
    Shown,
    /// Only while the pointer is on what it belongs to (the reply, the header, the row).
    Hover,
    /// Never.
    Hidden,
}

impl Show {
    pub const ALL: [Self; 3] = [Self::Shown, Self::Hover, Self::Hidden];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Shown => "shown",
            Self::Hover => "hover",
            Self::Hidden => "hidden",
        }
    }

    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "shown" | "show" | "always" | "visible" | "on" => Some(Self::Shown),
            "hover" | "on_hover" | "on hover" | "hovered" => Some(Self::Hover),
            "hidden" | "hide" | "never" | "off" | "none" => Some(Self::Hidden),
            _ => None,
        }
    }

    /// Whether it is drawn now, `hovered` being whether the pointer is on its owner.
    pub fn visible(self, hovered: bool) -> bool {
        match self {
            Self::Shown => true,
            Self::Hover => hovered,
            Self::Hidden => false,
        }
    }
}

/// A region whose elements can be reordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Region {
    pub id: &'static str,
    /// Where it is, for people (and the model).
    pub describe: &'static str,
    /// Whether plugin views (`view:…`) are drawn here.
    pub plugin_views: bool,
}

/// An element of the interface that can be shown, hidden or moved.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Element {
    pub id: &'static str,
    /// Its name in Settings.
    pub label: &'static str,
    /// What it is, for people (and the model).
    pub describe: &'static str,
    /// The region it can be moved within, if any.
    pub region: Option<&'static str>,
    pub default: Show,
    /// Whether [`Show::Hover`] means something for it (else it acts as shown).
    pub hover: bool,
}

pub const HEADER: &str = "header";
pub const TOOLBAR: &str = "toolbar";
pub const REPLY: &str = "reply";

/// The regions that can be reordered, each listed left to right.
pub const REGIONS: &[Region] = &[
    Region { id: HEADER, describe: "the header after the chat's title, left to right", plugin_views: false },
    Region { id: TOOLBAR, describe: "the header's buttons on the right, left to right (the More menu always stays last)", plugin_views: true },
    Region { id: REPLY, describe: "the details under a reply, left to right", plugin_views: false },
];

const fn el(id: &'static str, label: &'static str, describe: &'static str, region: Option<&'static str>, default: Show, hover: bool) -> Element {
    Element { id, label, describe, region, default, hover }
}

/// Everything the layout knows, in the order Settings lists them (and each region's default order).
pub const ELEMENTS: &[Element] = &[
    // Header, after the title.
    el("header.model", "Model", "the model chip: which model this chat uses; click it to switch", Some(HEADER), Show::Shown, true),
    el("header.usage", "Context meter", "the bar of how full the chat's context is; click it for details", Some(HEADER), Show::Shown, true),
    el("header.server", "Server address", "the server's address inside the model chip, on wide windows", None, Show::Shown, false),
    el("header.usage_numbers", "Context numbers", "tokens used out of the context window, next to the context meter", None, Show::Shown, true),
    el("header.wordmark", "Wordmark", "the \"byob\" name on the left of the header, on wide windows", None, Show::Shown, false),
    el("header.workspace", "Workspace name", "the workspace's name before the chat's title", None, Show::Shown, true),
    // Header, right.
    el("toolbar.panes", "Plugin panes", "buttons that open plugins' panes beside the chat", Some(TOOLBAR), Show::Shown, true),
    el("toolbar.artifacts", "Artifacts button", "the button that shows or hides the artifact pane", Some(TOOLBAR), Show::Shown, true),
    el("toolbar.plugins", "Plugins chip", "how many plugins are on, with a badge when one has trouble", Some(TOOLBAR), Show::Shown, true),
    // Messages.
    el("message.role", "Who said it", "\"You\" and \"byob\" above each message", None, Show::Shown, false),
    el(
        "message.thinking",
        "Thinking",
        "the \"Thought\" row that opens the model's thinking; hidden, it shows only while the model is still thinking",
        None,
        Show::Shown,
        false,
    ),
    el("message.thought_size", "Thinking length", "how long the model's thinking was, next to \"Thought\" (\"1.1k chars\")", None, Show::Shown, false),
    el(
        "message.steps",
        "Tool steps",
        "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)",
        None,
        Show::Shown,
        false,
    ),
    el("message.step_files", "Files changed", "\"1 file\" (\"3 files\") on a tool's row when it changed files", None, Show::Shown, false),
    el("message.subagent_details", "Subagent details", "the model and tokens on a subagent's row", None, Show::Shown, false),
    el("message.edit", "Edit button", "\"Edit\" on your messages: change one and start the chat over from there", None, Show::Hover, true),
    el("message.undo", "Undo button", "\"Undo changes\" under a reply that changed files", None, Show::Shown, true),
    el(
        "reply.tokens",
        "Tokens",
        "tokens under each reply: how full the context was at its end, what the model wrote, and what several requests read together",
        Some(REPLY),
        Show::Shown,
        true,
    ),
    el("reply.time", "Time", "how long the reply took, under each reply", Some(REPLY), Show::Shown, true),
    el("reply.speed", "Speed", "tokens per second the model wrote, under each reply", Some(REPLY), Show::Hidden, true),
    // Artifacts and code in replies.
    el("artifact.kind", "Artifact kind", "the kind badge on an artifact's card in a reply (\"DOCUMENT\", \"APP\", \"CHART\")", None, Show::Shown, false),
    el("artifact.version", "Artifact version", "the version on an artifact's card in a reply (\"v1\") and its note", None, Show::Shown, false),
    el(
        "artifact.shown",
        "Artifact shown note",
        "\"Shown beside the chat\" on an artifact's card in a reply while it's open in the artifact pane",
        None,
        Show::Shown,
        true,
    ),
    el("code.language", "Code language", "the language (\"rust\", \"code\") at the top left of a code block", None, Show::Shown, true),
    el("code.copy", "Code copy button", "\"Copy\" at the top right of a code block", None, Show::Shown, true),
    // Elsewhere.
    el("chat.starters", "Suggestions", "the suggested prompts in an empty chat (\"Ask anything to get started, or try:\")", None, Show::Shown, false),
    el(
        "composer.attach",
        "Attach button",
        "the paperclip that attaches files, left of the message box (dropping or pasting files still works)",
        None,
        Show::Shown,
        false,
    ),
    el("composer.keys", "Composer keys", "\"Enter to send, Shift+Enter for a new line\" in the empty message box", None, Show::Shown, false),
    el("sidebar.shortcuts", "Sidebar shortcuts", "the keyboard shortcuts on New chat and the search field", None, Show::Shown, true),
];

/// Where elements that aren't in a region are, by id prefix, in the order Settings lists them.
pub const GROUPS: &[(&str, &str)] = &[
    ("header", "Header"),
    ("message", "Messages"),
    ("artifact", "Artifacts in replies"),
    ("code", "Code blocks"),
    ("chat", "Empty chat"),
    ("composer", "Message box"),
    ("sidebar", "Sidebar"),
];

/// The heading of the group element `id` is in ([`GROUPS`]).
pub fn group(id: &str) -> &'static str {
    let prefix = id.split('.').next().unwrap_or_default();
    GROUPS.iter().find(|(p, _)| *p == prefix).map_or("Other", |(_, name)| name)
}

/// The element with id `id`.
pub fn element(id: &str) -> Option<&'static Element> {
    ELEMENTS.iter().find(|e| e.id == id)
}

/// The region with id `id`.
pub fn region(id: &str) -> Option<&'static Region> {
    REGIONS.iter().find(|r| r.id == id)
}

/// The id of plugin `plugin`'s view `view` in a layout.
pub fn view_id(plugin: &str, view: &str) -> String {
    format!("view:{plugin}/{view}")
}

/// Ready-made layouts.
pub const PRESETS: &[(&str, &str)] = &[
    ("everything", "every detail shown (byob's default)"),
    ("balanced", "details of replies and the context numbers on hover; labels and shortcut hints hidden"),
    ("minimal", "only what you need: details on hover, the rest hidden"),
];

/// Most entries kept per map (ids are few; the rest is a hostile or broken file).
const MAX_ENTRIES: usize = 256;
const MAX_ID: usize = 160;

/// Most sections the chat list keeps, items in one, and characters in a section's name.
const MAX_SECTIONS: usize = 64;
/// Pinned projects (and, apart, pinned artifacts) the list keeps.
const MAX_PINS: usize = 64;
/// Spaces, and what one Space can hold.
const MAX_SPACES: usize = 16;
const MAX_SPACE_ITEMS: usize = 5000;
const MAX_SECTION_ITEMS: usize = 512;
const MAX_SECTION_NAME: usize = 80;

/// A section of the chat list the person made: a name and what they moved into it
/// (`chat:<id>`, `ws:<id>`). Only an arrangement: chats and projects stay what they are.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ListSection {
    #[serde(deserialize_with = "lenient")]
    pub id: String,
    #[serde(deserialize_with = "lenient")]
    pub name: String,
    #[serde(deserialize_with = "lenient_list")]
    pub items: Vec<String>,
}

/// How the chat list groups what isn't in a section.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ListGroup {
    /// Chats without a project, then each project with its chats.
    #[default]
    Project,
    /// Every chat by when it was last active.
    Date,
    /// One list.
    None,
}

/// The order within the chat list's groups.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ListSort {
    #[default]
    Updated,
    Name,
}

/// The chat list's arrangement: the person's sections, the grouping and the order. Part of
/// the layout so it is the same in every window and browser tab.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ChatList {
    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
    pub sections: Vec<ListSection>,
    #[serde(deserialize_with = "lenient")]
    pub group: ListGroup,
    #[serde(deserialize_with = "lenient")]
    pub sort: ListSort,
    /// Projects pinned to the top of the list, by id, in order.
    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
    pub pinned_projects: Vec<String>,
    /// Artifacts pinned to the top of the list, in order.
    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
    pub pinned_artifacts: Vec<ListPin>,
    /// Spaces (Work, Personal, a client): each shows only its own projects and chats. With
    /// fewer than two there are none to switch between. What no Space claims is the first's.
    #[serde(deserialize_with = "lenient_list", skip_serializing_if = "Vec::is_empty")]
    pub spaces: Vec<ListSpace>,
}

/// A Space: its name, its color (`#rrggbb`), and the projects and chats it holds
/// (`ws:<id>`, `chat:<id>`).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ListSpace {
    #[serde(deserialize_with = "lenient")]
    pub id: String,
    #[serde(deserialize_with = "lenient")]
    pub name: String,
    #[serde(deserialize_with = "lenient")]
    pub color: String,
    #[serde(deserialize_with = "lenient_list")]
    pub items: Vec<String>,
}

/// An artifact pinned to the chat list: the chat it's in, its id, and its title to show.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct ListPin {
    #[serde(deserialize_with = "lenient")]
    pub chat: String,
    #[serde(deserialize_with = "lenient")]
    pub id: String,
    #[serde(deserialize_with = "lenient")]
    pub title: String,
}

impl ChatList {
    pub fn is_default(&self) -> bool {
        *self == Self::default()
    }

    /// Within the limits: few enough sections and items, names and ids that are text.
    #[must_use]
    pub fn sanitized(mut self) -> Self {
        let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
        self.sections.retain(|s| ok(&s.id));
        self.sections.truncate(MAX_SECTIONS);
        for s in &mut self.sections {
            s.name = s.name.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME).collect::<String>().trim().to_owned();
            if s.name.is_empty() {
                "Section".clone_into(&mut s.name);
            }
            s.items.retain(&ok);
            s.items.dedup();
            s.items.truncate(MAX_SECTION_ITEMS);
        }
        self.pinned_projects.retain(&ok);
        self.pinned_projects.dedup();
        self.pinned_projects.truncate(MAX_PINS);
        self.pinned_artifacts.retain(|p| ok(&p.chat) && ok(&p.id));
        self.pinned_artifacts.dedup_by(|a, b| a.id == b.id);
        self.pinned_artifacts.truncate(MAX_PINS);
        self.spaces.retain(|sp| ok(&sp.id));
        self.spaces.truncate(MAX_SPACES);
        for sp in &mut self.spaces {
            sp.name = sp.name.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME).collect::<String>().trim().to_owned();
            if sp.name.is_empty() {
                "Space".clone_into(&mut sp.name);
            }
            let hex = sp.color.strip_prefix('#').unwrap_or("");
            if hex.len() != 6 || !hex.chars().all(|c| c.is_ascii_hexdigit()) {
                sp.color.clear();
            }
            sp.items.retain(&ok);
            sp.items.dedup();
            sp.items.truncate(MAX_SPACE_ITEMS);
        }
        for p in &mut self.pinned_artifacts {
            p.title = p.title.chars().filter(|c| !c.is_control()).take(MAX_SECTION_NAME * 2).collect::<String>().trim().to_owned();
        }
        self
    }
}

/// What the interface shows: the modes and orders that differ from the defaults.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Layout {
    /// Element id → how it is shown.
    #[serde(deserialize_with = "lenient_map", skip_serializing_if = "BTreeMap::is_empty")]
    pub show: BTreeMap<String, Show>,
    /// Region id → element ids in the order wanted. Ids a region doesn't have are skipped;
    /// those it has but the list doesn't name follow, in their default order.
    #[serde(deserialize_with = "lenient_map", skip_serializing_if = "BTreeMap::is_empty")]
    pub order: BTreeMap<String, Vec<String>>,
    /// The chat list's sections and view.
    #[serde(deserialize_with = "lenient", skip_serializing_if = "ChatList::is_default")]
    pub chat_list: ChatList,
}

impl Layout {
    pub fn is_default(&self) -> bool {
        self.show.is_empty() && self.order.is_empty() && self.chat_list.is_default()
    }

    /// How element (or plugin view) `id` is shown. Unknown ids are shown.
    pub fn show(&self, id: &str) -> Show {
        let mode = self.show.get(id).copied().or_else(|| element(id).map(|e| e.default)).unwrap_or(Show::Shown);
        match element(id) {
            Some(e) if !e.hover && mode == Show::Hover => Show::Shown,
            _ => mode,
        }
    }

    /// Whether `id` is drawn now (`hovered`: the pointer is on what it belongs to).
    pub fn visible(&self, id: &str, hovered: bool) -> bool {
        self.show(id).visible(hovered)
    }

    /// Set how `id` is shown; back to the default stores nothing.
    pub fn set_show(&mut self, id: &str, mode: Show) {
        if element(id).is_some_and(|e| e.default == mode) {
            self.show.remove(id);
        } else {
            self.show.insert(id.to_owned(), mode);
        }
    }

    /// Region `region`'s elements in order: byob's own (in [`ELEMENTS`] order) and then
    /// `extra` (plugin views drawn there, as found), arranged by the stored order. Hidden
    /// ones are included; ask [`Self::show`].
    pub fn arrange(&self, region: &str, extra: &[String]) -> Vec<String> {
        let mut present: Vec<String> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id.to_owned()).collect();
        for id in extra {
            if !present.contains(id) {
                present.push(id.clone());
            }
        }
        let Some(wanted) = self.order.get(region) else { return present };
        let mut out: Vec<String> = Vec::with_capacity(present.len());
        for id in wanted {
            if present.contains(id) && !out.contains(id) {
                out.push(id.clone());
            }
        }
        for id in present {
            if !out.contains(&id) {
                out.push(id);
            }
        }
        out
    }

    /// Put region `region` in this order (see [`Self::order`]); the default order stores nothing.
    pub fn set_order(&mut self, region: &str, ids: Vec<String>) {
        let default: Vec<&str> = ELEMENTS.iter().filter(|e| e.region == Some(region)).map(|e| e.id).collect();
        let mut ids: Vec<String> = ids.into_iter().filter(|id| !id.is_empty()).collect();
        ids.dedup();
        if ids.is_empty() || ids.iter().map(String::as_str).eq(default.iter().copied()) {
            self.order.remove(region);
        } else {
            self.order.insert(region.to_owned(), ids);
        }
    }

    /// Move `id` one place earlier (`dir` < 0) or later within region `region`, among `extra`.
    pub fn nudge(&mut self, region: &str, extra: &[String], id: &str, dir: i32) {
        let mut ids = self.arrange(region, extra);
        let Some(i) = ids.iter().position(|x| x == id) else { return };
        let j = if dir < 0 { i.checked_sub(1) } else { Some(i + 1).filter(|j| *j < ids.len()) };
        if let Some(j) = j {
            ids.swap(i, j);
            self.set_order(region, ids);
        }
    }

    /// A ready-made layout by name ([`PRESETS`]).
    pub fn preset(name: &str) -> Option<Self> {
        let mut l = Self::default();
        let hover = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hover));
        let hide = |l: &mut Self, ids: &[&str]| ids.iter().for_each(|id| l.set_show(id, Show::Hidden));
        match name.trim().to_ascii_lowercase().as_str() {
            "everything" | "default" | "full" => {}
            "balanced" => {
                hover(&mut l, &["reply.tokens", "reply.time", "header.usage_numbers", "sidebar.shortcuts"]);
                hide(&mut l, &["message.role", "message.thought_size", "composer.keys"]);
            }
            "minimal" => {
                hover(&mut l, &["reply.tokens", "reply.time", "sidebar.shortcuts", "toolbar.plugins", "artifact.shown", "message.undo", "code.copy"]);
                hide(
                    &mut l,
                    &[
                        "message.role",
                        "message.thought_size",
                        "message.step_files",
                        "message.subagent_details",
                        "artifact.version",
                        "code.language",
                        "composer.keys",
                        "header.usage_numbers",
                        "header.server",
                        "header.wordmark",
                    ],
                );
            }
            _ => return None,
        }
        Some(l)
    }

    /// Drop what a broken or hostile file could hold: too many entries, absurd ids, empty orders.
    #[must_use]
    pub fn sanitized(mut self) -> Self {
        let ok = |id: &String| !id.is_empty() && id.len() <= MAX_ID && !id.chars().any(char::is_control);
        self.show.retain(|id, _| ok(id));
        while self.show.len() > MAX_ENTRIES {
            self.show.pop_last();
        }
        self.order.retain(|region, ids| {
            ids.retain(&ok);
            ids.truncate(MAX_ENTRIES);
            ok(region) && !ids.is_empty()
        });
        while self.order.len() > MAX_ENTRIES {
            self.order.pop_last();
        }
        self.chat_list = self.chat_list.sanitized();
        self
    }
}

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

    /// Regression: one value this build can't read (a newer build's show mode or grouping, a
    /// hand edit) made the whole layout unreadable, and settings.json falls back to the
    /// default layout: every Space, section and pin was gone, and the next save made it so.
    #[test]
    fn one_unreadable_value_loses_only_itself() {
        let json = r#"{
            "show": {"reply.tokens": "hidden", "header.usage": "sometimes"},
            "order": {"composer": ["a", 5]},
            "chat_list": {"group": "by_mood", "sort": "name", "pinned_projects": "w1",
                "sections": [{"id": "s", "name": "Later", "items": ["chat:1"]}],
                "spaces": [{"id": "space-1", "name": "Work", "items": ["ws:w1"]}, {"id": "space-2", "name": "Home", "items": [7]}]}
        }"#;
        let l: Layout = serde_json::from_str(json).unwrap();
        assert_eq!(l.show.get("reply.tokens"), Some(&Show::Hidden));
        assert!(!l.show.contains_key("header.usage"));
        assert_eq!((l.chat_list.group, l.chat_list.sort), (ListGroup::Project, ListSort::Name));
        assert!(l.chat_list.pinned_projects.is_empty());
        assert_eq!(l.chat_list.sections.len(), 1);
        let spaces: Vec<&str> = l.chat_list.spaces.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(spaces, ["Work", "Home"]);
        assert_eq!(l.chat_list.spaces[0].items, ["ws:w1"]);
    }

    #[test]
    fn the_chat_list_rides_in_the_layout_and_stays_within_limits() {
        // Old layouts read as before; a default chat list writes nothing.
        let l: Layout = serde_json::from_str(r#"{"show":{"reply.speed":"shown"}}"#).unwrap();
        assert!(l.chat_list.is_default());
        assert!(!serde_json::to_string(&l).unwrap().contains("chat_list"));
        let mut l = Layout::default();
        l.chat_list.group = ListGroup::Date;
        l.chat_list.sections.push(ListSection {
            id: "s1".into(),
            name: "  Design\u{7} work  ".into(),
            items: vec!["chat:a".into(), "chat:a".into(), String::new()],
        });
        let back: Layout = serde_json::from_str(&serde_json::to_string(&l).unwrap()).unwrap();
        let clean = back.sanitized();
        assert_eq!(clean.chat_list.group, ListGroup::Date);
        assert_eq!(clean.chat_list.sections[0].name, "Design work");
        assert_eq!(clean.chat_list.sections[0].items, ["chat:a"]);
        assert!(!clean.is_default());
        let many = ChatList { sections: (0..100).map(|i| ListSection { id: format!("s{i}"), ..ListSection::default() }).collect(), ..ChatList::default() };
        let many = many.sanitized();
        assert_eq!(many.sections.len(), MAX_SECTIONS);
        assert_eq!(many.sections[0].name, "Section");
    }

    #[test]
    fn defaults_show_everything_but_speed_and_store_nothing() {
        let l = Layout::default();
        for e in ELEMENTS {
            assert_eq!(l.show(e.id), e.default, "{}", e.id);
        }
        assert_eq!(l.show("reply.speed"), Show::Hidden);
        assert_eq!(l.show("view:todo/count"), Show::Shown);
        let mut l = Layout::default();
        l.set_show("reply.tokens", Show::Hover);
        l.set_show("reply.tokens", Show::Shown);
        assert!(l.is_default(), "back to the default stores nothing");
        assert_eq!(serde_json::to_string(&l).unwrap(), "{}");
    }

    #[test]
    fn hover_falls_back_to_shown_where_it_means_nothing() {
        let mut l = Layout::default();
        l.set_show("message.role", Show::Hover);
        assert_eq!(l.show("message.role"), Show::Shown);
        l.set_show("reply.time", Show::Hover);
        assert!(!l.visible("reply.time", false));
        assert!(l.visible("reply.time", true));
    }

    #[test]
    fn arranging_puts_named_ids_first_and_keeps_the_rest_in_their_order() {
        let views = vec!["view:todo/count".to_owned()];
        let mut l = Layout::default();
        assert_eq!(l.arrange(TOOLBAR, &views), ["toolbar.panes", "toolbar.artifacts", "toolbar.plugins", "view:todo/count"]);
        l.set_order(TOOLBAR, vec!["view:todo/count".into(), "nope".into(), "toolbar.plugins".into()]);
        assert_eq!(l.arrange(TOOLBAR, &views), ["view:todo/count", "toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
        // A plugin view that isn't loaded is skipped (and kept for when it is).
        assert_eq!(l.arrange(TOOLBAR, &[]), ["toolbar.plugins", "toolbar.panes", "toolbar.artifacts"]);
        assert!(l.order[TOOLBAR].contains(&"view:todo/count".to_owned()));
    }

    #[test]
    fn nudging_moves_one_place_and_the_default_order_stores_nothing() {
        let mut l = Layout::default();
        l.nudge(REPLY, &[], "reply.time", -1);
        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"]);
        l.nudge(REPLY, &[], "reply.time", -1);
        assert_eq!(l.arrange(REPLY, &[]), ["reply.time", "reply.tokens", "reply.speed"], "already first");
        l.nudge(REPLY, &[], "reply.time", 1);
        assert!(l.is_default());
    }

    #[test]
    fn presets_are_named_and_known() {
        for (name, _) in PRESETS {
            assert!(Layout::preset(name).is_some(), "{name}");
        }
        assert!(Layout::preset("everything").unwrap().is_default());
        assert!(Layout::preset("sparkly").is_none());
        let min = Layout::preset("minimal").unwrap();
        assert!(!min.visible("reply.tokens", false) && min.visible("reply.tokens", true));
        for id in min.show.keys() {
            assert!(element(id).is_some(), "{id}");
        }
    }

    #[test]
    fn modes_parse_loosely_and_sanitizing_drops_junk() {
        assert_eq!(Show::parse(" Hide "), Some(Show::Hidden));
        assert_eq!(Show::parse("on hover"), Some(Show::Hover));
        assert_eq!(Show::parse("maybe"), None);
        let l: Layout = serde_json::from_str(r#"{"show": {"": "hidden", "a\u0007": "hidden", "reply.time": "hover"}, "order": {"reply": []}}"#).unwrap();
        let l = l.sanitized();
        assert_eq!(l.show.len(), 1);
        assert!(l.order.is_empty());
    }

    #[test]
    fn every_element_is_unique_and_its_region_exists() {
        for (i, e) in ELEMENTS.iter().enumerate() {
            assert!(ELEMENTS[..i].iter().all(|o| o.id != e.id), "{}", e.id);
            assert!(e.region.is_none_or(|r| region(r).is_some()), "{}", e.id);
        }
    }
}