1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::{fmt, str::FromStr};
4
5use serde::{Deserialize, Serialize};
6
7use crate::SecretString;
8use crate::mode::AgentMode;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
18#[serde(rename_all = "lowercase")]
19pub enum AutoAcceptMode {
20 Off,
21 #[default]
22 Safe,
23 All,
24}
25
26impl<'de> Deserialize<'de> for AutoAcceptMode {
27 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
28 where
29 D: serde::Deserializer<'de>,
30 {
31 struct AutoAcceptModeVisitor;
32
33 impl<'de> serde::de::Visitor<'de> for AutoAcceptModeVisitor {
34 type Value = AutoAcceptMode;
35
36 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
37 formatter
38 .write_str("a string (\"off\", \"safe\", \"all\") or a boolean (true/false)")
39 }
40
41 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
42 where
43 E: serde::de::Error,
44 {
45 Ok(if v {
46 AutoAcceptMode::All
47 } else {
48 AutoAcceptMode::Off
49 })
50 }
51
52 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
53 where
54 E: serde::de::Error,
55 {
56 AutoAcceptMode::from_str(v).map_err(serde::de::Error::custom)
57 }
58
59 fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
60 where
61 E: serde::de::Error,
62 {
63 AutoAcceptMode::from_str(&v).map_err(serde::de::Error::custom)
64 }
65 }
66
67 deserializer.deserialize_any(AutoAcceptModeVisitor)
68 }
69}
70
71impl FromStr for AutoAcceptMode {
72 type Err = String;
73
74 fn from_str(s: &str) -> Result<Self, Self::Err> {
75 match s.to_lowercase().as_str() {
76 "off" | "false" | "no" | "0" | "disabled" => Ok(AutoAcceptMode::Off),
77 "safe" | "on" => Ok(AutoAcceptMode::Safe),
78 "all" | "always" | "true" | "yes" | "1" | "enabled" => Ok(AutoAcceptMode::All),
79 _ => Err(format!(
80 "Unknown auto-accept mode '{}'. Valid values: off, safe, all",
81 s
82 )),
83 }
84 }
85}
86
87impl fmt::Display for AutoAcceptMode {
88 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89 match self {
90 AutoAcceptMode::Off => write!(f, "off"),
91 AutoAcceptMode::Safe => write!(f, "safe"),
92 AutoAcceptMode::All => write!(f, "all"),
93 }
94 }
95}
96
97#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct SandboxConfig {
143 pub backend: String,
146 #[serde(default)]
153 pub writable_paths: Vec<String>,
154}
155
156impl Default for SandboxConfig {
157 fn default() -> Self {
159 Self::auto()
160 }
161}
162
163impl SandboxConfig {
164 pub fn disabled() -> Self {
166 SandboxConfig {
167 backend: "off".to_string(),
168 writable_paths: Vec::new(),
169 }
170 }
171
172 pub fn auto() -> Self {
174 SandboxConfig {
175 backend: "auto".to_string(),
176 ..Self::disabled()
177 }
178 }
179
180 pub fn is_disabled(&self) -> bool {
182 crate::sandbox::SandboxBackend::is_off(&self.backend)
183 }
184
185 pub fn is_enabled(&self) -> bool {
187 !self.is_disabled()
188 }
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize, Default)]
198pub struct ProjectSettings {
199 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub safe_command_prefixes: Option<Vec<String>>,
202 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub denied_command_prefixes: Option<Vec<String>>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
207 pub auto_accept_mode: Option<AutoAcceptMode>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub context_limit: Option<u32>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub project_md_files: Option<Vec<String>>,
216 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub preferred_mode: Option<AgentMode>,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub auto_compact_enabled: Option<bool>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub questions_enabled: Option<bool>,
225 }
233
234pub fn discover_project_settings(
242 start_dir: &std::path::Path,
243) -> Option<Result<ProjectSettings, SettingsError>> {
244 let mut dir = start_dir.to_path_buf();
245
246 loop {
247 let candidate = dir.join(".tinyharness").join("config.json");
248 if candidate.is_file() {
249 let content = match std::fs::read_to_string(&candidate) {
250 Ok(c) => c,
251 Err(e) => return Some(Err(SettingsError::Io(e))),
252 };
253 let parsed = serde_json::from_str(&content).map_err(SettingsError::Parse);
254 return Some(parsed);
255 }
256
257 if let Some(parent) = dir.parent() {
259 if parent == dir {
260 break;
261 }
262 dir = parent.to_path_buf();
263 } else {
264 break;
265 }
266 }
267
268 None
269}
270
271#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum SettingSource {
274 Global,
276 Project,
278 Default,
280}
281
282impl std::fmt::Display for SettingSource {
283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284 match self {
285 SettingSource::Global => f.write_str("global"),
286 SettingSource::Project => f.write_str("project"),
287 SettingSource::Default => f.write_str("default"),
288 }
289 }
290}
291
292#[derive(Debug, Clone)]
296pub struct MergedSettings {
297 pub safe_commands: Vec<String>,
299 pub safe_commands_source: SettingSource,
300 pub denied_commands: Vec<String>,
302 pub denied_commands_source: SettingSource,
303 pub auto_accept_mode: AutoAcceptMode,
304 pub auto_accept_mode_source: SettingSource,
305 pub context_limit: Option<u32>,
306 pub context_limit_source: SettingSource,
307 pub project_md_files: Vec<String>,
308 pub project_md_files_source: SettingSource,
309 pub preferred_mode: AgentMode,
310 pub preferred_mode_source: SettingSource,
311 pub auto_compact_enabled: bool,
312 pub auto_compact_enabled_source: SettingSource,
313 pub questions_enabled: bool,
314 pub questions_enabled_source: SettingSource,
315 pub sandbox: SandboxConfig,
319 pub sandbox_source: SettingSource,
320 pub allowed_paths: Vec<String>,
327 pub allowed_paths_source: SettingSource,
328}
329
330pub fn load_merged_settings_from(
335 paths: &crate::paths::Paths,
336) -> (Settings, Option<ProjectSettings>, MergedSettings) {
337 let global = load_settings_from(paths);
338 let project = project_settings_or_none(paths);
339 let merged = merge_settings(&global, project.as_ref());
340 (global, project, merged)
341}
342
343pub fn load_merged_settings() -> (Settings, Option<ProjectSettings>, MergedSettings) {
353 load_merged_settings_from(&crate::paths::Paths::default())
354}
355
356pub(crate) fn project_settings_or_none(paths: &crate::paths::Paths) -> Option<ProjectSettings> {
361 match discover_project_settings(paths.project_dir()) {
362 Some(Ok(ps)) => Some(ps),
363 Some(Err(e)) => {
364 tracing::warn!(
365 "Failed to parse .tinyharness/config.json: {e}. Ignoring project settings."
366 );
367 None
368 }
369 None => None,
370 }
371}
372
373fn merge_settings(global: &Settings, project: Option<&ProjectSettings>) -> MergedSettings {
375 let global_safe = global.get_safe_commands();
376 let global_denied = global.get_denied_commands();
377
378 match project {
379 None => MergedSettings {
380 safe_commands: global_safe,
381 safe_commands_source: SettingSource::Default,
382 denied_commands: global_denied,
383 denied_commands_source: SettingSource::Default,
384 auto_accept_mode: global.auto_accept_mode,
385 auto_accept_mode_source: SettingSource::Default,
386 context_limit: global.context_limit,
387 context_limit_source: SettingSource::Default,
388 project_md_files: Vec::new(),
389 project_md_files_source: SettingSource::Default,
390 preferred_mode: global.preferred_mode,
391 preferred_mode_source: SettingSource::Default,
392 auto_compact_enabled: global.auto_compact_enabled,
393 auto_compact_enabled_source: SettingSource::Default,
394 questions_enabled: global.questions_enabled,
395 questions_enabled_source: SettingSource::Default,
396 sandbox: global.sandbox.clone(),
397 sandbox_source: SettingSource::Global,
398 allowed_paths: global.allowed_paths.clone().unwrap_or_default(),
399 allowed_paths_source: SettingSource::Default,
400 },
401 Some(p) => {
402 let safe_commands = if let Some(ref proj_safe) = p.safe_command_prefixes {
404 let mut combined = global_safe.clone();
405 for cmd in proj_safe {
406 if !combined.contains(cmd) {
407 combined.push(cmd.clone());
408 }
409 }
410 combined
411 } else {
412 global_safe
413 };
414 let safe_source = if p.safe_command_prefixes.is_some() {
415 SettingSource::Project
416 } else {
417 SettingSource::Default
418 };
419
420 let (denied_commands, denied_source) =
422 if let Some(ref proj_denied) = p.denied_command_prefixes {
423 (proj_denied.clone(), SettingSource::Project)
424 } else {
425 (global_denied, SettingSource::Default)
426 };
427
428 let (auto_accept_mode, auto_source) = p
429 .auto_accept_mode
430 .map(|v| (v, SettingSource::Project))
431 .unwrap_or((global.auto_accept_mode, SettingSource::Default));
432
433 let (context_limit, ctx_source) = p
434 .context_limit
435 .map(|v| (Some(v), SettingSource::Project))
436 .unwrap_or((global.context_limit, SettingSource::Default));
437
438 let (project_md_files, md_source) = p
439 .project_md_files
440 .as_ref()
441 .map(|files| (files.clone(), SettingSource::Project))
442 .unwrap_or((Vec::new(), SettingSource::Default));
443
444 let (preferred_mode, mode_source) = p
445 .preferred_mode
446 .map(|m| (m, SettingSource::Project))
447 .unwrap_or((global.preferred_mode, SettingSource::Default));
448
449 let (auto_compact_enabled, ac_source) = p
450 .auto_compact_enabled
451 .map(|v| (v, SettingSource::Project))
452 .unwrap_or((global.auto_compact_enabled, SettingSource::Default));
453
454 let (questions_enabled, q_source) = p
455 .questions_enabled
456 .map(|v| (v, SettingSource::Project))
457 .unwrap_or((global.questions_enabled, SettingSource::Default));
458
459 let sandbox = global.sandbox.clone();
464 let sandbox_source = SettingSource::Global;
465
466 let allowed_paths = global.allowed_paths.clone().unwrap_or_default();
471 let allowed_paths_source = SettingSource::Global;
472
473 MergedSettings {
474 safe_commands,
475 safe_commands_source: safe_source,
476 denied_commands,
477 denied_commands_source: denied_source,
478 auto_accept_mode,
479 auto_accept_mode_source: auto_source,
480 context_limit,
481 context_limit_source: ctx_source,
482 project_md_files,
483 project_md_files_source: md_source,
484 preferred_mode,
485 preferred_mode_source: mode_source,
486 auto_compact_enabled,
487 auto_compact_enabled_source: ac_source,
488 questions_enabled,
489 questions_enabled_source: q_source,
490 sandbox,
491 sandbox_source,
492 allowed_paths,
493 allowed_paths_source,
494 }
495 }
496 }
497}
498
499impl MergedSettings {
500 pub fn tool_availability(&self) -> crate::tools::ToolAvailability {
502 crate::tools::ToolAvailability {
503 auto_compact: self.auto_compact_enabled,
504 question: self.questions_enabled,
505 }
506 }
507}
508
509pub fn generate_project_config_template(settings: &Settings) -> ProjectSettings {
513 ProjectSettings {
514 safe_command_prefixes: settings.safe_command_prefixes.clone(),
515 denied_command_prefixes: settings.denied_command_prefixes.clone(),
516 auto_accept_mode: Some(settings.auto_accept_mode),
517 context_limit: settings.context_limit,
518 project_md_files: None, preferred_mode: Some(settings.preferred_mode),
520 auto_compact_enabled: Some(settings.auto_compact_enabled),
521 questions_enabled: Some(settings.questions_enabled),
522 }
527}
528
529#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
531pub enum ProviderKind {
532 #[default]
533 Ollama,
534 LlamaCpp,
535 Vllm,
536 OpenAiCompat,
542 Sockudo,
543}
544
545impl fmt::Display for ProviderKind {
546 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
547 match self {
548 ProviderKind::Ollama => f.write_str("ollama"),
549 ProviderKind::LlamaCpp => f.write_str("llama.cpp"),
550 ProviderKind::Vllm => f.write_str("vllm"),
551 ProviderKind::OpenAiCompat => f.write_str("openai-compat"),
552 ProviderKind::Sockudo => f.write_str("sockudo"),
553 }
554 }
555}
556
557impl FromStr for ProviderKind {
558 type Err = String;
559
560 fn from_str(s: &str) -> Result<Self, Self::Err> {
561 match s.trim().to_lowercase().as_str() {
562 "ollama" => Ok(ProviderKind::Ollama),
563 "llama.cpp" | "llamacpp" | "llama_cpp" => Ok(ProviderKind::LlamaCpp),
564 "vllm" => Ok(ProviderKind::Vllm),
565 "openai-compat" | "openaicompat" | "openai_compat" => Ok(ProviderKind::OpenAiCompat),
566 "sockudo" => Ok(ProviderKind::Sockudo),
567 _ => Err(format!("Unknown provider '{}'", s)),
568 }
569 }
570}
571
572#[derive(Debug, Clone, Serialize, Deserialize)]
576#[serde(default)] pub struct Settings {
578 #[serde(default)]
579 pub last_provider: ProviderKind,
580 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
585 pub provider_urls: HashMap<ProviderKind, String>,
586 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
591 pub provider_models: HashMap<ProviderKind, String>,
592 #[serde(default)]
593 pub preferred_mode: AgentMode,
594 pub openai_compat_api_key: Option<SecretString>,
598 pub sockudo_app_id: Option<String>,
600 pub sockudo_app_key: Option<String>,
602 pub sockudo_app_secret: Option<SecretString>,
604 #[serde(default, skip_serializing_if = "Option::is_none")]
609 pub request_timeout_secs: Option<u64>,
610 #[serde(default, skip_serializing_if = "Option::is_none")]
615 pub request_max_retries: Option<u32>,
616 #[serde(default)]
618 pub show_thinking: bool,
619 pub context_limit: Option<u32>,
621 #[serde(default)]
631 pub auto_accept_mode: AutoAcceptMode,
632 pub skip_health_check: bool,
641 pub safe_command_prefixes: Option<Vec<String>>,
643 pub denied_command_prefixes: Option<Vec<String>>,
646 pub project_md_files: Option<Vec<String>>,
651 #[serde(default = "default_true")]
655 pub auto_compact_enabled: bool,
656 #[serde(default = "default_true")]
661 pub questions_enabled: bool,
662 #[serde(default, skip_serializing_if = "SandboxConfig::is_disabled")]
668 pub sandbox: SandboxConfig,
669 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub allowed_paths: Option<Vec<String>>,
685}
686
687fn default_true() -> bool {
688 true
689}
690
691pub fn timeout_default_for(kind: ProviderKind) -> u64 {
694 match kind {
695 ProviderKind::Ollama => 5,
696 ProviderKind::Sockudo => 120,
697 _ => 30,
698 }
699}
700
701impl Default for Settings {
702 fn default() -> Self {
703 Settings {
704 last_provider: ProviderKind::Ollama,
705 provider_urls: HashMap::new(),
706 provider_models: HashMap::new(),
707 preferred_mode: AgentMode::Casual,
708 openai_compat_api_key: None,
709 sockudo_app_id: None,
710 sockudo_app_key: None,
711 sockudo_app_secret: None,
712 request_timeout_secs: None,
713 request_max_retries: None,
714 show_thinking: true,
715 context_limit: None,
716 auto_accept_mode: AutoAcceptMode::Safe,
717 skip_health_check: false,
718 safe_command_prefixes: None,
719 denied_command_prefixes: None,
720 project_md_files: None,
721 auto_compact_enabled: true,
722 questions_enabled: true,
723 sandbox: SandboxConfig::default(),
724 allowed_paths: None,
725 }
726 }
727}
728
729pub fn get_default_safe_commands() -> Vec<String> {
732 vec![
733 "cd".to_string(),
734 "ls".to_string(),
735 "grep".to_string(),
736 "glob".to_string(),
737 "find".to_string(),
738 "cat".to_string(),
739 "head".to_string(),
740 "tail".to_string(),
741 "wc".to_string(),
742 "pwd".to_string(),
743 "echo".to_string(),
744 "printf".to_string(),
745 "tree".to_string(),
746 "file".to_string(),
747 "stat".to_string(),
748 "du".to_string(),
749 "df".to_string(),
750 "free".to_string(),
751 "uptime".to_string(),
752 "whoami".to_string(),
753 "hostname".to_string(),
754 "uname".to_string(),
755 "date".to_string(),
756 "cal".to_string(),
757 "ps".to_string(),
758 "env".to_string(),
759 "printenv".to_string(),
760 "which".to_string(),
761 "whereis".to_string(),
762 "type".to_string(),
763 "git status".to_string(),
764 "git diff".to_string(),
765 "git log".to_string(),
766 "git show".to_string(),
767 "git branch".to_string(),
768 "git remote".to_string(),
769 "git tag".to_string(),
770 "git describe".to_string(),
771 "git rev-parse".to_string(),
772 "cargo tree".to_string(),
773 "cargo metadata".to_string(),
774 "cargo doc".to_string(),
775 "rustc --version".to_string(),
776 "cargo --version".to_string(),
777 ]
778}
779
780impl Settings {
781 pub fn get_safe_commands(&self) -> Vec<String> {
783 self.safe_command_prefixes
784 .clone()
785 .unwrap_or_else(get_default_safe_commands)
786 }
787
788 pub fn get_denied_commands(&self) -> Vec<String> {
793 self.denied_command_prefixes.clone().unwrap_or_default()
794 }
795
796 pub fn get_url_for(&self, kind: ProviderKind) -> Option<&str> {
798 self.provider_urls.get(&kind).map(|s| s.as_str())
799 }
800
801 pub fn set_url_for(&mut self, kind: ProviderKind, url: String) {
803 self.provider_urls.insert(kind, url);
804 }
805
806 pub fn get_model_for(&self, kind: ProviderKind) -> Option<&str> {
808 self.provider_models.get(&kind).map(|s| s.as_str())
809 }
810
811 pub fn set_model_for(&mut self, kind: ProviderKind, model: String) {
813 self.provider_models.insert(kind, model);
814 }
815
816 pub fn get_current_model(&self) -> Option<&str> {
818 self.get_model_for(self.last_provider)
819 }
820
821 pub fn get_current_url(&self) -> Option<&str> {
823 self.get_url_for(self.last_provider)
824 }
825
826 pub fn effective_timeout_secs(&self) -> u64 {
829 match self.request_timeout_secs {
830 Some(secs) if secs > 0 => secs,
831 _ => timeout_default_for(self.last_provider),
832 }
833 }
834
835 pub fn effective_max_retries(&self) -> u32 {
838 self.request_max_retries
839 .unwrap_or(match self.last_provider {
840 ProviderKind::Ollama => 3,
841 _ => 0,
842 })
843 }
844}
845
846#[derive(Debug)]
850pub enum SettingsError {
851 Io(std::io::Error),
852 Parse(serde_json::Error),
853}
854
855impl std::fmt::Display for SettingsError {
856 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
857 match self {
858 SettingsError::Io(e) => write!(f, "I/O error: {}", e),
859 SettingsError::Parse(e) => write!(f, "parse error: {}", e),
860 }
861 }
862}
863
864impl std::error::Error for SettingsError {
865 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
866 match self {
867 SettingsError::Io(e) => Some(e),
868 SettingsError::Parse(e) => Some(e),
869 }
870 }
871}
872
873impl From<std::io::Error> for SettingsError {
874 fn from(e: std::io::Error) -> Self {
875 SettingsError::Io(e)
876 }
877}
878
879impl From<serde_json::Error> for SettingsError {
880 fn from(e: serde_json::Error) -> Self {
881 SettingsError::Parse(e)
882 }
883}
884
885pub struct SettingsStore {
892 path: std::path::PathBuf,
893}
894
895impl SettingsStore {
896 pub fn default_path() -> Self {
903 Self::from_paths(&crate::paths::Paths::default())
904 }
905
906 pub fn from_paths(paths: &crate::paths::Paths) -> Self {
908 SettingsStore {
909 path: paths.settings_file(),
910 }
911 }
912
913 pub fn new(path: std::path::PathBuf) -> Self {
915 SettingsStore { path }
916 }
917
918 pub fn load(&self) -> Result<Settings, SettingsError> {
923 self.cleanup_stale_temp_files();
926
927 if !self.path.exists() {
928 return Ok(Settings::default());
929 }
930 let content = std::fs::read_to_string(&self.path)?;
931 let mut settings: Settings = serde_json::from_str(&content)?;
932
933 if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
938 && let Some(obj) = raw.as_object()
939 && !obj.contains_key("auto_accept_mode")
940 {
941 if let Some(val) = obj.get("auto_accept_all") {
943 if val.as_bool() == Some(true) {
944 settings.auto_accept_mode = AutoAcceptMode::All;
945 } else if val.as_bool() == Some(false) {
946 settings.auto_accept_mode = AutoAcceptMode::Off;
947 }
948 }
949 else if let Some(val) = obj.get("auto_accept_safe_commands")
952 && val.as_bool() == Some(false)
953 {
954 settings.auto_accept_mode = AutoAcceptMode::Off;
955 }
956 }
957
958 if let Ok(raw) = serde_json::from_str::<serde_json::Value>(&content)
962 && let Some(obj) = raw.as_object()
963 {
964 if settings.provider_models.is_empty()
965 && let Some(model) = obj.get("last_model")
966 && let Some(model_str) = model.as_str()
967 && !model_str.is_empty()
968 {
969 settings
970 .provider_models
971 .insert(settings.last_provider, model_str.to_string());
972 }
973 if settings.provider_urls.is_empty()
974 && let Some(url) = obj.get("last_provider_url")
975 && let Some(url_str) = url.as_str()
976 && !url_str.is_empty()
977 {
978 settings
979 .provider_urls
980 .insert(settings.last_provider, url_str.to_string());
981 }
982
983 if settings.request_timeout_secs == Some(0) {
987 settings.request_timeout_secs = None;
988 }
989
990 if settings.request_timeout_secs.is_none()
994 && let Some(timeout) = obj.get("ollama_timeout_secs").and_then(|v| v.as_u64())
995 {
996 settings.request_timeout_secs = Some(timeout);
997 }
998 if settings.request_max_retries.is_none()
999 && let Some(retries) = obj.get("ollama_max_retries").and_then(|v| v.as_u64())
1000 {
1001 settings.request_max_retries = Some(retries as u32);
1002 }
1003 }
1004
1005 Ok(settings)
1006 }
1007
1008 fn cleanup_stale_temp_files(&self) {
1014 let Some(dir) = self.path.parent() else {
1015 return;
1016 };
1017 let Ok(entries) = std::fs::read_dir(dir) else {
1018 return;
1019 };
1020 for entry in entries.flatten() {
1021 let name = entry.file_name();
1022 let name = name.to_string_lossy();
1023 if name.starts_with(".settings.json.tmp.")
1024 && let Err(e) = std::fs::remove_file(entry.path())
1025 {
1026 tracing::debug!("Could not remove stale temp file {name}: {e}");
1027 }
1028 }
1029 }
1030
1031 pub fn load_or_default(&self) -> Settings {
1038 self.load().unwrap_or_else(|e| {
1039 tracing::warn!("Failed to load settings: {e}. Using defaults.");
1040 if self.path.exists() {
1045 let backup = self.path.with_extension("json.corrupt");
1046 if let Err(backup_err) = std::fs::rename(&self.path, &backup) {
1047 tracing::warn!(
1048 "Could not back up corrupt settings to {}: {backup_err}",
1049 backup.display(),
1050 );
1051 } else {
1052 tracing::warn!("Corrupt settings backed up to {}", backup.display(),);
1053 }
1054 }
1055 Settings::default()
1056 })
1057 }
1058
1059 pub fn save(&self, settings: &Settings) -> Result<(), SettingsError> {
1066 let dir = self.path.parent().ok_or_else(|| {
1067 SettingsError::Io(std::io::Error::new(
1068 std::io::ErrorKind::InvalidInput,
1069 "settings path has no parent directory",
1070 ))
1071 })?;
1072 std::fs::create_dir_all(dir)?;
1073
1074 let json = serde_json::to_string_pretty(settings)?;
1075
1076 let tmp_name = format!(
1080 ".settings.json.tmp.{}.{}",
1081 std::process::id(),
1082 std::time::SystemTime::now()
1083 .duration_since(std::time::UNIX_EPOCH)
1084 .map(|d| d.as_nanos())
1085 .unwrap_or(0),
1086 );
1087 let tmp_path = dir.join(&tmp_name);
1088
1089 {
1091 let mut file = std::fs::File::create(&tmp_path)?;
1092 std::io::Write::write_all(&mut file, json.as_bytes())?;
1093 std::io::Write::flush(&mut file)?;
1094 file.sync_all()?;
1099 }
1100
1101 std::fs::rename(&tmp_path, &self.path)?;
1103 Ok(())
1104 }
1105
1106 pub fn path(&self) -> &std::path::Path {
1108 &self.path
1109 }
1110}
1111
1112pub fn load_settings_from(paths: &crate::paths::Paths) -> Settings {
1120 SettingsStore::from_paths(paths).load_or_default()
1121}
1122
1123pub fn load_settings() -> Settings {
1128 load_settings_from(&crate::paths::Paths::default())
1129}
1130
1131pub fn save_settings_to(
1133 paths: &crate::paths::Paths,
1134 settings: &Settings,
1135) -> Result<(), SettingsError> {
1136 SettingsStore::from_paths(paths).save(settings)
1137}
1138
1139pub fn save_settings(settings: &Settings) {
1146 if let Err(e) = save_settings_to(&crate::paths::Paths::default(), settings) {
1147 tracing::warn!("Failed to save settings: {e}");
1148 }
1149}
1150
1151pub fn update_settings_from(
1155 paths: &crate::paths::Paths,
1156 mutate: impl FnOnce(&mut Settings),
1157) -> Settings {
1158 let mut settings = load_settings_from(paths);
1159 mutate(&mut settings);
1160 if let Err(e) = save_settings_to(paths, &settings) {
1161 tracing::warn!("Failed to save settings: {e}");
1162 }
1163 settings
1164}
1165
1166pub fn resolve_project_md_files(settings: Option<&Settings>) -> Vec<String> {
1175 if let Ok(env) = std::env::var("TINYHARNESS_MD_FILES") {
1177 let files: Vec<String> = env
1178 .split(',')
1179 .map(|s| s.trim().to_string())
1180 .filter(|s| !s.is_empty())
1181 .collect();
1182 if !files.is_empty() {
1183 return files;
1184 }
1185 }
1186
1187 if let Some(s) = settings
1189 && let Some(ref configured) = s.project_md_files
1190 && !configured.is_empty()
1191 {
1192 return configured.clone();
1193 }
1194
1195 crate::context::DEFAULT_PROJECT_MD_FILE_NAMES
1197 .iter()
1198 .map(|s| s.to_string())
1199 .collect()
1200}
1201
1202pub fn prompts_dir() -> PathBuf {
1209 prompts_dir_for(&crate::paths::Paths::default())
1210}
1211
1212pub fn prompts_dir_for(paths: &crate::paths::Paths) -> PathBuf {
1214 paths.prompts_dir()
1215}
1216
1217pub fn ensure_prompts_initialized_in(dir: &Path) -> PathBuf {
1227 if !dir.exists() {
1228 std::fs::create_dir_all(dir).ok();
1229 }
1230
1231 {
1233 let header_path = dir.join("header.md");
1234 if !header_path.exists() {
1235 let header_text = include_str!("../prompts/header.md");
1236 if let Err(e) = std::fs::write(&header_path, header_text.trim()) {
1237 tracing::warn!(
1238 "Failed to write default header to {}: {e}",
1239 header_path.display(),
1240 );
1241 }
1242 }
1243 }
1244
1245 let modes = [AgentMode::Casual, AgentMode::Planning, AgentMode::Agent];
1246
1247 for mode in &modes {
1248 let file_path = dir.join(mode.prompts_filename());
1249 if !file_path.exists() {
1250 let default_text = mode.default_system_prompt();
1251 if let Err(e) = std::fs::write(&file_path, default_text.trim()) {
1253 tracing::warn!(
1254 "Failed to write default prompt to {}: {e}",
1255 file_path.display(),
1256 );
1257 }
1258 }
1259 }
1260
1261 dir.to_path_buf()
1262}
1263
1264pub fn ensure_prompts_initialized() -> PathBuf {
1273 ensure_prompts_initialized_for(&crate::paths::Paths::default())
1274}
1275
1276pub fn ensure_prompts_initialized_for(paths: &crate::paths::Paths) -> PathBuf {
1278 ensure_prompts_initialized_in(&paths.prompts_dir())
1279}
1280
1281#[cfg(test)]
1284mod tests {
1285 use super::*;
1286
1287 #[test]
1290 fn load_settings_missing_fields_uses_defaults() {
1291 let json = r#"{
1292 "last_provider": "OpenAiCompat",
1293 "last_provider_url": "http://localhost:8080/v1",
1294 "last_model": "MiniMax-M3",
1295 "preferred_mode": "Agent",
1296 "openai_compat_api_key": "sk-test",
1297 "request_timeout_secs": 5,
1298 "request_max_retries": 3,
1299 "show_thinking": true,
1300 "context_limit": 256000,
1301 "auto_accept_mode": "all",
1302 "skip_health_check": true
1303 }"#;
1304
1305 let settings: Settings =
1306 serde_json::from_str(json).expect("missing fields should use defaults");
1307 assert_eq!(settings.last_provider, ProviderKind::OpenAiCompat);
1308 assert_eq!(settings.preferred_mode, AgentMode::Agent);
1309 assert!(settings.skip_health_check);
1311 }
1312
1313 #[test]
1315 fn load_settings_empty_object_uses_all_defaults() {
1316 let settings: Settings =
1317 serde_json::from_str("{}").expect("empty object should use defaults");
1318 assert_eq!(settings.last_provider, ProviderKind::Ollama);
1319 assert_eq!(settings.preferred_mode, AgentMode::Casual);
1320 assert!(!settings.skip_health_check);
1321 }
1322
1323 #[test]
1324 fn questions_enabled_defaults_to_true() {
1325 let settings: Settings =
1326 serde_json::from_str("{}").expect("empty object should use defaults");
1327 assert!(settings.questions_enabled);
1328 assert!(settings.auto_compact_enabled);
1329 assert!(Settings::default().questions_enabled);
1330 }
1331
1332 #[test]
1333 fn questions_enabled_can_be_disabled_and_roundtrips() {
1334 let store = SettingsStore::new(temp_settings_path());
1335 let settings = Settings {
1336 questions_enabled: false,
1337 ..Settings::default()
1338 };
1339 store.save(&settings).unwrap();
1340 let loaded = store.load().unwrap();
1341 assert!(!loaded.questions_enabled);
1342 assert!(loaded.auto_compact_enabled);
1344 let _ = std::fs::remove_dir_all(store.path().parent().unwrap());
1345 }
1346
1347 #[test]
1348 fn project_settings_override_questions_enabled() {
1349 let global = Settings {
1350 questions_enabled: true,
1351 ..Settings::default()
1352 };
1353
1354 let merged = merge_settings(&global, None);
1356 assert!(merged.questions_enabled);
1357 assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1358
1359 let project = ProjectSettings {
1361 questions_enabled: Some(false),
1362 ..ProjectSettings::default()
1363 };
1364 let merged = merge_settings(&global, Some(&project));
1365 assert!(!merged.questions_enabled);
1366 assert_eq!(merged.questions_enabled_source, SettingSource::Project);
1367 }
1368
1369 #[test]
1375 fn project_settings_cannot_set_allowed_paths() {
1376 let global = Settings {
1377 allowed_paths: Some(vec!["/opt/data".to_string()]),
1378 ..Settings::default()
1379 };
1380
1381 let project: ProjectSettings =
1384 serde_json::from_str(r#"{"allowed_paths": ["/", "~"]}"#).unwrap();
1385 let merged = merge_settings(&global, Some(&project));
1386 assert_eq!(merged.allowed_paths, vec!["/opt/data".to_string()]);
1387 assert_eq!(merged.allowed_paths_source, SettingSource::Global);
1388
1389 let project: ProjectSettings =
1391 serde_json::from_str(r#"{"sandbox": {"backend": "off"}}"#).unwrap();
1392 let merged = merge_settings(&global, Some(&project));
1393 assert_eq!(merged.sandbox, global.sandbox);
1394 assert_eq!(merged.sandbox_source, SettingSource::Global);
1395 }
1396
1397 #[test]
1398 fn project_settings_questions_absent_falls_back_to_global() {
1399 let global = Settings {
1400 questions_enabled: false,
1401 ..Settings::default()
1402 };
1403 let project = ProjectSettings::default();
1404 let merged = merge_settings(&global, Some(&project));
1405 assert!(!merged.questions_enabled);
1406 assert_eq!(merged.questions_enabled_source, SettingSource::Default);
1407 }
1408
1409 #[test]
1410 fn merged_settings_produce_tool_availability() {
1411 let global = Settings {
1412 questions_enabled: false,
1413 auto_compact_enabled: true,
1414 ..Settings::default()
1415 };
1416 let availability = merge_settings(&global, None).tool_availability();
1417 assert!(!availability.question);
1418 assert!(availability.auto_compact);
1419
1420 let global = Settings::default();
1421 let availability = merge_settings(&global, None).tool_availability();
1422 assert_eq!(availability, crate::tools::ToolAvailability::all());
1423 }
1424
1425 #[test]
1426 fn discover_project_settings_parses_questions_enabled() {
1427 let tmp = tempfile::tempdir().unwrap();
1428 let dir = tmp.path().join(".tinyharness");
1429 std::fs::create_dir_all(&dir).unwrap();
1430 std::fs::write(dir.join("config.json"), r#"{"questions_enabled": false}"#).unwrap();
1431
1432 let found = discover_project_settings(tmp.path()).expect("config should be discovered");
1433 let settings = found.expect("config should parse");
1434 assert_eq!(settings.questions_enabled, Some(false));
1435 assert_eq!(settings.auto_compact_enabled, None);
1436 }
1437
1438 #[test]
1439 fn generate_project_config_template_includes_questions() {
1440 let settings = Settings {
1441 questions_enabled: false,
1442 ..Settings::default()
1443 };
1444 let template = generate_project_config_template(&settings);
1445 assert_eq!(template.questions_enabled, Some(false));
1446 assert_eq!(template.auto_compact_enabled, Some(true));
1447 }
1448
1449 #[test]
1450 fn auto_accept_mode_from_string() {
1451 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "all"}"#).unwrap();
1452 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1453
1454 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "off"}"#).unwrap();
1455 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1456
1457 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": "safe"}"#).unwrap();
1458 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1459 }
1460
1461 #[test]
1462 fn auto_accept_mode_from_legacy_bool() {
1463 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": true}"#).unwrap();
1464 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1465
1466 let settings: Settings = serde_json::from_str(r#"{"auto_accept_mode": false}"#).unwrap();
1467 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1468 }
1469 #[test]
1470 fn auto_accept_mode_from_legacy_all_field() {
1471 let store = SettingsStore::new(temp_settings_path());
1473 let json = r#"{"auto_accept_all": true}"#;
1474 std::fs::write(store.path(), json).unwrap();
1475 let settings = store.load().unwrap();
1476 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::All);
1477 let _ = std::fs::remove_file(store.path());
1478
1479 let store = SettingsStore::new(temp_settings_path());
1481 let json = r#"{"auto_accept_all": false}"#;
1482 std::fs::write(store.path(), json).unwrap();
1483 let settings = store.load().unwrap();
1484 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1485 let _ = std::fs::remove_file(store.path());
1486 }
1487 #[test]
1488 fn auto_accept_mode_from_legacy_safe_commands_field() {
1489 let store = SettingsStore::new(temp_settings_path());
1491 let json = r#"{"auto_accept_safe_commands": false}"#;
1492 std::fs::write(store.path(), json).unwrap();
1493 let settings = store.load().unwrap();
1494 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1495 let _ = std::fs::remove_file(store.path());
1496
1497 let store = SettingsStore::new(temp_settings_path());
1499 let json = r#"{"auto_accept_safe_commands": true}"#;
1500 std::fs::write(store.path(), json).unwrap();
1501 let settings = store.load().unwrap();
1502 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Safe);
1503 let _ = std::fs::remove_file(store.path());
1504 }
1505
1506 #[test]
1507 fn auto_accept_mode_explicit_overrides_legacy() {
1508 let settings: Settings =
1510 serde_json::from_str(r#"{"auto_accept_mode": "off", "auto_accept_all": true}"#)
1511 .unwrap();
1512 assert_eq!(settings.auto_accept_mode, AutoAcceptMode::Off);
1513 }
1514
1515 #[test]
1516 fn migrate_legacy_last_model_and_url() {
1517 let store = SettingsStore::new(temp_settings_path());
1518 let json = r#"{"last_provider": "Ollama", "last_model": "qwen2.5:7b", "last_provider_url": "http://localhost:11434"}"#;
1519 std::fs::write(store.path(), json).unwrap();
1520 let settings = store.load().unwrap();
1521 assert_eq!(
1522 settings.get_model_for(ProviderKind::Ollama),
1523 Some("qwen2.5:7b")
1524 );
1525 assert_eq!(
1526 settings.get_url_for(ProviderKind::Ollama),
1527 Some("http://localhost:11434")
1528 );
1529 let _ = std::fs::remove_file(store.path());
1530 }
1531
1532 #[test]
1533 fn migrate_legacy_fields_for_openai_compat() {
1534 let store = SettingsStore::new(temp_settings_path());
1535 let json = r#"{"last_provider": "OpenAiCompat", "last_model": "gpt-4o", "last_provider_url": "https://api.openai.com/v1"}"#;
1536 std::fs::write(store.path(), json).unwrap();
1537 let settings = store.load().unwrap();
1538 assert_eq!(
1539 settings.get_model_for(ProviderKind::OpenAiCompat),
1540 Some("gpt-4o")
1541 );
1542 assert_eq!(
1543 settings.get_url_for(ProviderKind::OpenAiCompat),
1544 Some("https://api.openai.com/v1")
1545 );
1546 assert_eq!(settings.get_model_for(ProviderKind::Ollama), None);
1548 let _ = std::fs::remove_file(store.path());
1549 }
1550
1551 #[test]
1552 fn per_provider_model_and_url_accessors() {
1553 let mut settings = Settings::default();
1554 settings.set_model_for(ProviderKind::Ollama, "qwen2.5:7b".to_string());
1555 settings.set_model_for(ProviderKind::LlamaCpp, "llama-3.1-8b".to_string());
1556 settings.set_url_for(ProviderKind::LlamaCpp, "http://localhost:8080".to_string());
1557
1558 assert_eq!(
1559 settings.get_model_for(ProviderKind::Ollama),
1560 Some("qwen2.5:7b")
1561 );
1562 assert_eq!(
1563 settings.get_model_for(ProviderKind::LlamaCpp),
1564 Some("llama-3.1-8b")
1565 );
1566 assert_eq!(settings.get_model_for(ProviderKind::Vllm), None);
1567 assert_eq!(
1568 settings.get_url_for(ProviderKind::LlamaCpp),
1569 Some("http://localhost:8080")
1570 );
1571 assert_eq!(settings.get_url_for(ProviderKind::Ollama), None);
1572 }
1573
1574 #[test]
1575 fn get_current_model_and_url_use_last_provider() {
1576 let mut settings = Settings {
1577 last_provider: ProviderKind::OpenAiCompat,
1578 ..Settings::default()
1579 };
1580 settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1581 settings.set_url_for(
1582 ProviderKind::OpenAiCompat,
1583 "https://api.openai.com/v1".to_string(),
1584 );
1585
1586 assert_eq!(settings.get_current_model(), Some("gpt-4o"));
1587 assert_eq!(
1588 settings.get_current_url(),
1589 Some("https://api.openai.com/v1")
1590 );
1591 }
1592
1593 fn temp_settings_path() -> std::path::PathBuf {
1594 let mut dir = std::env::temp_dir();
1598 dir.push(format!(
1599 "tinyharness_test_{}_{}_{:?}",
1600 std::process::id(),
1601 std::time::SystemTime::now()
1602 .duration_since(std::time::UNIX_EPOCH)
1603 .map(|d| d.as_nanos())
1604 .unwrap_or(0),
1605 std::thread::current().id()
1606 ));
1607 std::fs::create_dir_all(&dir).unwrap();
1608 dir.push("settings.json");
1609 dir
1610 }
1611
1612 #[test]
1616 fn save_and_load_roundtrip() {
1617 let store = SettingsStore::new(temp_settings_path());
1618 let mut settings = Settings {
1619 last_provider: ProviderKind::OpenAiCompat,
1620 auto_accept_mode: AutoAcceptMode::All,
1621 ..Settings::default()
1622 };
1623 settings.set_model_for(ProviderKind::OpenAiCompat, "gpt-4o".to_string());
1624
1625 store.save(&settings).unwrap();
1626 let loaded = store.load().unwrap();
1627 assert_eq!(loaded.last_provider, ProviderKind::OpenAiCompat);
1628 assert_eq!(
1629 loaded.get_model_for(ProviderKind::OpenAiCompat),
1630 Some("gpt-4o")
1631 );
1632 assert_eq!(loaded.auto_accept_mode, AutoAcceptMode::All);
1633
1634 let dir = store.path().parent().unwrap();
1636 let _ = std::fs::remove_dir_all(dir);
1637 }
1638
1639 #[test]
1642 fn corrupt_settings_backed_up_and_defaults_returned() {
1643 let store = SettingsStore::new(temp_settings_path());
1644 let corrupt_json = "{ this is not valid json !!!";
1645 std::fs::write(store.path(), corrupt_json).unwrap();
1646
1647 let settings = store.load_or_default();
1648 assert_eq!(settings.last_provider, ProviderKind::Ollama);
1649 assert_eq!(settings.preferred_mode, AgentMode::Casual);
1650
1651 assert!(!store.path().exists());
1653 let backup = store.path().with_extension("json.corrupt");
1654 assert!(backup.exists(), "corrupt settings should be backed up");
1655
1656 let backup_content = std::fs::read_to_string(&backup).unwrap();
1658 assert_eq!(backup_content, corrupt_json);
1659
1660 let dir = store.path().parent().unwrap();
1662 let _ = std::fs::remove_dir_all(dir);
1663 }
1664
1665 #[test]
1667 fn stale_temp_files_cleaned_up_on_load() {
1668 let store = SettingsStore::new(temp_settings_path());
1669 let dir = store.path().parent().unwrap();
1670 let tmp1 = dir.join(".settings.json.tmp.12345.999999999");
1671 let tmp2 = dir.join(".settings.json.tmp.67890.888888888");
1672 std::fs::write(&tmp1, "stale data").unwrap();
1673 std::fs::write(&tmp2, "more stale data").unwrap();
1674 assert!(tmp1.exists());
1675 assert!(tmp2.exists());
1676
1677 let _ = store.load();
1679
1680 assert!(!tmp1.exists(), "stale temp file should be removed");
1681 assert!(!tmp2.exists(), "stale temp file should be removed");
1682
1683 let _ = std::fs::remove_dir_all(dir);
1685 }
1686
1687 #[test]
1689 fn save_leaves_no_temp_files() {
1690 let store = SettingsStore::new(temp_settings_path());
1691 store.save(&Settings::default()).unwrap();
1692
1693 let dir = store.path().parent().unwrap();
1694 let entries = std::fs::read_dir(dir).unwrap();
1695 for entry in entries.flatten() {
1696 let name = entry.file_name();
1697 assert!(
1698 !name.to_string_lossy().starts_with(".settings.json.tmp."),
1699 "no temp files should remain after successful save"
1700 );
1701 }
1702
1703 let _ = std::fs::remove_dir_all(dir);
1704 }
1705
1706 #[test]
1708 fn multiple_saves_are_consistent() {
1709 let store = SettingsStore::new(temp_settings_path());
1710
1711 for i in 0..10 {
1712 let settings = Settings {
1713 request_timeout_secs: Some(i),
1714 ..Settings::default()
1715 };
1716 store.save(&settings).unwrap();
1717 }
1718
1719 let loaded = store.load().unwrap();
1720 assert_eq!(loaded.request_timeout_secs, Some(9));
1721
1722 let dir = store.path().parent().unwrap();
1723 let _ = std::fs::remove_dir_all(dir);
1724 }
1725
1726 #[test]
1731 fn migrate_legacy_ollama_timeout_and_retries() {
1732 let store = SettingsStore::new(temp_settings_path());
1733 let json =
1734 r#"{"last_provider": "Ollama", "ollama_timeout_secs": 42, "ollama_max_retries": 7}"#;
1735 std::fs::write(store.path(), json).unwrap();
1736 let settings = store.load().unwrap();
1737 assert_eq!(settings.request_timeout_secs, Some(42));
1738 assert_eq!(settings.request_max_retries, Some(7));
1739 let _ = std::fs::remove_file(store.path());
1740 }
1741
1742 #[test]
1744 fn migrate_legacy_timeout_does_not_override_new_fields() {
1745 let store = SettingsStore::new(temp_settings_path());
1746 let json = r#"{"last_provider": "Ollama", "ollama_timeout_secs": 42, "ollama_max_retries": 7, "request_timeout_secs": 99}"#;
1747 std::fs::write(store.path(), json).unwrap();
1748 let settings = store.load().unwrap();
1749 assert_eq!(settings.request_timeout_secs, Some(99));
1750 assert_eq!(settings.request_max_retries, Some(7));
1751 let _ = std::fs::remove_file(store.path());
1752 }
1753
1754 #[test]
1757 fn effective_timeout_retries_defaults_per_provider() {
1758 let mut settings = Settings {
1759 last_provider: ProviderKind::Ollama,
1760 ..Settings::default()
1761 };
1762 assert_eq!(settings.effective_timeout_secs(), 5);
1763 assert_eq!(settings.effective_max_retries(), 3);
1764
1765 settings.last_provider = ProviderKind::OpenAiCompat;
1766 assert_eq!(settings.effective_timeout_secs(), 30);
1767 assert_eq!(settings.effective_max_retries(), 0);
1768
1769 settings.last_provider = ProviderKind::Sockudo;
1770 assert_eq!(settings.effective_timeout_secs(), 120);
1771 assert_eq!(settings.effective_max_retries(), 0);
1772
1773 settings.request_timeout_secs = Some(0);
1776 settings.last_provider = ProviderKind::OpenAiCompat;
1777 assert_eq!(settings.effective_timeout_secs(), 30);
1778 settings.last_provider = ProviderKind::Ollama;
1779 assert_eq!(settings.effective_timeout_secs(), 5);
1780 settings.request_timeout_secs = Some(60);
1781 assert_eq!(settings.effective_timeout_secs(), 60);
1782
1783 settings.request_timeout_secs = Some(60);
1785 settings.request_max_retries = Some(2);
1786 assert_eq!(settings.effective_timeout_secs(), 60);
1787 assert_eq!(settings.effective_max_retries(), 2);
1788 }
1789}