Skip to main content

byob_protocol/
workspace.rs

1//! Workspaces as clients see them, layered settings (global → workspace → chat), and the
2//! engine's folder browser for picking a workspace folder from a browser.
3//!
4//! The settings types and their resolver live in [`byob_types::config`], so the engine and
5//! the UI resolve the same way.
6
7use serde::{Deserialize, Serialize};
8
9pub use byob_types::config::{Approvals, Effective, EnvKind, Field, Layer, Level, Sourced, ToolMode};
10
11use crate::{ClientMsg, Link};
12
13/// Longest id (chat, workspace) a client may send.
14pub const MAX_ID_CHARS: usize = 128;
15/// Longest workspace name a client may send (the engine trims it to 80 characters).
16pub const MAX_NAME_CHARS: usize = 200;
17/// Longest folder path a client may send.
18pub const MAX_PATH_CHARS: usize = 4096;
19/// Most folders listed by one [`ServerMsg::Folders`](crate::ServerMsg::Folders).
20pub const MAX_LISTED_FOLDERS: usize = 500;
21
22/// A workspace in the chat list.
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct WorkspaceSummary {
25    pub id: String,
26    pub name: String,
27    /// Its folder on the engine's machine.
28    pub folder: String,
29    /// How many chats it has.
30    #[serde(default)]
31    pub chats: u64,
32    /// Latest activity of its chats, else when it was created (ms since the epoch).
33    #[serde(default)]
34    pub updated_at: i64,
35    /// Its environment setting, for a small marker in the list.
36    #[serde(default)]
37    pub env: EnvKind,
38}
39
40/// Which level's settings a [`ClientMsg::GetConfig`] / [`ClientMsg::SetConfig`] means.
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(tag = "kind", rename_all = "snake_case")]
43pub enum ConfigScope {
44    /// `settings.json` (the endpoint itself changes with [`ClientMsg::SetInference`]).
45    Global,
46    Workspace {
47        id: String,
48    },
49    /// The chat this client looks at, or the new chat it is about to start.
50    Chat,
51}
52
53/// One level's settings, what applies there, and where each value comes from.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct ConfigView {
56    pub scope: ConfigScope,
57    /// What this level sets itself.
58    pub own: Layer,
59    /// What applies at this level (to the chat, or to new chats of the workspace).
60    pub effective: Effective,
61    /// This level stores its own API key (the key itself never leaves the engine).
62    #[serde(default)]
63    pub has_key: bool,
64    /// For the heading: the workspace's or chat's name.
65    #[serde(default)]
66    pub title: String,
67    /// The workspace this level belongs to (none for global).
68    #[serde(default)]
69    pub workspace: Option<WorkspaceSummary>,
70}
71
72/// Where a new workspace's folder comes from.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(tag = "kind", rename_all = "snake_case")]
75pub enum NewFolder {
76    /// A folder that exists on the engine's machine.
77    Existing { path: String },
78    /// A fresh folder named after the workspace, in the workspaces folder (settings.json
79    /// `workspaces_root`, default `~/byob-workspaces`).
80    Create,
81}
82
83/// A folder's subfolders on the engine's machine (answer to [`ClientMsg::ListFolders`]).
84#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
85pub struct FolderList {
86    /// The folder listed (absolute, canonical).
87    pub path: String,
88    #[serde(default)]
89    pub parent: Option<String>,
90    /// Names of its subfolders (hidden ones left out), sorted, at most [`MAX_LISTED_FOLDERS`].
91    #[serde(default)]
92    pub dirs: Vec<String>,
93    /// More subfolders than listed.
94    #[serde(default)]
95    pub truncated: bool,
96    /// Why it couldn't be listed (`path` is then what was asked for).
97    #[serde(default)]
98    pub error: Option<String>,
99}
100
101/// The endpoint of the chat in view, when its workspace or the chat itself picked another
102/// one than the global settings.
103#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
104pub struct ChatEndpoint {
105    pub base_url: String,
106    pub model: String,
107    /// Which level chose it.
108    pub from: Level,
109    pub has_api_key: bool,
110    /// The model profile it is (13.9+), if it is one.
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub profile: Option<String>,
113    #[serde(default)]
114    pub link: Link,
115    #[serde(default)]
116    pub info: Option<crate::EndpointInfo>,
117}
118
119fn long(s: &str, max: usize) -> bool {
120    s.chars().count() > max
121}
122
123impl ClientMsg {
124    /// Cheap checks of an untrusted message's sizes (the engine checks meaning: unknown
125    /// ids, folders that don't exist, settings that don't belong at a level).
126    pub fn check_sizes(&self) -> Result<(), String> {
127        let id = |s: &str| if long(s, MAX_ID_CHARS) || s.is_empty() { Err("bad id".to_owned()) } else { Ok(()) };
128        let name = |s: &str| if long(s, MAX_NAME_CHARS) { Err("the name is too long".to_owned()) } else { Ok(()) };
129        let path = |s: &str| if long(s, MAX_PATH_CHARS) { Err("the path is too long".to_owned()) } else { Ok(()) };
130        match self {
131            Self::NewChat { workspace: Some(w) } => id(w),
132            Self::CreateWorkspace { name: n, folder, .. } => {
133                name(n)?;
134                match folder {
135                    NewFolder::Existing { path: p } => path(p),
136                    NewFolder::Create => Ok(()),
137                }
138            }
139            Self::RenameWorkspace { id: i, name: n } => id(i).and_then(|()| name(n)),
140            Self::RemoveWorkspace { id: i, .. } => id(i),
141            Self::GetConfig { scope: ConfigScope::Workspace { id: i } } | Self::SetConfig { scope: ConfigScope::Workspace { id: i }, .. } => id(i),
142            Self::ListFolders { path: Some(p) } => path(p),
143            Self::WorkspaceEnv { workspace: Some(w), .. } => id(w),
144            Self::SetPluginEnabled { .. } | Self::SetPluginSetting { .. } | Self::KeepPlugin { .. } | Self::RemovePlugin { .. } | Self::TrustPlugins { .. } => {
145                crate::plugins::check_sizes(self)
146            }
147            Self::Hello { client, caps, .. } => {
148                name(client)?;
149                crate::version::check_caps(caps)
150            }
151            Self::Plugin { plugin, msg } => crate::version::check_plugin_msg(plugin, msg),
152            Self::OpenView { .. } | Self::CloseView { .. } | Self::ViewEvent { .. } => crate::sites::check_sizes(self),
153            Self::WebCall { owner, method, params, .. } => crate::web::check_call(owner, method, params),
154            Self::CreateProfile { .. }
155            | Self::UpdateProfile { .. }
156            | Self::DeleteProfile { .. }
157            | Self::DuplicateProfile { .. }
158            | Self::TestProfile { .. }
159            | Self::SetRole { .. }
160            | Self::SetLevelProfile { .. } => crate::profiles::check_sizes(self),
161            Self::AnswerQuestion { text, .. } => {
162                if long(text, crate::MAX_ANSWER_CHARS) {
163                    Err("the answer is too long".to_owned())
164                } else {
165                    Ok(())
166                }
167            }
168            _ => crate::queue::check_sizes(self),
169        }
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176    use crate::ServerMsg;
177
178    #[test]
179    fn workspace_messages_round_trip() {
180        let layer = Layer { env: Some(EnvKind::Container), image: Some("python:3-slim".into()), ..Layer::default() };
181        let msgs = vec![
182            ClientMsg::NewChat { workspace: Some("w1".into()) },
183            ClientMsg::CreateWorkspace { name: "Data".into(), folder: NewFolder::Create, config: layer.clone() },
184            ClientMsg::CreateWorkspace { name: "Repo".into(), folder: NewFolder::Existing { path: "/home/me/repo".into() }, config: Layer::default() },
185            ClientMsg::RenameWorkspace { id: "w1".into(), name: "New".into() },
186            ClientMsg::RemoveWorkspace { id: "w1".into(), clean: true },
187            ClientMsg::GetConfig { scope: ConfigScope::Chat },
188            ClientMsg::SetConfig { scope: ConfigScope::Workspace { id: "w1".into() }, layer: layer.clone(), api_key: None },
189            ClientMsg::ListFolders { path: None },
190            ClientMsg::CheckContainers,
191            ClientMsg::WorkspaceEnv { action: None, workspace: Some("w1".into()) },
192        ];
193        for m in msgs {
194            assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
195            assert!(m.check_sizes().is_ok());
196        }
197        // Older clients' messages still parse.
198        assert_eq!(ClientMsg::from_json(r#"{"type":"new_chat"}"#).unwrap(), ClientMsg::NewChat { workspace: None });
199        assert_eq!(ClientMsg::from_json(r#"{"type":"workspace_env"}"#).unwrap(), ClientMsg::WorkspaceEnv { action: None, workspace: None });
200        let ws = WorkspaceSummary { id: "w1".into(), name: "Data".into(), folder: "/d".into(), chats: 2, updated_at: 5, env: EnvKind::Nix };
201        let effective = byob_types::config::resolve(Default::default(), Default::default(), Default::default());
202        let view = ConfigView { scope: ConfigScope::Global, own: layer, effective, has_key: false, title: "Defaults".into(), workspace: Some(ws.clone()) };
203        let msgs = vec![
204            ServerMsg::Workspaces { items: vec![ws], current: Some("w1".into()), root: "/home/me/byob-workspaces".into(), support: Default::default() },
205            ServerMsg::Config(Box::new(view)),
206            ServerMsg::Folders(FolderList { path: "/".into(), parent: None, dirs: vec!["home".into()], truncated: false, error: None }),
207            ServerMsg::ContainersChecked { ok: false, message: "Docker isn't running".into() },
208            ServerMsg::WorkspaceCreated { id: None, error: Some("no".into()) },
209            ServerMsg::ChatOpened { chat: None, workspace: Some("w1".into()) },
210        ];
211        for m in msgs {
212            assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
213        }
214        assert_eq!(ServerMsg::from_json(r#"{"type":"chat_opened","chat":null}"#).unwrap(), ServerMsg::ChatOpened { chat: None, workspace: None });
215    }
216
217    #[test]
218    fn oversized_fields_are_refused() {
219        let huge = "x".repeat(MAX_PATH_CHARS + 1);
220        for m in [
221            ClientMsg::CreateWorkspace { name: "n".into(), folder: NewFolder::Existing { path: huge.clone() }, config: Layer::default() },
222            ClientMsg::CreateWorkspace { name: huge.clone(), folder: NewFolder::Create, config: Layer::default() },
223            ClientMsg::RenameWorkspace { id: huge.clone(), name: "n".into() },
224            ClientMsg::RemoveWorkspace { id: String::new(), clean: false },
225            ClientMsg::ListFolders { path: Some(huge.clone()) },
226            ClientMsg::NewChat { workspace: Some(huge.clone()) },
227            ClientMsg::GetConfig { scope: ConfigScope::Workspace { id: huge.clone() } },
228        ] {
229            assert!(m.check_sizes().is_err(), "{m:?}");
230        }
231    }
232}