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;
21pub const MAX_LINKED_FOLDERS: usize = 16;
23pub const MAX_GOAL_CHARS: usize = 280;
25
26#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct WorkspaceSummary {
31 pub id: String,
32 pub name: String,
33 pub folder: String,
35 #[serde(default, skip_serializing_if = "Vec::is_empty")]
37 pub folders: Vec<String>,
38 #[serde(default, skip_serializing_if = "String::is_empty")]
40 pub goal: String,
41 #[serde(default)]
43 pub chats: u64,
44 #[serde(default)]
46 pub updated_at: i64,
47 #[serde(default)]
49 pub env: EnvKind,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54#[serde(tag = "kind", rename_all = "snake_case")]
55pub enum ConfigScope {
56 Global,
58 Workspace {
59 id: String,
60 },
61 Chat,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct ConfigView {
68 pub scope: ConfigScope,
69 pub own: Layer,
71 pub effective: Effective,
73 #[serde(default)]
75 pub has_key: bool,
76 #[serde(default)]
78 pub title: String,
79 #[serde(default)]
81 pub workspace: Option<WorkspaceSummary>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86#[serde(tag = "kind", rename_all = "snake_case")]
87pub enum NewFolder {
88 Existing { path: String },
90 Create,
93}
94
95#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97pub struct FolderList {
98 pub path: String,
100 #[serde(default)]
101 pub parent: Option<String>,
102 #[serde(default)]
104 pub dirs: Vec<String>,
105 #[serde(default)]
107 pub truncated: bool,
108 #[serde(default)]
110 pub error: Option<String>,
111}
112
113#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
116pub struct ChatEndpoint {
117 pub base_url: String,
118 pub model: String,
119 pub from: Level,
121 pub has_api_key: bool,
122 #[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 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 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}