1use std::io::{BufRead, IsTerminal, Write};
6use std::path::Path;
7
8use tracevault_cli::agent::Agent;
9
10use crate::mode::TracingMode;
11
12pub fn is_interactive() -> bool {
14 std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
15}
16
17fn ask_line(question: &str) -> Option<String> {
19 eprint!("{question} ");
20 let _ = std::io::stderr().flush();
21 let mut line = String::new();
22 match std::io::stdin().lock().read_line(&mut line) {
23 Ok(0) | Err(_) => None,
24 Ok(_) => Some(line.trim().to_string()),
25 }
26}
27
28pub fn parse_agent_choice(answer: &str) -> Option<Agent> {
31 match answer.trim().to_ascii_lowercase().as_str() {
32 "" | "1" | "claude" | "claude-code" => Some(Agent::ClaudeCode),
33 "2" | "codex" => Some(Agent::Codex),
34 _ => None,
35 }
36}
37
38pub fn ask_agent() -> Agent {
40 loop {
41 let Some(answer) = ask_line("Which agent? [1] Claude Code [2] Codex (default 1):") else {
42 return Agent::ClaudeCode;
43 };
44 match parse_agent_choice(&answer) {
45 Some(agent) => return agent,
46 None => eprintln!("Answer 1 or 2."),
47 }
48 }
49}
50
51pub fn parse_mode_choice(answer: &str) -> Option<TracingMode> {
54 match answer.trim().to_ascii_lowercase().as_str() {
55 "" | "1" | "hooks" => Some(TracingMode::Hooks),
56 "2" | "gateway" => Some(TracingMode::Gateway),
57 _ => None,
58 }
59}
60
61pub fn ask_mode() -> Option<TracingMode> {
63 loop {
64 let answer = ask_line(
65 "How should your sessions be traced? [1] hooks [2] through the AI Gateway (default 1):",
66 )?;
67 match parse_mode_choice(&answer) {
68 Some(mode) => return Some(mode),
69 None => eprintln!("Answer 1 or 2."),
70 }
71 }
72}
73
74#[derive(Debug, PartialEq, Eq)]
76pub enum UrlAnswer {
77 Url(String),
78 Skipped,
80 Invalid,
81}
82
83pub fn parse_url_answer(answer: &str) -> UrlAnswer {
86 let answer = answer.trim();
87 if answer.is_empty() {
88 return UrlAnswer::Skipped;
89 }
90 if answer.starts_with('-') {
91 return UrlAnswer::Invalid;
92 }
93 let candidate = if answer.contains("://") {
94 answer.to_string()
95 } else {
96 format!("https://{answer}")
97 };
98 if crate::components::bazaar::is_http_url(&candidate) {
99 UrlAnswer::Url(candidate.trim_end_matches('/').to_string())
100 } else {
101 UrlAnswer::Invalid
102 }
103}
104
105pub fn ask_url(question: &str) -> Option<String> {
108 loop {
109 match parse_url_answer(&ask_line(question)?) {
110 UrlAnswer::Url(url) => return Some(url),
111 UrlAnswer::Skipped => return None,
112 UrlAnswer::Invalid => eprintln!("That is not an http(s) URL."),
113 }
114 }
115}
116
117pub fn save_bazaar_url(path: &Path, url: &str) -> Result<(), String> {
120 save_user_setting(path, "bazaar_url", url)
121}
122
123pub fn save_tracing_mode(path: &Path, mode: TracingMode) -> Result<(), String> {
125 save_user_setting(path, "tracing_mode", mode.name())
126}
127
128fn save_user_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
131 let existing = match std::fs::read_to_string(path) {
132 Ok(text) => text,
133 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
134 Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
135 };
136 let mut table: toml::Table =
137 toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
138 let line = format!("{key} = {}\n", toml::Value::String(value.to_string()));
139 let updated = if table.contains_key(key) {
140 table.insert(key.to_string(), toml::Value::String(value.to_string()));
143 toml::to_string(&table).map_err(|e| e.to_string())?
144 } else {
145 format!("{line}{existing}")
148 };
149 if let Some(dir) = path.parent() {
150 std::fs::create_dir_all(dir)
151 .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
152 }
153 std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
154}
155
156#[cfg(test)]
157mod tests {
158 use super::*;
159 use crate::config::load_user_config_in;
160
161 #[test]
162 fn agent_choice_by_number_name_or_default() {
163 assert_eq!(parse_agent_choice(""), Some(Agent::ClaudeCode));
164 assert_eq!(parse_agent_choice("1"), Some(Agent::ClaudeCode));
165 assert_eq!(parse_agent_choice(" Claude-Code "), Some(Agent::ClaudeCode));
166 assert_eq!(parse_agent_choice("2"), Some(Agent::Codex));
167 assert_eq!(parse_agent_choice("codex"), Some(Agent::Codex));
168 assert_eq!(parse_agent_choice("3"), None);
169 assert_eq!(parse_agent_choice("amp"), None);
170 }
171
172 #[test]
173 fn mode_choice_by_number_name_or_default() {
174 assert_eq!(parse_mode_choice(""), Some(TracingMode::Hooks));
175 assert_eq!(parse_mode_choice("1"), Some(TracingMode::Hooks));
176 assert_eq!(parse_mode_choice(" Gateway "), Some(TracingMode::Gateway));
177 assert_eq!(parse_mode_choice("2"), Some(TracingMode::Gateway));
178 assert_eq!(parse_mode_choice("3"), None);
179 assert_eq!(parse_mode_choice("proxy"), None);
180 }
181
182 #[test]
183 fn the_mode_is_saved_next_to_the_other_settings() {
184 let tmp = tempfile::tempdir().unwrap();
185 let path = crate::config::user_config_path_in(tmp.path());
186 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
187 let before = "agent = \"codex\"\n\n[gateway]\nproject = \"alpha\"\n";
188 std::fs::write(&path, before).unwrap();
189 save_tracing_mode(&path, TracingMode::Gateway).unwrap();
190 assert_eq!(
191 std::fs::read_to_string(&path).unwrap(),
192 format!("tracing_mode = \"gateway\"\n{before}")
193 );
194 let user = load_user_config_in(tmp.path()).unwrap();
195 assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
196 assert_eq!(user.agent, Some(Agent::Codex));
197 assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
198 save_tracing_mode(&path, TracingMode::Hooks).unwrap();
200 let user = load_user_config_in(tmp.path()).unwrap();
201 assert_eq!(user.tracing_mode, Some(TracingMode::Hooks));
202 assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
203 }
204
205 #[test]
206 fn url_answers() {
207 assert_eq!(parse_url_answer(" "), UrlAnswer::Skipped);
208 assert_eq!(
209 parse_url_answer("https://tv.example.com/"),
210 UrlAnswer::Url("https://tv.example.com".to_string())
211 );
212 assert_eq!(
213 parse_url_answer("tv.example.com"),
214 UrlAnswer::Url("https://tv.example.com".to_string())
215 );
216 assert_eq!(
217 parse_url_answer("http://localhost:3000/mcp/remote"),
218 UrlAnswer::Url("http://localhost:3000/mcp/remote".to_string())
219 );
220 for bad in ["ftp://x.example.com", "--flag", "two words", "https://"] {
221 assert_eq!(parse_url_answer(bad), UrlAnswer::Invalid, "{bad}");
222 }
223 }
224
225 #[test]
226 fn bazaar_url_is_saved_into_a_new_file() {
227 let tmp = tempfile::tempdir().unwrap();
228 let path = crate::config::user_config_path_in(tmp.path());
229 save_bazaar_url(&path, "https://ctx.example.com/mcp/remote").unwrap();
230 let user = load_user_config_in(tmp.path()).unwrap();
231 assert_eq!(
232 user.bazaar_url.as_deref(),
233 Some("https://ctx.example.com/mcp/remote")
234 );
235 }
236
237 #[test]
238 fn bazaar_url_is_added_without_touching_the_rest() {
239 let tmp = tempfile::tempdir().unwrap();
240 let path = crate::config::user_config_path_in(tmp.path());
241 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
242 let before = "# my settings\nagent = \"codex\"\n\n[agents]\n# the nightly build\ncodex = \"/opt/codex\"\n";
243 std::fs::write(&path, before).unwrap();
244 save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
245 let after = std::fs::read_to_string(&path).unwrap();
246 assert_eq!(
247 after,
248 format!("bazaar_url = \"https://ctx.example.com/mcp\"\n{before}")
249 );
250 let user = load_user_config_in(tmp.path()).unwrap();
251 assert_eq!(user.agent, Some(Agent::Codex));
252 assert_eq!(
253 user.bazaar_url.as_deref(),
254 Some("https://ctx.example.com/mcp")
255 );
256 assert_eq!(
257 user.agents.program_for(Agent::Codex).as_deref(),
258 Some("/opt/codex")
259 );
260 }
261
262 #[test]
263 fn an_empty_bazaar_url_is_replaced() {
264 let tmp = tempfile::tempdir().unwrap();
265 let path = crate::config::user_config_path_in(tmp.path());
266 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
267 std::fs::write(&path, "bazaar_url = \"\"\nagent = \"codex\"\n").unwrap();
268 save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
269 let user = load_user_config_in(tmp.path()).unwrap();
270 assert_eq!(
271 user.bazaar_url.as_deref(),
272 Some("https://ctx.example.com/mcp")
273 );
274 assert_eq!(user.agent, Some(Agent::Codex));
275 }
276
277 #[test]
278 fn a_config_that_cannot_be_parsed_is_left_alone() {
279 let tmp = tempfile::tempdir().unwrap();
280 let path = crate::config::user_config_path_in(tmp.path());
281 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
282 std::fs::write(&path, "agent = [broken").unwrap();
283 let err = save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap_err();
284 assert!(err.contains("cannot parse"), "{err}");
285 assert_eq!(std::fs::read_to_string(&path).unwrap(), "agent = [broken");
286 }
287}