use std::collections::HashMap; use serde::{Deserialize, Serialize}; use crate::action::AgentAction; use crate::profile::{AgentBackend, AgentProfile}; use crate::template::{is_known_placeholder, placeholders_in}; pub const SETTINGS_KEY: &str = "agents.settings"; pub const RECENT_WORKING_DIR_LIMIT: usize = 5; #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] pub enum SettingsProblem { #[error("action {action_id} references unknown agent {agent_id}")] UnknownAgent { action_id: String, agent_id: String }, #[error("agent {agent_id} has an empty command")] EmptyCommand { agent_id: String }, #[error("{item_id} uses unknown placeholder {{{placeholder}}}")] UnknownPlaceholder { item_id: String, placeholder: String, }, #[error("agent {agent_id} has an empty model")] EmptyModel { agent_id: String }, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct AgentSettings { pub agents: Vec, pub actions: Vec, pub resume_interrupted_runs: bool, pub recent_working_dirs: HashMap>, /// Empty means Microsoft Copilot. Otherwise the id of a chat profile. pub write_with: String, } impl Default for AgentSettings { fn default() -> Self { Self { agents: vec![AgentProfile::claude_wsl(), AgentProfile::copilot_wsl()], actions: vec![ AgentAction::answer_this("claude"), AgentAction::build_this("claude"), ], resume_interrupted_runs: true, recent_working_dirs: HashMap::new(), write_with: String::new(), } } } fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec) { for text in texts { for placeholder in placeholders_in(text) { if !is_known_placeholder(&placeholder) { problems.push(SettingsProblem::UnknownPlaceholder { item_id: item_id.to_string(), placeholder, }); } } } } impl AgentSettings { /// Chat profile chosen under «Write with», or `None` for Microsoft Copilot. pub fn write_with_profile(&self) -> Option<&AgentProfile> { if self.write_with.is_empty() { return None; } self.agents .iter() .find(|agent| agent.id == self.write_with && agent.is_chat()) } pub fn to_json(&self) -> String { serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string()) } pub fn from_json(json: &str) -> Result { let mut settings: Self = serde_json::from_str(json)?; for agent in &mut settings.agents { agent.migrate_open_session_command(); } Ok(settings) } pub fn recent_working_dirs_of(&self, agent_id: &str) -> &[String] { self.recent_working_dirs .get(agent_id) .map_or(&[], Vec::as_slice) } pub fn remember_working_dir(&mut self, agent_id: &str, working_dir: &str) { let recent = self .recent_working_dirs .entry(agent_id.to_owned()) .or_default(); recent.retain(|existing| existing != working_dir); recent.insert(0, working_dir.to_owned()); recent.truncate(RECENT_WORKING_DIR_LIMIT); } pub fn validate(&self) -> Vec { let mut problems = Vec::new(); for agent in &self.agents { if agent.is_command() && agent.command.trim().is_empty() { problems.push(SettingsProblem::EmptyCommand { agent_id: agent.id.clone(), }); } let model = match &agent.backend { AgentBackend::OpenAi { model, .. } | AgentBackend::Anthropic { model, .. } => { model.as_str() } AgentBackend::Command => "", }; if agent.is_chat() && model.trim().is_empty() { problems.push(SettingsProblem::EmptyModel { agent_id: agent.id.clone(), }); } check_placeholders( &agent.id, &[&agent.command, &agent.open_session_command], &mut problems, ); } for action in &self.actions { if !self.agents.iter().any(|agent| agent.id == action.agent_id) { problems.push(SettingsProblem::UnknownAgent { action_id: action.id.clone(), agent_id: action.agent_id.clone(), }); } check_placeholders( &action.id, &[&action.prompt_template, &action.extra_args], &mut problems, ); } problems } } #[cfg(test)] mod tests { use super::*; #[test] fn default_round_trips_and_is_valid() { let settings = AgentSettings::default(); let loaded = AgentSettings::from_json(&settings.to_json()).unwrap(); assert_eq!(loaded, settings); assert!(settings.validate().is_empty()); } #[test] fn from_json_migrates_legacy_wsl_open_session_commands_only() { let legacy = AgentSettings::from_json(&format!( r#"{{"agents":[{{"id":"claude","open_session_command":"{}"}},{{"id":"copilot","open_session_command":"{}"}},{{"id":"mine","open_session_command":"wt.exe wsl.exe -e claude --resume {{session_id}}"}}]}}"#, crate::profile::LEGACY_CLAUDE_WSL_OPEN_SESSION, crate::profile::LEGACY_COPILOT_WSL_OPEN_SESSION, )) .unwrap(); assert_eq!( legacy.agents[0].open_session_command, AgentProfile::claude_wsl().open_session_command ); assert_eq!( legacy.agents[1].open_session_command, AgentProfile::copilot_wsl().open_session_command ); assert_eq!( legacy.agents[2].open_session_command, "wt.exe wsl.exe -e claude --resume {session_id}" ); } #[test] fn recent_working_dirs_are_newest_first_deduped_limited_and_per_agent() { let mut settings = AgentSettings::default(); assert!(settings.recent_working_dirs_of("claude").is_empty()); for index in 0..7 { settings.remember_working_dir("claude", &format!("/repo/{index}")); } settings.remember_working_dir("claude", "/repo/4"); settings.remember_working_dir("copilot", "/other"); assert_eq!( settings.recent_working_dirs_of("claude"), ["/repo/4", "/repo/6", "/repo/5", "/repo/3", "/repo/2"] ); assert_eq!(settings.recent_working_dirs_of("copilot"), ["/other"]); let loaded = AgentSettings::from_json(&settings.to_json()).unwrap(); assert_eq!(loaded, settings); assert!( AgentSettings::from_json("{}") .unwrap() .recent_working_dirs .is_empty() ); } #[test] fn empty_object_loads_defaults() { assert_eq!( AgentSettings::from_json("{}").unwrap(), AgentSettings::default() ); } #[test] fn resume_defaults_on_and_can_be_switched_off() { assert!( AgentSettings::from_json("{}") .unwrap() .resume_interrupted_runs ); let off = AgentSettings::from_json(r#"{"resume_interrupted_runs":false}"#).unwrap(); assert!(!off.resume_interrupted_runs); } #[test] fn partial_json_fills_missing_fields() { let loaded = AgentSettings::from_json( r#"{"agents":[{"id":"x","command":"x {session_id}"}],"actions":[{"id":"a","agent_id":"x"}]}"#, ) .unwrap(); assert_eq!(loaded.agents.len(), 1); assert_eq!( loaded.agents[0].output, crate::OutputFormat::ClaudeStreamJson ); assert_eq!(loaded.actions[0].working_dir, ""); let only_actions = AgentSettings::from_json(r#"{"actions":[]}"#).unwrap(); assert_eq!(only_actions.agents.len(), 2); } #[test] fn validate_finds_problems() { let mut settings = AgentSettings::default(); settings.actions[0].agent_id = "ghost".to_string(); settings.agents[1].command = String::new(); settings.agents[0].command.push_str(" {bogus}"); settings.actions[1].prompt_template.push_str(" {nope}"); let problems = settings.validate(); assert!(problems.contains(&SettingsProblem::UnknownAgent { action_id: "answer-this".to_string(), agent_id: "ghost".to_string(), })); assert!(problems.contains(&SettingsProblem::EmptyCommand { agent_id: "copilot".to_string(), })); assert!(problems.contains(&SettingsProblem::UnknownPlaceholder { item_id: "claude".to_string(), placeholder: "bogus".to_string(), })); assert!(problems.contains(&SettingsProblem::UnknownPlaceholder { item_id: "build-this".to_string(), placeholder: "nope".to_string(), })); } #[test] fn a_profile_without_backend_stays_a_command() { let loaded = AgentSettings::from_json( r#"{"agents":[{"id":"legacy","name":"Legacy","command":"claude -p"}]}"#, ) .unwrap(); assert!(loaded.agents[0].is_command()); assert!(loaded.write_with.is_empty()); } #[test] fn chat_profiles_need_a_model_and_write_with_round_trips() { let mut settings = AgentSettings::default(); settings.agents.push(AgentProfile::ollama()); assert!(settings.validate().contains(&SettingsProblem::EmptyModel { agent_id: "ollama".to_string(), })); settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi { base_url: "http://127.0.0.1:11434/v1".to_owned(), model: "qwen3.5:9b".to_owned(), api_key: String::new(), }; settings.write_with = "ollama".to_owned(); let loaded = AgentSettings::from_json(&settings.to_json()).unwrap(); assert_eq!(loaded.write_with, "ollama"); assert!(loaded.validate().is_empty()); } #[test] fn write_with_profile_is_none_for_microsoft_and_missing_ids() { let mut settings = AgentSettings::default(); assert!(settings.write_with_profile().is_none()); settings.write_with = "missing".to_owned(); assert!(settings.write_with_profile().is_none()); settings.agents.push(AgentProfile::ollama()); settings.agents.last_mut().unwrap().backend = AgentBackend::OpenAi { base_url: "http://127.0.0.1:11434/v1".to_owned(), model: "qwen3.5:9b".to_owned(), api_key: String::new(), }; settings.write_with = "ollama".to_owned(); assert_eq!( settings .write_with_profile() .map(|profile| profile.name.as_str()), Some("Ollama") ); settings.write_with = "claude".to_owned(); assert!(settings.write_with_profile().is_none()); } }