Skip to main content

wisp/settings/
mod.rs

1#![doc = include_str!("../docs/settings_module.md")]
2
3pub mod menu;
4pub mod overlay;
5pub(crate) mod picker;
6pub mod types;
7
8use crate::components::provider_login::{ProviderLoginEntry, ProviderLoginStatus, provider_login_summary};
9use crate::components::server_status::server_status_summary;
10use acp_utils::notifications::McpServerStatusEntry;
11use acp_utils::settings::SettingsStore;
12use agent_client_protocol::schema::{AuthMethod, SessionConfigOption};
13use serde::{Deserialize, Serialize};
14use std::path::{Path, PathBuf};
15use tracing::warn;
16
17#[cfg(test)]
18pub(crate) static WISP_HOME_ENV_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());
19
20#[doc = include_str!("../docs/wisp_settings.md")]
21#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
22#[serde(rename_all = "camelCase")]
23pub struct WispSettings {
24    #[serde(default)]
25    pub theme: ThemeSettings,
26    #[serde(default)]
27    pub content_padding: Option<u16>,
28}
29
30pub const DEFAULT_CONTENT_PADDING: usize = 2;
31
32pub fn resolve_content_padding(settings: &WispSettings) -> usize {
33    settings.content_padding.map_or(DEFAULT_CONTENT_PADDING, |v| v.max(2) as usize)
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
37#[serde(rename_all = "camelCase")]
38pub struct ThemeSettings {
39    #[serde(default)]
40    pub file: Option<String>,
41}
42
43pub fn wisp_home() -> Option<PathBuf> {
44    Some(SettingsStore::new("WISP_HOME", ".wisp")?.home().to_path_buf())
45}
46
47pub fn themes_dir_path() -> Option<PathBuf> {
48    Some(wisp_home()?.join("themes"))
49}
50
51pub fn load_or_create_settings() -> WispSettings {
52    if let Some(store) = SettingsStore::new("WISP_HOME", ".wisp") {
53        store.load_or_create()
54    } else {
55        warn!("Unable to resolve Wisp settings path; using defaults");
56        WispSettings::default()
57    }
58}
59
60pub fn load_theme(settings: &WispSettings) -> tui::Theme {
61    let Some(theme_file) = settings.theme.file.as_deref() else {
62        return tui::Theme::default();
63    };
64
65    let Some(path) = resolve_theme_file_path(theme_file) else {
66        warn!("Rejected unsafe theme filename: {}", theme_file);
67        return tui::Theme::default();
68    };
69
70    tui::Theme::load_from_path(&path)
71}
72
73pub fn resolve_theme_file_path(file_name: &str) -> Option<PathBuf> {
74    let trimmed = file_name.trim();
75    if trimmed.is_empty() {
76        return None;
77    }
78
79    let candidate = Path::new(trimmed);
80    let base_name = candidate.file_name()?.to_str()?;
81    if base_name != trimmed {
82        return None;
83    }
84
85    if base_name == "." || base_name == ".." {
86        return None;
87    }
88
89    Some(themes_dir_path()?.join(base_name))
90}
91
92pub fn list_theme_files() -> Vec<String> {
93    let Some(themes_dir) = themes_dir_path() else {
94        return Vec::new();
95    };
96
97    let Ok(entries) = std::fs::read_dir(themes_dir) else {
98        return Vec::new();
99    };
100
101    let mut files = entries
102        .filter_map(Result::ok)
103        .filter_map(|entry| {
104            let Ok(file_type) = entry.file_type() else {
105                return None;
106            };
107
108            if !file_type.is_file() {
109                return None;
110            }
111
112            let name = entry.file_name().into_string().ok()?;
113            if !name.ends_with(".tmTheme") {
114                return None;
115            }
116            Some(name)
117        })
118        .collect::<Vec<_>>();
119
120    files.sort_unstable();
121    files
122}
123
124pub(crate) fn build_login_entries(auth_methods: &[AuthMethod]) -> Vec<ProviderLoginEntry> {
125    auth_methods
126        .iter()
127        .map(|m| {
128            let status = if m.description() == Some("authenticated") {
129                ProviderLoginStatus::LoggedIn
130            } else {
131                ProviderLoginStatus::NeedsLogin
132            };
133            ProviderLoginEntry { method_id: m.id().0.to_string(), name: m.name().to_string(), status }
134        })
135        .collect()
136}
137
138pub(crate) fn create_overlay(
139    config_options: &[SessionConfigOption],
140    server_statuses: &[McpServerStatusEntry],
141    auth_methods: &[AuthMethod],
142) -> overlay::SettingsOverlay {
143    let mut menu = menu::SettingsMenu::from_config_options(config_options);
144    decorate_menu(&mut menu, server_statuses, auth_methods);
145    overlay::SettingsOverlay::new(menu, server_statuses.to_vec(), auth_methods.to_vec())
146        .with_reasoning_effort_from_options(config_options)
147}
148
149pub(crate) fn decorate_menu(
150    menu: &mut menu::SettingsMenu,
151    server_statuses: &[McpServerStatusEntry],
152    auth_methods: &[AuthMethod],
153) {
154    let settings = load_or_create_settings();
155    let theme_files = list_theme_files();
156    menu.add_theme_entry(settings.theme.file.as_deref(), &theme_files);
157
158    let summary = server_status_summary(server_statuses);
159    menu.add_mcp_servers_entry(&summary);
160
161    if !auth_methods.is_empty() {
162        let login_entries = build_login_entries(auth_methods);
163        let login_summary = provider_login_summary(&login_entries);
164        menu.add_provider_logins_entry(&login_summary);
165    }
166}
167
168pub(crate) fn process_config_changes(changes: Vec<types::SettingsChange>) -> Vec<overlay::SettingsMessage> {
169    use acp_utils::config_option_id::THEME_CONFIG_ID;
170
171    let mut messages = Vec::new();
172    for change in changes {
173        if change.config_id == THEME_CONFIG_ID {
174            let file = theme_file_from_picker_value(&change.new_value);
175            let mut settings = load_or_create_settings();
176            settings.theme.file = file;
177            if let Err(err) = save_settings(&settings) {
178                tracing::warn!("Failed to persist theme setting: {err}");
179            }
180            let theme = load_theme(&settings);
181            messages.push(overlay::SettingsMessage::SetTheme(theme));
182        } else {
183            messages.push(overlay::SettingsMessage::SetConfigOption {
184                config_id: change.config_id,
185                value: change.new_value,
186            });
187        }
188    }
189    messages
190}
191
192fn theme_file_from_picker_value(value: &str) -> Option<String> {
193    let trimmed = value.trim();
194    if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
195}
196
197pub(crate) fn cycle_quick_option(config_options: &[SessionConfigOption]) -> Option<(String, String)> {
198    use crate::components::status_line::is_cycleable_mode_option;
199    use agent_client_protocol::schema::{SessionConfigKind, SessionConfigSelectOptions};
200
201    let option = config_options.iter().find(|option| is_cycleable_mode_option(option))?;
202
203    let SessionConfigKind::Select(ref select) = option.kind else {
204        return None;
205    };
206
207    let SessionConfigSelectOptions::Ungrouped(ref options) = select.options else {
208        return None;
209    };
210
211    if options.is_empty() {
212        return None;
213    }
214
215    let current_index = options.iter().position(|entry| entry.value == select.current_value).unwrap_or(0);
216    let next_index = (current_index + 1) % options.len();
217    options.get(next_index).map(|next| (option.id.0.to_string(), next.value.0.to_string()))
218}
219
220pub(crate) fn cycle_reasoning_option(config_options: &[SessionConfigOption]) -> Option<(String, String)> {
221    use crate::components::status_line::{extract_reasoning_effort, extract_reasoning_levels};
222    use acp_utils::config_option_id::ConfigOptionId;
223    use utils::ReasoningEffort;
224
225    let levels = extract_reasoning_levels(config_options);
226    if levels.is_empty() {
227        return None;
228    }
229
230    let current = extract_reasoning_effort(config_options);
231    let next = ReasoningEffort::cycle_within(current, &levels);
232    Some((ConfigOptionId::ReasoningEffort.as_str().to_string(), ReasoningEffort::config_str(next).to_string()))
233}
234
235pub(crate) fn unhealthy_server_count(statuses: &[McpServerStatusEntry]) -> usize {
236    use acp_utils::notifications::McpServerStatus;
237
238    statuses.iter().filter(|status| !matches!(status.status, McpServerStatus::Connected { .. })).count()
239}
240
241pub fn save_settings(settings: &WispSettings) -> std::io::Result<()> {
242    let store = SettingsStore::new("WISP_HOME", ".wisp")
243        .ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "Unable to resolve Wisp settings path"))?;
244
245    store.save(settings)
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251    use crate::test_helpers::with_wisp_home;
252    use acp_utils::config_option_id::THEME_CONFIG_ID;
253    use acp_utils::settings::SettingsStore;
254    use std::fs;
255    use tempfile::TempDir;
256
257    fn change(config_id: &str, new_value: &str) -> types::SettingsChange {
258        types::SettingsChange { config_id: config_id.to_string(), new_value: new_value.to_string() }
259    }
260
261    fn with_themes_dir(f: impl FnOnce(&std::path::Path)) {
262        let temp_dir = TempDir::new().unwrap();
263        let themes = temp_dir.path().join("themes");
264        fs::create_dir_all(&themes).unwrap();
265        f(&themes);
266        std::mem::drop(temp_dir);
267    }
268
269    #[test]
270    fn round_trip_serde() {
271        let temp_dir = TempDir::new().unwrap();
272        let store = SettingsStore::from_path(temp_dir.path());
273        let settings =
274            WispSettings { theme: ThemeSettings { file: Some("my-theme.json".to_string()) }, content_padding: None };
275        store.save(&settings).unwrap();
276        assert_eq!(store.load_or_create::<WispSettings>(), settings);
277    }
278
279    #[test]
280    fn resolve_theme_file_path_allows_basename_only() {
281        for rejected in ["", "../escape.json", "subdir/theme.json"] {
282            assert!(resolve_theme_file_path(rejected).is_none(), "should reject {rejected:?}");
283        }
284        #[cfg(windows)]
285        assert!(resolve_theme_file_path("..\\escape.json").is_none());
286    }
287
288    #[test]
289    fn list_theme_files_returns_sorted_and_filters_correctly() {
290        // Sorted .tmTheme files only, ignoring directories and non-.tmTheme files
291        with_themes_dir(|themes| {
292            fs::create_dir_all(themes.join("nested")).unwrap();
293            fs::write(themes.join("zeta.tmTheme"), "z").unwrap();
294            fs::write(themes.join("alpha.tmTheme"), "a").unwrap();
295            fs::write(themes.join("readme.txt"), "ignored").unwrap();
296
297            with_wisp_home(themes.parent().unwrap(), || {
298                assert_eq!(list_theme_files(), vec!["alpha.tmTheme", "zeta.tmTheme"]);
299            });
300        });
301    }
302
303    #[test]
304    fn list_theme_files_returns_empty_when_themes_dir_missing() {
305        let temp_dir = TempDir::new().unwrap();
306        with_wisp_home(temp_dir.path(), || {
307            assert!(list_theme_files().is_empty());
308        });
309    }
310
311    #[test]
312    fn theme_file_from_picker_value_parsing() {
313        for (input, expected) in [
314            ("   ", None),
315            ("", None),
316            ("sage.tmTheme", Some("sage.tmTheme")),
317            ("  spaced.tmTheme  ", Some("spaced.tmTheme")),
318        ] {
319            assert_eq!(theme_file_from_picker_value(input), expected.map(String::from), "input: {input:?}");
320        }
321    }
322
323    #[test]
324    fn process_theme_change_persists_and_produces_set_theme() {
325        use crate::test_helpers::CUSTOM_TMTHEME;
326        use tui::Color;
327
328        with_themes_dir(|themes| {
329            fs::write(themes.join("custom.tmTheme"), CUSTOM_TMTHEME).unwrap();
330
331            with_wisp_home(themes.parent().unwrap(), || {
332                let messages = process_config_changes(vec![change(THEME_CONFIG_ID, "custom.tmTheme")]);
333                let theme = messages.iter().find_map(|m| match m {
334                    overlay::SettingsMessage::SetTheme(t) => Some(t),
335                    _ => None,
336                });
337                assert!(theme.is_some(), "should produce SetTheme message");
338                assert_eq!(theme.unwrap().text_primary(), Color::Rgb { r: 0x11, g: 0x22, b: 0x33 });
339                assert_eq!(load_or_create_settings().theme.file.as_deref(), Some("custom.tmTheme"));
340            });
341        });
342    }
343
344    #[test]
345    fn process_theme_change_persists_default_as_none() {
346        let temp_dir = TempDir::new().unwrap();
347        with_wisp_home(temp_dir.path(), || {
348            save_settings(&WispSettings {
349                theme: ThemeSettings { file: Some("old.tmTheme".to_string()) },
350                content_padding: None,
351            })
352            .unwrap();
353            let _ = process_config_changes(vec![change(THEME_CONFIG_ID, "   ")]);
354            assert_eq!(load_or_create_settings().theme.file, None);
355        });
356    }
357
358    #[test]
359    fn process_non_theme_change_produces_set_config_option() {
360        let messages = process_config_changes(vec![change("provider", "ollama")]);
361        match messages.as_slice() {
362            [overlay::SettingsMessage::SetConfigOption { config_id, value }] => {
363                assert_eq!(config_id, "provider");
364                assert_eq!(value, "ollama");
365            }
366            other => panic!("expected SetConfigOption, got: {other:?}"),
367        }
368    }
369}