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