use serde::{Deserialize, Serialize};
pub use byob_types::config::{Approvals, Effective, EnvKind, Field, Layer, Level, Sourced, ToolMode};
use crate::{ClientMsg, Link};
pub const MAX_ID_CHARS: usize = 128;
pub const MAX_NAME_CHARS: usize = 200;
pub const MAX_PATH_CHARS: usize = 4096;
pub const MAX_LISTED_FOLDERS: usize = 500;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceSummary {
pub id: String,
pub name: String,
pub folder: String,
#[serde(default)]
pub chats: u64,
#[serde(default)]
pub updated_at: i64,
#[serde(default)]
pub env: EnvKind,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ConfigScope {
Global,
Workspace {
id: String,
},
Chat,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigView {
pub scope: ConfigScope,
pub own: Layer,
pub effective: Effective,
#[serde(default)]
pub has_key: bool,
#[serde(default)]
pub title: String,
#[serde(default)]
pub workspace: Option<WorkspaceSummary>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum NewFolder {
Existing { path: String },
Create,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderList {
pub path: String,
#[serde(default)]
pub parent: Option<String>,
#[serde(default)]
pub dirs: Vec<String>,
#[serde(default)]
pub truncated: bool,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct ChatEndpoint {
pub base_url: String,
pub model: String,
pub from: Level,
pub has_api_key: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub profile: Option<String>,
#[serde(default)]
pub link: Link,
#[serde(default)]
pub info: Option<crate::EndpointInfo>,
}
fn long(s: &str, max: usize) -> bool {
s.chars().count() > max
}
impl ClientMsg {
pub fn check_sizes(&self) -> Result<(), String> {
let id = |s: &str| if long(s, MAX_ID_CHARS) || s.is_empty() { Err("bad id".to_owned()) } else { Ok(()) };
let name = |s: &str| if long(s, MAX_NAME_CHARS) { Err("the name is too long".to_owned()) } else { Ok(()) };
let path = |s: &str| if long(s, MAX_PATH_CHARS) { Err("the path is too long".to_owned()) } else { Ok(()) };
match self {
Self::NewChat { workspace: Some(w) } => id(w),
Self::CreateWorkspace { name: n, folder, .. } => {
name(n)?;
match folder {
NewFolder::Existing { path: p } => path(p),
NewFolder::Create => Ok(()),
}
}
Self::RenameWorkspace { id: i, name: n } => id(i).and_then(|()| name(n)),
Self::RemoveWorkspace { id: i, .. } => id(i),
Self::GetConfig { scope: ConfigScope::Workspace { id: i } } | Self::SetConfig { scope: ConfigScope::Workspace { id: i }, .. } => id(i),
Self::ListFolders { path: Some(p) } => path(p),
Self::WorkspaceEnv { workspace: Some(w), .. } => id(w),
Self::SetPluginEnabled { .. } | Self::SetPluginSetting { .. } | Self::KeepPlugin { .. } | Self::RemovePlugin { .. } | Self::TrustPlugins { .. } => {
crate::plugins::check_sizes(self)
}
Self::Hello { client, caps, .. } => {
name(client)?;
crate::version::check_caps(caps)
}
Self::Plugin { plugin, msg } => crate::version::check_plugin_msg(plugin, msg),
Self::OpenView { .. } | Self::CloseView { .. } | Self::ViewEvent { .. } => crate::sites::check_sizes(self),
Self::WebCall { owner, method, params, .. } => crate::web::check_call(owner, method, params),
Self::CreateProfile { .. }
| Self::UpdateProfile { .. }
| Self::DeleteProfile { .. }
| Self::DuplicateProfile { .. }
| Self::TestProfile { .. }
| Self::SetRole { .. }
| Self::SetLevelProfile { .. } => crate::profiles::check_sizes(self),
Self::AnswerQuestion { text, .. } => {
if long(text, crate::MAX_ANSWER_CHARS) {
Err("the answer is too long".to_owned())
} else {
Ok(())
}
}
_ => crate::queue::check_sizes(self),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ServerMsg;
#[test]
fn workspace_messages_round_trip() {
let layer = Layer { env: Some(EnvKind::Container), image: Some("python:3-slim".into()), ..Layer::default() };
let msgs = vec![
ClientMsg::NewChat { workspace: Some("w1".into()) },
ClientMsg::CreateWorkspace { name: "Data".into(), folder: NewFolder::Create, config: layer.clone() },
ClientMsg::CreateWorkspace { name: "Repo".into(), folder: NewFolder::Existing { path: "/home/me/repo".into() }, config: Layer::default() },
ClientMsg::RenameWorkspace { id: "w1".into(), name: "New".into() },
ClientMsg::RemoveWorkspace { id: "w1".into(), clean: true },
ClientMsg::GetConfig { scope: ConfigScope::Chat },
ClientMsg::SetConfig { scope: ConfigScope::Workspace { id: "w1".into() }, layer: layer.clone(), api_key: None },
ClientMsg::ListFolders { path: None },
ClientMsg::CheckContainers,
ClientMsg::WorkspaceEnv { action: None, workspace: Some("w1".into()) },
];
for m in msgs {
assert_eq!(ClientMsg::from_json(&m.to_json()).unwrap(), m, "{}", m.to_json());
assert!(m.check_sizes().is_ok());
}
assert_eq!(ClientMsg::from_json(r#"{"type":"new_chat"}"#).unwrap(), ClientMsg::NewChat { workspace: None });
assert_eq!(ClientMsg::from_json(r#"{"type":"workspace_env"}"#).unwrap(), ClientMsg::WorkspaceEnv { action: None, workspace: None });
let ws = WorkspaceSummary { id: "w1".into(), name: "Data".into(), folder: "/d".into(), chats: 2, updated_at: 5, env: EnvKind::Nix };
let effective = byob_types::config::resolve(Default::default(), Default::default(), Default::default());
let view = ConfigView { scope: ConfigScope::Global, own: layer, effective, has_key: false, title: "Defaults".into(), workspace: Some(ws.clone()) };
let msgs = vec![
ServerMsg::Workspaces { items: vec![ws], current: Some("w1".into()), root: "/home/me/byob-workspaces".into(), support: Default::default() },
ServerMsg::Config(Box::new(view)),
ServerMsg::Folders(FolderList { path: "/".into(), parent: None, dirs: vec!["home".into()], truncated: false, error: None }),
ServerMsg::ContainersChecked { ok: false, message: "Docker isn't running".into() },
ServerMsg::WorkspaceCreated { id: None, error: Some("no".into()) },
ServerMsg::ChatOpened { chat: None, workspace: Some("w1".into()) },
];
for m in msgs {
assert_eq!(ServerMsg::from_json(&m.to_json()).unwrap(), m);
}
assert_eq!(ServerMsg::from_json(r#"{"type":"chat_opened","chat":null}"#).unwrap(), ServerMsg::ChatOpened { chat: None, workspace: None });
}
#[test]
fn oversized_fields_are_refused() {
let huge = "x".repeat(MAX_PATH_CHARS + 1);
for m in [
ClientMsg::CreateWorkspace { name: "n".into(), folder: NewFolder::Existing { path: huge.clone() }, config: Layer::default() },
ClientMsg::CreateWorkspace { name: huge.clone(), folder: NewFolder::Create, config: Layer::default() },
ClientMsg::RenameWorkspace { id: huge.clone(), name: "n".into() },
ClientMsg::RemoveWorkspace { id: String::new(), clean: false },
ClientMsg::ListFolders { path: Some(huge.clone()) },
ClientMsg::NewChat { workspace: Some(huge.clone()) },
ClientMsg::GetConfig { scope: ConfigScope::Workspace { id: huge.clone() } },
] {
assert!(m.check_sizes().is_err(), "{m:?}");
}
}
}