Skip to main content

visdom_cli/
interactive.rs

1//! Asking for what `visdom init` was not told on the command line. Only ever
2//! used when both stdin and stderr are a terminal; without one, init behaves
3//! as if nothing could be asked and says what to pass instead.
4
5use std::io::{BufRead, IsTerminal, Write};
6use std::path::Path;
7
8use tracevault_cli::agent::Agent;
9
10use crate::mode::TracingMode;
11
12/// Whether there is somebody to ask.
13pub fn is_interactive() -> bool {
14    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
15}
16
17/// Print `question` and read one line, trimmed. `None` at end of input.
18fn 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
28/// The agent an answer names: its number in the list, or its name. An empty
29/// answer takes the default, Claude Code. `None` when it names neither.
30pub 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
38/// Ask which agent to set up. End of input takes the default.
39pub 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
51/// What `visdom init` sets up.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53pub enum InitScope {
54    /// The repository `visdom init` is run in.
55    Repo,
56    /// Every session of the agent on this machine (`--global`).
57    Machine,
58    /// The directory `visdom init` is run in, as a folder of checkouts
59    /// recorded to one project (`--workspace`).
60    Workspace,
61}
62
63/// The scope an answer names: its number in the list, or its name. An empty
64/// answer takes `default`. `None` when it names none.
65pub fn parse_scope_choice(answer: &str, default: InitScope) -> Option<InitScope> {
66    match answer.trim().to_ascii_lowercase().as_str() {
67        "" => Some(default),
68        "1" | "repo" | "repository" => Some(InitScope::Repo),
69        "2" | "machine" | "global" => Some(InitScope::Machine),
70        "3" | "workspace" | "folder" => Some(InitScope::Workspace),
71        _ => None,
72    }
73}
74
75/// Ask what to set up. `None` at end of input: nothing chosen.
76pub fn ask_scope(default: InitScope) -> Option<InitScope> {
77    let number = match default {
78        InitScope::Repo => 1,
79        InitScope::Machine => 2,
80        InitScope::Workspace => 3,
81    };
82    eprintln!("What should visdom set up?");
83    eprintln!("  [1] this repository");
84    eprintln!("  [2] every session on this machine");
85    eprintln!("  [3] this folder of checkouts, recorded to one project (a workspace)");
86    loop {
87        let answer = ask_line(&format!("Number (default {number}):"))?;
88        match parse_scope_choice(&answer, default) {
89            Some(scope) => return Some(scope),
90            None => eprintln!("Answer 1, 2 or 3."),
91        }
92    }
93}
94
95/// Ask for a line of text; `None` when nothing was typed.
96pub fn ask_text(question: &str) -> Option<String> {
97    ask_line(question).filter(|answer| !answer.is_empty())
98}
99
100/// The mode an answer names: its number in the list, or its name. An empty
101/// answer takes the default, hooks. `None` when it names neither.
102pub fn parse_mode_choice(answer: &str) -> Option<TracingMode> {
103    match answer.trim().to_ascii_lowercase().as_str() {
104        "" | "1" | "hooks" => Some(TracingMode::Hooks),
105        "2" | "gateway" => Some(TracingMode::Gateway),
106        _ => None,
107    }
108}
109
110/// Ask how sessions should be traced. `None` at end of input: nothing chosen.
111pub fn ask_mode() -> Option<TracingMode> {
112    loop {
113        let answer = ask_line(
114            "How should your sessions be traced? [1] hooks  [2] through the AI Gateway  (default 1):",
115        )?;
116        match parse_mode_choice(&answer) {
117            Some(mode) => return Some(mode),
118            None => eprintln!("Answer 1 or 2."),
119        }
120    }
121}
122
123/// The entry of a list of `count` an answer names by its number, from 1.
124pub fn parse_choice(answer: &str, count: usize) -> Option<usize> {
125    let n: usize = answer.trim().parse().ok()?;
126    (1..=count).contains(&n).then(|| n - 1)
127}
128
129/// Ask for one of `options`. `None` at end of input, or with nothing to
130/// choose from.
131pub fn ask_choice(question: &str, options: &[String]) -> Option<usize> {
132    if options.is_empty() {
133        return None;
134    }
135    eprintln!("{question}");
136    for (i, option) in options.iter().enumerate() {
137        eprintln!("  [{}] {option}", i + 1);
138    }
139    loop {
140        let answer = ask_line("Number:")?;
141        match parse_choice(&answer, options.len()) {
142            Some(index) => return Some(index),
143            None => eprintln!("Answer a number from 1 to {}.", options.len()),
144        }
145    }
146}
147
148/// What a typed URL answer means.
149#[derive(Debug, PartialEq, Eq)]
150pub enum UrlAnswer {
151    Url(String),
152    /// Nothing typed.
153    Skipped,
154    Invalid,
155}
156
157/// A bare host is taken as https; anything that is then not an absolute
158/// http(s) URL is invalid.
159pub fn parse_url_answer(answer: &str) -> UrlAnswer {
160    let answer = answer.trim();
161    if answer.is_empty() {
162        return UrlAnswer::Skipped;
163    }
164    if answer.starts_with('-') {
165        return UrlAnswer::Invalid;
166    }
167    let candidate = if answer.contains("://") {
168        answer.to_string()
169    } else {
170        format!("https://{answer}")
171    };
172    if crate::components::bazaar::is_http_url(&candidate) {
173        UrlAnswer::Url(candidate.trim_end_matches('/').to_string())
174    } else {
175        UrlAnswer::Invalid
176    }
177}
178
179/// Ask for a URL until one is given or the question is skipped (Enter, or
180/// end of input).
181pub fn ask_url(question: &str) -> Option<String> {
182    loop {
183        match parse_url_answer(&ask_line(question)?) {
184            UrlAnswer::Url(url) => return Some(url),
185            UrlAnswer::Skipped => return None,
186            UrlAnswer::Invalid => eprintln!("That is not an http(s) URL."),
187        }
188    }
189}
190
191/// Record `bazaar_url` in the user config at `path`, creating the file if
192/// needed and leaving everything else in it as it is.
193pub fn save_bazaar_url(path: &Path, url: &str) -> Result<(), String> {
194    save_user_setting(path, "bazaar_url", url)
195}
196
197/// Record `tracing_mode` in the user config at `path`, the same way.
198pub fn save_tracing_mode(path: &Path, mode: TracingMode) -> Result<(), String> {
199    save_user_setting(path, "tracing_mode", mode.name())
200}
201
202/// Record `key` under `[gateway]` in the user config at `path`, creating the
203/// file if needed. A file with no `[gateway]` table gets one at its end and
204/// is otherwise kept byte for byte; one that has it is rewritten from its
205/// parsed form.
206pub fn save_gateway_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
207    let existing = match std::fs::read_to_string(path) {
208        Ok(text) => text,
209        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
210        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
211    };
212    let mut table: toml::Table =
213        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
214    let value = toml::Value::String(value.to_string());
215    let updated = match table.get_mut("gateway") {
216        Some(toml::Value::Table(gateway)) => {
217            // The same setting under its other spelling (`claude-code-model`)
218            // would make the file name it twice, and then not load at all.
219            gateway.remove(&key.replace('_', "-"));
220            gateway.insert(key.to_string(), value);
221            toml::to_string(&table).map_err(|e| e.to_string())?
222        }
223        Some(_) => return Err(format!("`gateway` in {} is not a table", path.display())),
224        None => {
225            let gap = match existing.is_empty() || existing.ends_with("\n\n") {
226                true => "",
227                false if existing.ends_with('\n') => "\n",
228                false => "\n\n",
229            };
230            format!("{existing}{gap}[gateway]\n{key} = {value}\n")
231        }
232    };
233    if let Some(dir) = path.parent() {
234        std::fs::create_dir_all(dir)
235            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
236    }
237    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
238}
239
240/// Set the top-level string `key` in the user config at `path`, creating the
241/// file if needed and leaving everything else in it as it is.
242fn save_user_setting(path: &Path, key: &str, value: &str) -> Result<(), String> {
243    let existing = match std::fs::read_to_string(path) {
244        Ok(text) => text,
245        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
246        Err(e) => return Err(format!("cannot read {}: {e}", path.display())),
247    };
248    let mut table: toml::Table =
249        toml::from_str(&existing).map_err(|e| format!("cannot parse {}: {e}", path.display()))?;
250    let line = format!("{key} = {}\n", toml::Value::String(value.to_string()));
251    let updated = if table.contains_key(key) {
252        // Already there (empty, or it would not have been asked for): the
253        // file is rewritten from its parsed form.
254        table.insert(key.to_string(), toml::Value::String(value.to_string()));
255        toml::to_string(&table).map_err(|e| e.to_string())?
256    } else {
257        // A top-level key must come before the first table: put it first, and
258        // keep the rest of the file, comments included, byte for byte.
259        format!("{line}{existing}")
260    };
261    if let Some(dir) = path.parent() {
262        std::fs::create_dir_all(dir)
263            .map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
264    }
265    std::fs::write(path, updated).map_err(|e| format!("cannot write {}: {e}", path.display()))
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271    use crate::config::load_user_config_in;
272
273    #[test]
274    fn agent_choice_by_number_name_or_default() {
275        assert_eq!(parse_agent_choice(""), Some(Agent::ClaudeCode));
276        assert_eq!(parse_agent_choice("1"), Some(Agent::ClaudeCode));
277        assert_eq!(parse_agent_choice(" Claude-Code "), Some(Agent::ClaudeCode));
278        assert_eq!(parse_agent_choice("2"), Some(Agent::Codex));
279        assert_eq!(parse_agent_choice("codex"), Some(Agent::Codex));
280        assert_eq!(parse_agent_choice("3"), None);
281        assert_eq!(parse_agent_choice("amp"), None);
282    }
283
284    #[test]
285    fn mode_choice_by_number_name_or_default() {
286        assert_eq!(parse_mode_choice(""), Some(TracingMode::Hooks));
287        assert_eq!(parse_mode_choice("1"), Some(TracingMode::Hooks));
288        assert_eq!(parse_mode_choice(" Gateway "), Some(TracingMode::Gateway));
289        assert_eq!(parse_mode_choice("2"), Some(TracingMode::Gateway));
290        assert_eq!(parse_mode_choice("3"), None);
291        assert_eq!(parse_mode_choice("proxy"), None);
292    }
293
294    #[test]
295    fn the_mode_is_saved_next_to_the_other_settings() {
296        let tmp = tempfile::tempdir().unwrap();
297        let path = crate::config::user_config_path_in(tmp.path());
298        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
299        let before = "agent = \"codex\"\n\n[gateway]\nproject = \"alpha\"\n";
300        std::fs::write(&path, before).unwrap();
301        save_tracing_mode(&path, TracingMode::Gateway).unwrap();
302        assert_eq!(
303            std::fs::read_to_string(&path).unwrap(),
304            format!("tracing_mode = \"gateway\"\n{before}")
305        );
306        let user = load_user_config_in(tmp.path()).unwrap();
307        assert_eq!(user.tracing_mode, Some(TracingMode::Gateway));
308        assert_eq!(user.agent, Some(Agent::Codex));
309        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
310        // Choosing again replaces it.
311        save_tracing_mode(&path, TracingMode::Hooks).unwrap();
312        let user = load_user_config_in(tmp.path()).unwrap();
313        assert_eq!(user.tracing_mode, Some(TracingMode::Hooks));
314        assert_eq!(user.gateway.project.as_deref(), Some("alpha"));
315    }
316
317    #[test]
318    fn scope_choice_by_number_name_or_default() {
319        use InitScope::*;
320        assert_eq!(parse_scope_choice("", Machine), Some(Machine));
321        assert_eq!(parse_scope_choice("\n", Repo), Some(Repo));
322        assert_eq!(parse_scope_choice("1", Machine), Some(Repo));
323        assert_eq!(parse_scope_choice(" 2 ", Repo), Some(Machine));
324        assert_eq!(parse_scope_choice("global", Repo), Some(Machine));
325        assert_eq!(parse_scope_choice("3", Repo), Some(Workspace));
326        assert_eq!(parse_scope_choice("Workspace", Repo), Some(Workspace));
327        assert_eq!(parse_scope_choice("4", Repo), None);
328        assert_eq!(parse_scope_choice("everything", Repo), None);
329    }
330
331    #[test]
332    fn a_choice_is_a_number_of_the_list() {
333        assert_eq!(parse_choice("1", 3), Some(0));
334        assert_eq!(parse_choice(" 3\n", 3), Some(2));
335        for answer in ["0", "4", "", "alpha", "-1"] {
336            assert_eq!(parse_choice(answer, 3), None, "{answer}");
337        }
338    }
339
340    #[test]
341    fn a_gateway_setting_is_saved_without_touching_the_rest() {
342        let tmp = tempfile::tempdir().unwrap();
343        let path = tmp.path().join("visdom").join("config.toml");
344        // A new file.
345        save_gateway_setting(&path, "project", "alpha").unwrap();
346        assert_eq!(
347            std::fs::read_to_string(&path).unwrap(),
348            "[gateway]\nproject = \"alpha\"\n"
349        );
350        // A second setting, and the first one replaced.
351        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
352        save_gateway_setting(&path, "project", "beta").unwrap();
353        let user = load_user_config_in(tmp.path()).unwrap();
354        assert_eq!(user.gateway.project.as_deref(), Some("beta"));
355        assert_eq!(
356            user.gateway.claude_code_model.as_deref(),
357            Some("claude-sonnet")
358        );
359
360        // A file with no [gateway] keeps every byte, comments included.
361        let before =
362            "# mine\ntracing_mode = \"gateway\"\n\n[agents]\ncodex = \"cdx\" # local build";
363        std::fs::write(&path, before).unwrap();
364        save_gateway_setting(&path, "codex_model", "gpt-general").unwrap();
365        let after = std::fs::read_to_string(&path).unwrap();
366        assert_eq!(
367            after,
368            format!("{before}\n\n[gateway]\ncodex_model = \"gpt-general\"\n")
369        );
370        let user = load_user_config_in(tmp.path()).unwrap();
371        assert_eq!(user.gateway.codex_model.as_deref(), Some("gpt-general"));
372        assert_eq!(user.agents.codex.as_deref(), Some("cdx"));
373
374        // The other spelling of a key is replaced, not doubled.
375        std::fs::write(&path, "[gateway]\nclaude-code-model = \"\"\n").unwrap();
376        save_gateway_setting(&path, "claude_code_model", "claude-sonnet").unwrap();
377        let user = load_user_config_in(tmp.path()).unwrap();
378        assert_eq!(
379            user.gateway.claude_code_model.as_deref(),
380            Some("claude-sonnet")
381        );
382
383        // One that cannot be parsed is left alone.
384        std::fs::write(&path, "[gateway\n").unwrap();
385        assert!(save_gateway_setting(&path, "project", "alpha").is_err());
386        assert_eq!(std::fs::read_to_string(&path).unwrap(), "[gateway\n");
387    }
388
389    #[test]
390    fn url_answers() {
391        assert_eq!(parse_url_answer("  "), UrlAnswer::Skipped);
392        assert_eq!(
393            parse_url_answer("https://tv.example.com/"),
394            UrlAnswer::Url("https://tv.example.com".to_string())
395        );
396        assert_eq!(
397            parse_url_answer("tv.example.com"),
398            UrlAnswer::Url("https://tv.example.com".to_string())
399        );
400        assert_eq!(
401            parse_url_answer("http://localhost:3000/mcp/remote"),
402            UrlAnswer::Url("http://localhost:3000/mcp/remote".to_string())
403        );
404        for bad in ["ftp://x.example.com", "--flag", "two words", "https://"] {
405            assert_eq!(parse_url_answer(bad), UrlAnswer::Invalid, "{bad}");
406        }
407    }
408
409    #[test]
410    fn bazaar_url_is_saved_into_a_new_file() {
411        let tmp = tempfile::tempdir().unwrap();
412        let path = crate::config::user_config_path_in(tmp.path());
413        save_bazaar_url(&path, "https://ctx.example.com/mcp/remote").unwrap();
414        let user = load_user_config_in(tmp.path()).unwrap();
415        assert_eq!(
416            user.bazaar_url.as_deref(),
417            Some("https://ctx.example.com/mcp/remote")
418        );
419    }
420
421    #[test]
422    fn bazaar_url_is_added_without_touching_the_rest() {
423        let tmp = tempfile::tempdir().unwrap();
424        let path = crate::config::user_config_path_in(tmp.path());
425        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
426        let before = "# my settings\nagent = \"codex\"\n\n[agents]\n# the nightly build\ncodex = \"/opt/codex\"\n";
427        std::fs::write(&path, before).unwrap();
428        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
429        let after = std::fs::read_to_string(&path).unwrap();
430        assert_eq!(
431            after,
432            format!("bazaar_url = \"https://ctx.example.com/mcp\"\n{before}")
433        );
434        let user = load_user_config_in(tmp.path()).unwrap();
435        assert_eq!(user.agent, Some(Agent::Codex));
436        assert_eq!(
437            user.bazaar_url.as_deref(),
438            Some("https://ctx.example.com/mcp")
439        );
440        assert_eq!(
441            user.agents.program_for(Agent::Codex).as_deref(),
442            Some("/opt/codex")
443        );
444    }
445
446    #[test]
447    fn an_empty_bazaar_url_is_replaced() {
448        let tmp = tempfile::tempdir().unwrap();
449        let path = crate::config::user_config_path_in(tmp.path());
450        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
451        std::fs::write(&path, "bazaar_url = \"\"\nagent = \"codex\"\n").unwrap();
452        save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap();
453        let user = load_user_config_in(tmp.path()).unwrap();
454        assert_eq!(
455            user.bazaar_url.as_deref(),
456            Some("https://ctx.example.com/mcp")
457        );
458        assert_eq!(user.agent, Some(Agent::Codex));
459    }
460
461    #[test]
462    fn a_config_that_cannot_be_parsed_is_left_alone() {
463        let tmp = tempfile::tempdir().unwrap();
464        let path = crate::config::user_config_path_in(tmp.path());
465        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
466        std::fs::write(&path, "agent = [broken").unwrap();
467        let err = save_bazaar_url(&path, "https://ctx.example.com/mcp").unwrap_err();
468        assert!(err.contains("cannot parse"), "{err}");
469        assert_eq!(std::fs::read_to_string(&path).unwrap(), "agent = [broken");
470    }
471}