1use serde::{Deserialize, Serialize};
8
9pub use byob_types::config::{Approvals, Effective, EnvKind, Field, Layer, Level, Sourced, ToolMode};
10
11use crate::{ClientMsg, Link};
12
13pub const MAX_ID_CHARS: usize = 128;
15pub const MAX_NAME_CHARS: usize = 200;
17pub const MAX_PATH_CHARS: usize = 4096;
19pub const MAX_LISTED_FOLDERS: usize = 500;
21
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24pub struct WorkspaceSummary {
25 pub id: String,
26 pub name: String,
27 pub folder: String,
29 #[serde(default)]
31 pub chats: u64,
32 #[serde(default)]
34 pub updated_at: i64,
35 #[serde(default)]
37 pub env: EnvKind,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[serde(tag = "kind", rename_all = "snake_case")]
43pub enum ConfigScope {
44 Global,
46 Workspace {
47 id: String,
48 },
49 Chat,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct ConfigView {
56 pub scope: ConfigScope,
57 pub own: Layer,
59 pub effective: Effective,
61 #[serde(default)]
63 pub has_key: bool,
64 #[serde(default)]
66 pub title: String,
67 #[serde(default)]
69 pub workspace: Option<WorkspaceSummary>,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(tag = "kind", rename_all = "snake_case")]
75pub enum NewFolder {
76 Existing { path: String },
78 Create,
81}
82
83#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
85pub struct FolderList {
86 pub path: String,
88 #[serde(default)]
89 pub parent: Option<String>,
90 #[serde(default)]
92 pub dirs: Vec<String>,
93 #[serde(default)]
95 pub truncated: bool,
96 #[serde(default)]
98 pub error: Option<String>,
99}
100
101#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
104pub struct ChatEndpoint {
105 pub base_url: String,
106 pub model: String,
107 pub from: Level,
109 pub has_api_key: bool,
110 #[serde(default)]
111 pub link: Link,
112 #[serde(default)]
113 pub info: Option<crate::EndpointInfo>,
114}
115
116fn long(s: &str, max: usize) -> bool {
117 s.chars().count() > max
118}
119
120impl ClientMsg {
121 pub fn check_sizes(&self) -> Result<(), String> {
124 let id = |s: &str| if long(s, MAX_ID_CHARS) || s.is_empty() { Err("bad id".to_owned()) } else { Ok(()) };
125 let name = |s: &str| if long(s, MAX_NAME_CHARS) { Err("the name is too long".to_owned()) } else { Ok(()) };
126 let path = |s: &str| if long(s, MAX_PATH_CHARS) { Err("the path is too long".to_owned()) } else { Ok(()) };
127 match self {
128 Self::NewChat { workspace: Some(w) } => id(w),
129 Self::CreateWorkspace { name: n, folder, .. } => {
130 name(n)?;
131 match folder {
132 NewFolder::Existing { path: p } => path(p),
133 NewFolder::Create => Ok(()),
134 }
135 }
136 Self::RenameWorkspace { id: i, name: n } => id(i).and_then(|()| name(n)),
137 Self::RemoveWorkspace { id: i, .. } => id(i),
138 Self::GetConfig { scope: ConfigScope::Workspace { id: i } } | Self::SetConfig { scope: ConfigScope::Workspace { id: i }, .. } => id(i),
139 Self::ListFolders { path: Some(p) } => path(p),
140 Self::WorkspaceEnv { workspace: Some(w), .. } => id(w),
141 Self::SetPluginEnabled { .. } | Self::SetPluginSetting { .. } | Self::KeepPlugin { .. } | Self::RemovePlugin { .. } | Self::TrustPlugins { .. } => {
142 crate::plugins::check_sizes(self)
143 }
144 _ => crate::queue::check_sizes(self),
145 }
146 }
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::ServerMsg;
153
154 #[test]
155 fn workspace_messages_round_trip() {
156 let layer = Layer { env: Some(EnvKind::Container), image: Some("python:3-slim".into()), ..Layer::default() };
157 let msgs = vec![
158 ClientMsg::NewChat { workspace: Some("w1".into()) },
159 ClientMsg::CreateWorkspace { name: "Data".into(), folder: NewFolder::Create, config: layer.clone() },
160 ClientMsg::CreateWorkspace { name: "Repo".into(), folder: NewFolder::Existing { path: "/home/me/repo".into() }, config: Layer::default() },
161 ClientMsg::RenameWorkspace { id: "w1".into(), name: "New".into() },
162 ClientMsg::RemoveWorkspace { id: "w1".into(), clean: true },
163 ClientMsg::GetConfig { scope: ConfigScope::Chat },
164 ClientMsg::SetConfig { scope: ConfigScope::Workspace { id: "w1".into() }, layer: layer.clone(), api_key: None },
165 ClientMsg::ListFolders { path: None },
166 ClientMsg::CheckContainers,
167 ClientMsg::WorkspaceEnv { action: None, workspace: Some("w1".into()) },
168 ];
169 for m in msgs {
170 assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
171 assert!(m.check_sizes().is_ok());
172 }
173 assert_eq!(ClientMsg::from_json(r#"{"type":"new_chat"}"#).unwrap(), ClientMsg::NewChat { workspace: None });
175 assert_eq!(ClientMsg::from_json(r#"{"type":"workspace_env"}"#).unwrap(), ClientMsg::WorkspaceEnv { action: None, workspace: None });
176 let ws = WorkspaceSummary { id: "w1".into(), name: "Data".into(), folder: "/d".into(), chats: 2, updated_at: 5, env: EnvKind::Nix };
177 let effective = byob_types::config::resolve(Default::default(), Default::default(), Default::default());
178 let view = ConfigView { scope: ConfigScope::Global, own: layer, effective, has_key: false, title: "Defaults".into(), workspace: Some(ws.clone()) };
179 let msgs = vec![
180 ServerMsg::Workspaces { items: vec![ws], current: Some("w1".into()), root: "/home/me/byob-workspaces".into(), support: Default::default() },
181 ServerMsg::Config(Box::new(view)),
182 ServerMsg::Folders(FolderList { path: "/".into(), parent: None, dirs: vec!["home".into()], truncated: false, error: None }),
183 ServerMsg::ContainersChecked { ok: false, message: "Docker isn't running".into() },
184 ServerMsg::WorkspaceCreated { id: None, error: Some("no".into()) },
185 ServerMsg::ChatOpened { chat: None, workspace: Some("w1".into()) },
186 ];
187 for m in msgs {
188 assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
189 }
190 assert_eq!(ServerMsg::from_json(r#"{"type":"chat_opened","chat":null}"#).unwrap(), ServerMsg::ChatOpened { chat: None, workspace: None });
191 }
192
193 #[test]
194 fn oversized_fields_are_refused() {
195 let huge = "x".repeat(MAX_PATH_CHARS + 1);
196 for m in [
197 ClientMsg::CreateWorkspace { name: "n".into(), folder: NewFolder::Existing { path: huge.clone() }, config: Layer::default() },
198 ClientMsg::CreateWorkspace { name: huge.clone(), folder: NewFolder::Create, config: Layer::default() },
199 ClientMsg::RenameWorkspace { id: huge.clone(), name: "n".into() },
200 ClientMsg::RemoveWorkspace { id: String::new(), clean: false },
201 ClientMsg::ListFolders { path: Some(huge.clone()) },
202 ClientMsg::NewChat { workspace: Some(huge.clone()) },
203 ClientMsg::GetConfig { scope: ConfigScope::Workspace { id: huge.clone() } },
204 ] {
205 assert!(m.check_sizes().is_err(), "{m:?}");
206 }
207 }
208}