Skip to main content

ai_usagebar/tui/
settings.rs

1//! Settings overlay — opened from the TUI by pressing `s`. Lets the user pick
2//! the primary vendor and paste an API key for any key-authenticated vendor
3//! (including Z.AI, Kimi, MiniMax, and the balance vendors) without hand-editing
4//! config.toml. Anthropic, OpenAI, Cursor, and Antigravity authenticate through
5//! local product state, so they have no key field here.
6//!
7//! Persistence uses `toml_edit` so the existing config keeps its comments,
8//! whitespace, and unrelated fields. Writing a key also flips that vendor's
9//! `enabled = true` (the opt-in vendors are disabled by default), so "paste the
10//! key and save" is all it takes. Files with inline keys are atomically written
11//! and `chmod 600`ed.
12
13use std::path::{Path, PathBuf};
14
15use ratatui::Frame;
16use ratatui::layout::{Constraint, Direction, Layout, Rect};
17use ratatui::style::Modifier;
18use ratatui::text::{Line, Span};
19use ratatui::widgets::{Clear, Paragraph};
20use ratatui_bubbletea_theme::BubbleTheme;
21use toml_edit::{DocumentMut, value};
22
23use crate::config::Config;
24use crate::error::{AppError, Result};
25use crate::theme::Theme;
26use crate::tui::style::bubble_theme;
27use crate::vendor::VendorId;
28
29/// A vendor that authenticates with an inline API key (vs. OAuth). The order of
30/// this table is the tab order of the key fields and the layout of the state's
31/// `keys` vec.
32pub struct KeyVendor {
33    pub id: VendorId,
34    pub label: &'static str,
35    pub env: &'static str,
36    pub section: &'static str,
37    /// Extra hint after the env var (e.g. "management key"). Empty for none.
38    pub note: &'static str,
39}
40
41pub const KEY_VENDORS: &[KeyVendor] = &[
42    KeyVendor {
43        id: VendorId::AnthropicApi,
44        label: "Anthropic API",
45        env: "ANTHROPIC_ADMIN_KEY",
46        section: "anthropic_api",
47        note: "admin key — monthly spend",
48    },
49    KeyVendor {
50        id: VendorId::Zai,
51        label: "Z.AI",
52        env: "ZAI_API_KEY",
53        section: "zai",
54        note: "",
55    },
56    KeyVendor {
57        id: VendorId::Openrouter,
58        label: "OpenRouter",
59        env: "OPENROUTER_API_KEY",
60        section: "openrouter",
61        note: "",
62    },
63    KeyVendor {
64        id: VendorId::Deepseek,
65        label: "DeepSeek",
66        env: "DEEPSEEK_API_KEY",
67        section: "deepseek",
68        note: "",
69    },
70    KeyVendor {
71        id: VendorId::Kimi,
72        label: "Kimi",
73        env: "KIMI_API_KEY",
74        section: "kimi",
75        note: "coding-plan usage",
76    },
77    KeyVendor {
78        id: VendorId::Kilo,
79        label: "Kilo",
80        env: "KILO_API_KEY",
81        section: "kilo",
82        note: "",
83    },
84    KeyVendor {
85        id: VendorId::Novita,
86        label: "Novita",
87        env: "NOVITA_API_KEY",
88        section: "novita",
89        note: "",
90    },
91    KeyVendor {
92        id: VendorId::Moonshot,
93        label: "Moonshot",
94        env: "MOONSHOT_API_KEY",
95        section: "moonshot",
96        note: "account balance",
97    },
98    KeyVendor {
99        id: VendorId::Grok,
100        label: "Grok",
101        env: "XAI_MANAGEMENT_KEY",
102        section: "grok",
103        note: "management key, not the inference key",
104    },
105    KeyVendor {
106        id: VendorId::Minimax,
107        label: "MiniMax",
108        env: "MINIMAX_API_KEY",
109        section: "minimax",
110        note: "Token Plan subscription key",
111    },
112];
113
114/// Read the inline `api_key` currently in config for a given section, so the
115/// field opens pre-filled (masked) when one is already set.
116fn config_inline_key<'a>(cfg: &'a Config, section: &str) -> Option<&'a str> {
117    match section {
118        "anthropic_api" => cfg.anthropic_api.api_key.as_deref(),
119        "zai" => cfg.zai.api_key.as_deref(),
120        "openrouter" => cfg.openrouter.api_key.as_deref(),
121        "deepseek" => cfg.deepseek.api_key.as_deref(),
122        "kimi" => cfg.kimi.api_key.as_deref(),
123        "kilo" => cfg.kilo.api_key.as_deref(),
124        "novita" => cfg.novita.api_key.as_deref(),
125        "moonshot" => cfg.moonshot.api_key.as_deref(),
126        "grok" => cfg.grok.api_key.as_deref(),
127        "minimax" => cfg.minimax.api_key.as_deref(),
128        _ => None,
129    }
130}
131
132/// Which control has keyboard focus. `Key(i)` indexes into [`KEY_VENDORS`].
133#[derive(Debug, Clone, Copy, PartialEq, Eq)]
134pub enum Focus {
135    Primary,
136    Key(usize),
137    Save,
138}
139
140impl Focus {
141    pub fn next(self) -> Self {
142        match self {
143            Focus::Primary => Focus::Key(0),
144            Focus::Key(i) if i + 1 < KEY_VENDORS.len() => Focus::Key(i + 1),
145            Focus::Key(_) => Focus::Save,
146            Focus::Save => Focus::Primary,
147        }
148    }
149    pub fn prev(self) -> Self {
150        match self {
151            Focus::Primary => Focus::Save,
152            Focus::Key(0) => Focus::Primary,
153            Focus::Key(i) => Focus::Key(i - 1),
154            Focus::Save => Focus::Key(KEY_VENDORS.len() - 1),
155        }
156    }
157}
158
159/// Per-field text-input state — cursor + buffer + reveal flag.
160#[derive(Debug, Clone, Default)]
161pub struct KeyInput {
162    pub buf: String,
163    /// Char-index cursor position (0..=buf.chars().count()).
164    pub cursor: usize,
165    /// When true, the field renders the actual characters; otherwise `•`.
166    pub revealed: bool,
167    /// True after the user has typed/edited; only then does save write the
168    /// value back (avoids clobbering an existing key with the empty
169    /// placeholder the user opened the dialog with).
170    pub dirty: bool,
171}
172
173impl KeyInput {
174    pub fn from_config(initial: Option<&str>) -> Self {
175        let buf = initial.unwrap_or("").to_string();
176        let cursor = buf.chars().count();
177        Self {
178            buf,
179            cursor,
180            revealed: false,
181            dirty: false,
182        }
183    }
184
185    pub fn insert_char(&mut self, c: char) {
186        let byte_idx = self.char_to_byte(self.cursor);
187        self.buf.insert(byte_idx, c);
188        self.cursor += 1;
189        self.dirty = true;
190    }
191
192    pub fn backspace(&mut self) {
193        if self.cursor == 0 {
194            return;
195        }
196        let prev_byte = self.char_to_byte(self.cursor - 1);
197        let cur_byte = self.char_to_byte(self.cursor);
198        self.buf.replace_range(prev_byte..cur_byte, "");
199        self.cursor -= 1;
200        self.dirty = true;
201    }
202
203    pub fn delete(&mut self) {
204        let n = self.buf.chars().count();
205        if self.cursor >= n {
206            return;
207        }
208        let cur_byte = self.char_to_byte(self.cursor);
209        let next_byte = self.char_to_byte(self.cursor + 1);
210        self.buf.replace_range(cur_byte..next_byte, "");
211        self.dirty = true;
212    }
213
214    pub fn move_left(&mut self) {
215        if self.cursor > 0 {
216            self.cursor -= 1;
217        }
218    }
219    pub fn move_right(&mut self) {
220        if self.cursor < self.buf.chars().count() {
221            self.cursor += 1;
222        }
223    }
224    pub fn move_home(&mut self) {
225        self.cursor = 0;
226    }
227    pub fn move_end(&mut self) {
228        self.cursor = self.buf.chars().count();
229    }
230    pub fn toggle_reveal(&mut self) {
231        self.revealed = !self.revealed;
232    }
233
234    /// Render for display — bullets when masked, raw chars when revealed.
235    pub fn display(&self) -> String {
236        if self.revealed {
237            self.buf.clone()
238        } else {
239            "•".repeat(self.buf.chars().count())
240        }
241    }
242
243    fn char_to_byte(&self, char_idx: usize) -> usize {
244        self.buf
245            .char_indices()
246            .map(|(b, _)| b)
247            .chain(std::iter::once(self.buf.len()))
248            .nth(char_idx)
249            .unwrap_or(self.buf.len())
250    }
251}
252
253/// Mutable state of the overlay while open.
254#[derive(Debug, Clone)]
255pub struct SettingsState {
256    pub focus: Focus,
257    /// Enabled vendors only. The primary selector must not offer a value that
258    /// cannot actually be used by the widget or TUI.
259    pub primary_choices: Vec<VendorId>,
260    pub primary: VendorId,
261    /// One input per [`KEY_VENDORS`] entry, same order.
262    pub keys: Vec<KeyInput>,
263    /// One-line status displayed in the footer ("saved …", "save failed …").
264    pub status: String,
265}
266
267impl SettingsState {
268    pub fn from_config(cfg: &Config) -> Self {
269        let keys = KEY_VENDORS
270            .iter()
271            .map(|kv| KeyInput::from_config(config_inline_key(cfg, kv.section)))
272            .collect();
273        let primary_choices = cfg.enabled_vendors();
274        // A configured but disabled primary is ineffective. Display the first
275        // enabled vendor instead; when none are enabled retain the historical
276        // Anthropic fallback in memory without inventing a persisted primary.
277        let primary = cfg
278            .ui
279            .primary
280            .filter(|vendor| primary_choices.contains(vendor))
281            .or_else(|| primary_choices.first().copied())
282            .unwrap_or_else(|| cfg.ui.primary.unwrap_or(VendorId::Anthropic));
283        Self {
284            focus: Focus::Primary,
285            primary_choices,
286            primary,
287            keys,
288            status: String::new(),
289        }
290    }
291
292    /// The focused key input, if a key row is focused.
293    fn focused_key_mut(&mut self) -> Option<&mut KeyInput> {
294        match self.focus {
295            Focus::Key(i) => self.keys.get_mut(i),
296            _ => None,
297        }
298    }
299}
300
301/// What the key handler asks the host app to do next.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303pub enum Action {
304    /// Stay open, keep listening for keys.
305    Continue,
306    /// Close the overlay (discard or save already happened).
307    Close,
308    /// Save just succeeded — caller should refresh affected vendors.
309    SavedAndClose,
310    /// Quit the host TUI. Ctrl-C remains global even while the overlay owns
311    /// keyboard focus.
312    Quit,
313}
314
315/// Permission note appended to the "saved" status line. The overlay `chmod
316/// 600`s the file on Unix; Windows has no such step, so the note is empty there.
317#[cfg(unix)]
318const PERMS_NOTE: &str = " (chmod 600)";
319#[cfg(not(unix))]
320const PERMS_NOTE: &str = "";
321
322fn saved_status() -> String {
323    format!(
324        "saved to {}{}",
325        crate::config::config_path_hint(),
326        PERMS_NOTE
327    )
328}
329
330/// Key map. Returns the action to perform after the keypress.
331pub fn handle_key(state: &mut SettingsState, code: KeyCode, mods: KeyModifiers) -> Action {
332    if matches!(code, KeyCode::Esc) {
333        return Action::Close;
334    }
335    if matches!(code, KeyCode::Char('c')) && mods.contains(KeyModifiers::CONTROL) {
336        return Action::Quit;
337    }
338    // Ctrl-S triggers save from any field.
339    if matches!(code, KeyCode::Char('s')) && mods.contains(KeyModifiers::CONTROL) {
340        return try_save(state);
341    }
342    if matches!(code, KeyCode::Char('v')) && mods.contains(KeyModifiers::CONTROL) {
343        if let Some(input) = state.focused_key_mut() {
344            input.toggle_reveal();
345        }
346        return Action::Continue;
347    }
348    match code {
349        KeyCode::Tab | KeyCode::Down => {
350            state.focus = state.focus.next();
351            return Action::Continue;
352        }
353        KeyCode::BackTab | KeyCode::Up => {
354            state.focus = state.focus.prev();
355            return Action::Continue;
356        }
357        _ => {}
358    }
359
360    // A modifier chord is not text. The overlay swallows every key while open,
361    // so every unhandled chord must be ignored rather than corrupting the
362    // secret silently. SHIFT is deliberately not rejected — it is how
363    // uppercase arrives. Ctrl-C was handled above because it is a global quit.
364    if matches!(code, KeyCode::Char(_))
365        && mods.intersects(
366            KeyModifiers::CONTROL
367                | KeyModifiers::ALT
368                | KeyModifiers::SUPER
369                | KeyModifiers::HYPER
370                | KeyModifiers::META,
371        )
372    {
373        return Action::Continue;
374    }
375
376    // Field-specific handling.
377    match state.focus {
378        Focus::Primary => handle_primary(state, code),
379        Focus::Key(i) => {
380            if let Some(input) = state.keys.get_mut(i) {
381                handle_input(input, code);
382            }
383        }
384        Focus::Save => {
385            if matches!(code, KeyCode::Enter) {
386                return try_save(state);
387            }
388        }
389    }
390    Action::Continue
391}
392
393fn try_save(state: &mut SettingsState) -> Action {
394    match save_to_config_default(state) {
395        Ok(()) => {
396            state.status = saved_status();
397            Action::SavedAndClose
398        }
399        Err(e) => {
400            state.status = format!("save failed: {e}");
401            Action::Continue
402        }
403    }
404}
405
406fn handle_primary(state: &mut SettingsState, code: KeyCode) {
407    // Left/Right cycles the primary-vendor radio over enabled vendors only.
408    let choices = &state.primary_choices;
409    let Some(idx) = choices.iter().position(|v| *v == state.primary) else {
410        return;
411    };
412    let step = match code {
413        KeyCode::Left => -1,
414        KeyCode::Right | KeyCode::Char(' ') => 1,
415        _ => return,
416    };
417    state.primary = choices[((idx as i32 + step).rem_euclid(choices.len() as i32)) as usize];
418}
419
420fn handle_input(input: &mut KeyInput, code: KeyCode) {
421    match code {
422        KeyCode::Char(c) => input.insert_char(c),
423        KeyCode::Backspace => input.backspace(),
424        KeyCode::Delete => input.delete(),
425        KeyCode::Left => input.move_left(),
426        KeyCode::Right => input.move_right(),
427        KeyCode::Home => input.move_home(),
428        KeyCode::End => input.move_end(),
429        _ => {}
430    }
431}
432
433/// Save to the platform config path (creating it). On success, signal a running
434/// Waybar (`SIGRTMIN+13`) so a `signal: 13` module refreshes immediately.
435fn save_to_config_default(state: &SettingsState) -> Result<()> {
436    let path = default_config_path()?;
437    if let Some(parent) = path.parent() {
438        std::fs::create_dir_all(parent).map_err(|e| AppError::io_at(parent, e))?;
439    }
440    save_to_path(state, &path)?;
441    crate::waybar::request_refresh();
442    Ok(())
443}
444
445/// Same as `save_to_config_default` but with an explicit path — exposed for
446/// tests. Writing a non-empty key also sets that vendor's `enabled = true`.
447pub fn save_to_path(state: &SettingsState, path: &Path) -> Result<()> {
448    let original = match std::fs::read_to_string(path) {
449        Ok(contents) => contents,
450        Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
451        Err(error) => return Err(AppError::io_at(path, error)),
452    };
453    let mut doc: DocumentMut = if original.trim().is_empty() {
454        DocumentMut::new()
455    } else {
456        original.parse().map_err(|e: toml_edit::TomlError| {
457            AppError::Other(format!("config.toml not parseable: {e}"))
458        })?
459    };
460
461    // Do not write a disabled primary as a side effect of saving an API key.
462    // With no enabled vendors, leave any existing value alone so the legacy
463    // resolver's Anthropic fallback remains intact.
464    if state.primary_choices.contains(&state.primary) {
465        set_string(&mut doc, "ui", "primary", state.primary.slug())?;
466    }
467
468    for (i, kv) in KEY_VENDORS.iter().enumerate() {
469        let Some(input) = state.keys.get(i) else {
470            continue;
471        };
472        update_key(&mut doc, kv.section, input)?;
473    }
474
475    let bytes = doc.to_string();
476    crate::cache::atomic_write(path, bytes.as_bytes())?;
477
478    #[cfg(unix)]
479    {
480        use std::os::unix::fs::PermissionsExt;
481        if let Ok(meta) = std::fs::metadata(path) {
482            let mut perms = meta.permissions();
483            perms.set_mode(0o600);
484            let _ = std::fs::set_permissions(path, perms);
485        }
486    }
487    Ok(())
488}
489
490/// Apply one key field to the document. Untouched fields are left alone; a
491/// field the user cleared is *removed*, so an inline secret can be deleted
492/// from the overlay rather than lingering in the file. Writing a non-empty key
493/// also opts the vendor in — the opt-in vendors would otherwise never fetch.
494fn update_key(doc: &mut DocumentMut, section: &str, input: &KeyInput) -> Result<()> {
495    if !input.dirty {
496        return Ok(());
497    }
498    if input.buf.is_empty() {
499        if let Some(table) = doc.get_mut(section).and_then(toml_edit::Item::as_table_mut) {
500            table.remove("api_key");
501        }
502        return Ok(());
503    }
504    set_string(doc, section, "api_key", &input.buf)?;
505    set_bool(doc, section, "enabled", true)
506}
507
508/// Set or update a string field in a TOML section, preserving comments and
509/// formatting of unaffected nodes.
510fn set_string(doc: &mut DocumentMut, section: &str, key: &str, new_value: &str) -> Result<()> {
511    let table = doc
512        .entry(section)
513        .or_insert_with(toml_edit::table)
514        .as_table_mut()
515        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
516
517    if let Some(item) = table.get_mut(key)
518        && let Some(v) = item.as_value_mut()
519    {
520        *v = toml_edit::Value::from(new_value);
521        v.decor_mut().set_prefix(" ");
522        return Ok(());
523    }
524    table.insert(key, value(new_value));
525    Ok(())
526}
527
528/// Same as [`set_string`] for a boolean field.
529fn set_bool(doc: &mut DocumentMut, section: &str, key: &str, new_value: bool) -> Result<()> {
530    let table = doc
531        .entry(section)
532        .or_insert_with(toml_edit::table)
533        .as_table_mut()
534        .ok_or_else(|| AppError::Other(format!("config.toml: [{section}] is not a table")))?;
535
536    if let Some(item) = table.get_mut(key)
537        && let Some(v) = item.as_value_mut()
538    {
539        *v = toml_edit::Value::from(new_value);
540        v.decor_mut().set_prefix(" ");
541        return Ok(());
542    }
543    table.insert(key, value(new_value));
544    Ok(())
545}
546
547fn default_config_path() -> Result<PathBuf> {
548    // Save back to the same file Config::load() selected. On macOS this may be
549    // the legacy ~/.config path when the canonical Application Support file is
550    // absent; writing a new canonical file would shadow the existing config on
551    // the next load and silently discard all settings the overlay did not copy.
552    crate::config::resolved_path()
553        .ok_or_else(|| AppError::Other("could not resolve config dir".into()))
554}
555
556// ─── Render ────────────────────────────────────────────────────────────────
557
558/// Render the modal overlay over `area`.
559pub fn render(f: &mut Frame, area: Rect, state: &SettingsState, theme: &Theme) {
560    let modal = centered_rect(74, 88, area);
561    f.render_widget(Clear, modal);
562
563    let bubble = bubble_theme(theme);
564    let block = bubble.titled_modal_block(" Settings ");
565    let inner = block.inner(modal);
566    f.render_widget(block, modal);
567
568    // Body (everything but the pinned hint) + a 1-line hint footer.
569    let chunks = Layout::default()
570        .direction(Direction::Vertical)
571        .constraints([Constraint::Min(0), Constraint::Length(1)])
572        .split(inner);
573
574    // — Primary vendor + API keys header —
575    let mut lines: Vec<Line> = vec![
576        section_header("Primary vendor", "shown first on the bar / TUI", &bubble),
577        primary_line(state, &bubble),
578        Line::from(""),
579        section_header(
580            "API keys",
581            "pick a row, type the key, then Ctrl-S — Claude & Codex use CLI login",
582            &bubble,
583        ),
584    ];
585    for (i, kv) in KEY_VENDORS.iter().enumerate() {
586        let focused = state.focus == Focus::Key(i);
587        lines.push(key_row(kv, &state.keys[i], focused, &bubble));
588    }
589    lines.push(Line::from(""));
590
591    // — Save + status —
592    lines.push(save_line(state.focus == Focus::Save, &bubble));
593    if !state.status.is_empty() {
594        let ok = state.status.starts_with("saved");
595        let mark = if ok { "  ✓ " } else { "  ✗ " };
596        let style = if ok { bubble.accent } else { bubble.selected };
597        lines.push(Line::from(vec![
598            Span::styled(mark, style.add_modifier(Modifier::BOLD)),
599            Span::styled(state.status.clone(), bubble.muted),
600        ]));
601    }
602
603    f.render_widget(Paragraph::new(lines), chunks[0]);
604
605    // Context-aware hint footer.
606    let hint = match state.focus {
607        Focus::Primary => bubble.help_line([
608            ("↑↓/tab", "move"),
609            ("←→", "change vendor"),
610            ("^S", "save"),
611            ("esc", "close"),
612        ]),
613        Focus::Key(_) => bubble.help_line([
614            ("↑↓/tab", "move"),
615            ("type", "edit key"),
616            ("^V", "reveal"),
617            ("^S", "save"),
618            ("esc", "close"),
619        ]),
620        Focus::Save => {
621            bubble.help_line([("↑↓/tab", "move"), ("enter/^S", "save"), ("esc", "close")])
622        }
623    };
624    f.render_widget(Paragraph::new(hint), chunks[1]);
625}
626
627fn section_header(title: &str, sub: &str, theme: &BubbleTheme) -> Line<'static> {
628    Line::from(vec![
629        theme.span(" "),
630        Span::styled(title.to_string(), theme.title.add_modifier(Modifier::BOLD)),
631        theme.muted(format!("   — {sub}")),
632    ])
633}
634
635fn primary_line(state: &SettingsState, theme: &BubbleTheme) -> Line<'static> {
636    let focused = state.focus == Focus::Primary;
637    let name = state.primary.display_name().to_string();
638    if focused {
639        Line::from(vec![
640            theme.span("   "),
641            Span::styled("▸ ", theme.accent.add_modifier(Modifier::BOLD)),
642            Span::styled("◀ ", theme.accent),
643            Span::styled(
644                format!(" {name} "),
645                theme
646                    .selected
647                    .add_modifier(Modifier::REVERSED | Modifier::BOLD),
648            ),
649            Span::styled(" ▶", theme.accent),
650            theme.muted("    ← → to change"),
651        ])
652    } else {
653        Line::from(vec![theme.span("     "), Span::styled(name, theme.text)])
654    }
655}
656
657fn key_row(kv: &KeyVendor, input: &KeyInput, focused: bool, theme: &BubbleTheme) -> Line<'static> {
658    let label = format!("{:<11}", kv.label);
659    let value = value_text(input, focused);
660
661    // Env / status suffix: env-var name, whether an env override is set, note.
662    let env_set = std::env::var(kv.env)
663        .map(|v| !v.is_empty())
664        .unwrap_or(false);
665    let mut suffix = format!("   {}", kv.env);
666    if env_set {
667        suffix.push_str(" · env set (overrides)");
668    }
669    if !kv.note.is_empty() {
670        suffix.push_str(&format!(" · {}", kv.note));
671    }
672
673    if focused {
674        let val_style = if input.buf.is_empty() {
675            theme.accent.add_modifier(Modifier::BOLD)
676        } else {
677            theme.selected.add_modifier(Modifier::REVERSED)
678        };
679        let mut spans = vec![
680            theme.span("  "),
681            Span::styled("▸ ", theme.accent.add_modifier(Modifier::BOLD)),
682            Span::styled(label, theme.title.add_modifier(Modifier::BOLD)),
683            Span::styled(format!(" {value} "), val_style),
684        ];
685        if input.revealed {
686            spans.push(theme.muted("  [revealed]"));
687        }
688        spans.push(theme.muted(suffix));
689        Line::from(spans)
690    } else {
691        let val_style = if input.buf.is_empty() {
692            theme.muted
693        } else {
694            theme.text
695        };
696        Line::from(vec![
697            theme.span("    "),
698            Span::styled(label, theme.text),
699            Span::styled(format!(" {value}"), val_style),
700            theme.muted(suffix),
701        ])
702    }
703}
704
705/// The value column: `(empty)` / a cursor when focused-empty / masked or
706/// revealed buffer with a cursor mark inserted when focused.
707fn value_text(input: &KeyInput, focused: bool) -> String {
708    if input.buf.is_empty() {
709        return if focused {
710            "‸".to_string()
711        } else {
712            "(empty)".to_string()
713        };
714    }
715    let base = input.display();
716    if !focused {
717        return base;
718    }
719    let mut chars: Vec<char> = base.chars().collect();
720    let pos = input.cursor.min(chars.len());
721    chars.insert(pos, '‸');
722    chars.into_iter().collect()
723}
724
725fn save_line(focused: bool, theme: &BubbleTheme) -> Line<'static> {
726    let style = if focused {
727        theme
728            .selected
729            .add_modifier(Modifier::REVERSED | Modifier::BOLD)
730    } else {
731        theme.accent.add_modifier(Modifier::BOLD)
732    };
733    let marker = if focused { "▸ " } else { "  " };
734    Line::from(vec![
735        theme.span("   "),
736        Span::styled(marker, theme.accent.add_modifier(Modifier::BOLD)),
737        Span::styled("  Save  (Ctrl-S)  ", style),
738    ])
739}
740
741/// Center a rectangle of `percent_x * percent_y` over `r`.
742fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
743    let popup_h = (r.height * percent_y) / 100;
744    let popup_w = (r.width * percent_x) / 100;
745    Rect {
746        x: r.x + (r.width - popup_w) / 2,
747        y: r.y + (r.height - popup_h) / 2,
748        width: popup_w,
749        height: popup_h,
750    }
751}
752
753// crossterm types live behind ratatui; re-exported here for handle_key callers.
754pub use ratatui::crossterm::event::{KeyCode, KeyModifiers};
755
756#[cfg(test)]
757mod tests {
758    use super::*;
759    use tempfile::TempDir;
760
761    fn temp_config(initial: Option<&str>) -> (TempDir, std::path::PathBuf) {
762        crate::cache::closed_temp_file("config.toml", initial)
763    }
764
765    fn key_index(id: VendorId) -> usize {
766        KEY_VENDORS.iter().position(|kv| kv.id == id).unwrap()
767    }
768
769    fn blank_state(primary: VendorId) -> SettingsState {
770        SettingsState {
771            focus: Focus::Primary,
772            primary_choices: VendorId::all().to_vec(),
773            primary,
774            keys: KEY_VENDORS.iter().map(|_| KeyInput::default()).collect(),
775            status: String::new(),
776        }
777    }
778
779    /// State with a Z.AI key and an OpenRouter key, both marked dirty.
780    fn state_with(zai: &str, opr: &str, primary: VendorId) -> SettingsState {
781        let mut s = blank_state(primary);
782        s.keys[key_index(VendorId::Zai)] = KeyInput::from_config(Some(zai));
783        s.keys[key_index(VendorId::Zai)].dirty = true;
784        s.keys[key_index(VendorId::Openrouter)] = KeyInput::from_config(Some(opr));
785        s.keys[key_index(VendorId::Openrouter)].dirty = true;
786        s
787    }
788
789    #[test]
790    fn focus_cycles_through_primary_all_keys_and_save() {
791        let mut f = Focus::Primary;
792        let mut seen = vec![f];
793        // Full cycle = Primary + N key rows + Save.
794        for _ in 0..(KEY_VENDORS.len() + 2) {
795            f = f.next();
796            seen.push(f);
797        }
798        // Primary, Key(0..n), Save, back to Primary.
799        assert_eq!(seen.first(), Some(&Focus::Primary));
800        assert_eq!(seen.last(), Some(&Focus::Primary));
801        assert!(seen.contains(&Focus::Key(0)));
802        assert!(seen.contains(&Focus::Key(KEY_VENDORS.len() - 1)));
803        assert!(seen.contains(&Focus::Save));
804        // prev() is the inverse of next().
805        assert_eq!(Focus::Primary.next().prev(), Focus::Primary);
806        assert_eq!(Focus::Save.prev().next(), Focus::Save);
807        assert_eq!(Focus::Primary.prev(), Focus::Save);
808    }
809
810    #[test]
811    fn every_key_vendor_has_a_field() {
812        // Every enabled-by-key vendor must be reachable in the form.
813        for id in [
814            VendorId::Zai,
815            VendorId::Openrouter,
816            VendorId::Deepseek,
817            VendorId::Kilo,
818            VendorId::Novita,
819            VendorId::Moonshot,
820            VendorId::Grok,
821        ] {
822            assert!(
823                KEY_VENDORS.iter().any(|kv| kv.id == id),
824                "{id:?} has no key field"
825            );
826        }
827        // OAuth vendors are intentionally absent.
828        assert!(!KEY_VENDORS.iter().any(|kv| kv.id == VendorId::Anthropic));
829        assert!(!KEY_VENDORS.iter().any(|kv| kv.id == VendorId::Openai));
830    }
831
832    #[test]
833    fn from_config_prefills_existing_keys() {
834        let mut cfg = Config::default();
835        cfg.kilo.api_key = Some("sk-kilo".into());
836        let s = SettingsState::from_config(&cfg);
837        assert_eq!(s.keys[key_index(VendorId::Kilo)].buf, "sk-kilo");
838        assert!(!s.keys[key_index(VendorId::Kilo)].dirty);
839    }
840
841    #[test]
842    fn from_config_offers_enabled_vendors_only() {
843        let cfg = Config::default();
844        let s = SettingsState::from_config(&cfg);
845        assert_eq!(s.primary_choices, cfg.enabled_vendors());
846        // Opt-in vendors are disabled by default and must not be offered.
847        assert!(!s.primary_choices.contains(&VendorId::Grok));
848        assert!(s.primary_choices.contains(&s.primary));
849    }
850
851    #[test]
852    fn from_config_falls_back_when_configured_primary_is_disabled() {
853        // Grok is opt-in; a config naming it as primary without enabling it
854        // must display the first enabled vendor instead.
855        let mut cfg = Config::default();
856        cfg.ui.primary = Some(VendorId::Grok);
857        let s = SettingsState::from_config(&cfg);
858        assert_ne!(s.primary, VendorId::Grok);
859        assert_eq!(Some(s.primary), cfg.enabled_vendors().first().copied());
860    }
861
862    #[test]
863    fn key_input_insert_backspace_arrow() {
864        let mut k = KeyInput::default();
865        k.insert_char('a');
866        k.insert_char('b');
867        k.insert_char('c');
868        assert_eq!(k.buf, "abc");
869        assert_eq!(k.cursor, 3);
870        assert!(k.dirty);
871        k.move_left();
872        k.move_left();
873        assert_eq!(k.cursor, 1);
874        k.insert_char('x');
875        assert_eq!(k.buf, "axbc");
876        assert_eq!(k.cursor, 2);
877        k.backspace();
878        assert_eq!(k.buf, "abc");
879        assert_eq!(k.cursor, 1);
880    }
881
882    #[test]
883    fn key_input_masks_by_default_reveals_on_toggle() {
884        let mut k = KeyInput::default();
885        for c in "secret-key".chars() {
886            k.insert_char(c);
887        }
888        assert_eq!(k.display(), "•".repeat(10));
889        k.toggle_reveal();
890        assert_eq!(k.display(), "secret-key");
891    }
892
893    #[test]
894    fn key_input_handles_unicode() {
895        let mut k = KeyInput::default();
896        k.insert_char('a');
897        k.insert_char('→');
898        k.insert_char('b');
899        assert_eq!(k.buf, "a→b");
900        assert_eq!(k.cursor, 3);
901        k.move_left();
902        k.backspace();
903        assert_eq!(k.buf, "ab");
904    }
905
906    #[test]
907    fn value_text_shows_cursor_and_empty_states() {
908        let mut k = KeyInput::default();
909        assert_eq!(value_text(&k, false), "(empty)");
910        assert_eq!(value_text(&k, true), "‸");
911        k.insert_char('a');
912        k.insert_char('b');
913        // masked + cursor at end
914        assert_eq!(value_text(&k, true), "••‸");
915        assert_eq!(value_text(&k, false), "••");
916    }
917
918    #[test]
919    fn save_writes_key_and_enables_vendor() {
920        let (_dir, path) = temp_config(None);
921        let mut s = blank_state(VendorId::Kilo);
922        s.keys[key_index(VendorId::Kilo)] = KeyInput::from_config(Some("sk-kilo"));
923        s.keys[key_index(VendorId::Kilo)].dirty = true;
924        save_to_path(&s, &path).unwrap();
925        let raw = std::fs::read_to_string(&path).unwrap();
926        assert!(raw.contains("primary = \"kilo\""));
927        assert!(raw.contains("[kilo]"));
928        assert!(raw.contains("api_key = \"sk-kilo\""));
929        assert!(raw.contains("enabled = true"));
930    }
931
932    #[test]
933    fn save_writes_minimal_toml_when_starting_empty() {
934        let (_dir, path) = temp_config(None);
935        let s = state_with("zk", "ok", VendorId::Zai);
936        save_to_path(&s, &path).unwrap();
937        let raw = std::fs::read_to_string(&path).unwrap();
938        assert!(raw.contains("primary = \"zai\""));
939        assert!(raw.contains("[zai]"));
940        assert!(raw.contains("api_key = \"zk\""));
941        assert!(raw.contains("[openrouter]"));
942        assert!(raw.contains("api_key = \"ok\""));
943    }
944
945    #[test]
946    fn save_preserves_existing_comments_and_unrelated_fields() {
947        let (_dir, path) = temp_config(Some(
948            r##"# my comment
949[ui]
950# pre-existing comment
951primary = "anthropic"
952
953[zai]
954enabled = true
955api_key_env = "ZAI_API_KEY"
956# tier comment
957plan_tier = "pro"
958
959[openrouter]
960enabled = true
961api_key_env = "OPENROUTER_API_KEY"
962"##,
963        ));
964
965        let s = state_with("zk2", "ok2", VendorId::Openrouter);
966        save_to_path(&s, &path).unwrap();
967
968        let raw = std::fs::read_to_string(&path).unwrap();
969        assert!(raw.contains("# my comment"));
970        assert!(raw.contains("# pre-existing comment"));
971        assert!(raw.contains("# tier comment"));
972        assert!(raw.contains("api_key_env = \"ZAI_API_KEY\""));
973        assert!(raw.contains("plan_tier = \"pro\""));
974        assert!(raw.contains("primary = \"openrouter\""));
975        assert!(raw.contains("api_key = \"zk2\""));
976        assert!(raw.contains("api_key = \"ok2\""));
977    }
978
979    #[test]
980    fn save_refuses_to_replace_an_unreadable_existing_config() {
981        let (_dir, path) = temp_config(None);
982        let original = [0xff, 0xfe, 0xfd];
983        std::fs::write(&path, original).unwrap();
984        let state = state_with("new-secret", "", VendorId::Zai);
985
986        assert!(save_to_path(&state, &path).is_err());
987        assert_eq!(std::fs::read(&path).unwrap(), original);
988    }
989
990    #[test]
991    fn save_does_not_write_empty_key_when_dirty_but_blank() {
992        let (_dir, path) = temp_config(None);
993        let mut s = blank_state(VendorId::Anthropic);
994        // Focus each key, do nothing but mark dirty (blank).
995        for k in &mut s.keys {
996            k.dirty = true;
997        }
998        save_to_path(&s, &path).unwrap();
999        let raw = std::fs::read_to_string(&path).unwrap();
1000        assert!(!raw.contains("api_key ="));
1001    }
1002
1003    #[test]
1004    #[cfg(unix)]
1005    fn save_chmods_to_600() {
1006        use std::os::unix::fs::PermissionsExt;
1007        let (_dir, path) = temp_config(None);
1008        let s = state_with("zk", "ok", VendorId::Zai);
1009        save_to_path(&s, &path).unwrap();
1010        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1011        assert_eq!(mode & 0o777, 0o600);
1012    }
1013
1014    #[test]
1015    fn tab_cycles_focus_from_primary_to_first_key() {
1016        let mut s = blank_state(VendorId::Anthropic);
1017        assert_eq!(
1018            handle_key(&mut s, KeyCode::Tab, KeyModifiers::NONE),
1019            Action::Continue
1020        );
1021        assert_eq!(s.focus, Focus::Key(0));
1022        assert_eq!(
1023            handle_key(&mut s, KeyCode::BackTab, KeyModifiers::NONE),
1024            Action::Continue
1025        );
1026        assert_eq!(s.focus, Focus::Primary);
1027    }
1028
1029    #[test]
1030    fn esc_closes_without_saving() {
1031        let mut s = blank_state(VendorId::Anthropic);
1032        assert_eq!(
1033            handle_key(&mut s, KeyCode::Esc, KeyModifiers::NONE),
1034            Action::Close
1035        );
1036    }
1037
1038    #[test]
1039    fn left_right_cycles_primary_vendor() {
1040        // Canonical order (VendorId::all): Anthropic, AnthropicApi, Openai, …
1041        let mut s = blank_state(VendorId::Anthropic);
1042        handle_key(&mut s, KeyCode::Right, KeyModifiers::NONE);
1043        assert_eq!(s.primary, VendorId::AnthropicApi);
1044        handle_key(&mut s, KeyCode::Right, KeyModifiers::NONE);
1045        assert_eq!(s.primary, VendorId::Openai);
1046        handle_key(&mut s, KeyCode::Left, KeyModifiers::NONE);
1047        assert_eq!(s.primary, VendorId::AnthropicApi);
1048    }
1049
1050    #[test]
1051    fn left_right_offers_enabled_vendors_only() {
1052        // The selector must never land on a vendor the widget cannot use.
1053        let mut s = blank_state(VendorId::Anthropic);
1054        s.primary_choices = vec![VendorId::Anthropic, VendorId::Grok];
1055        handle_key(&mut s, KeyCode::Right, KeyModifiers::NONE);
1056        assert_eq!(s.primary, VendorId::Grok);
1057        // Wraps within the enabled set rather than walking into disabled ones.
1058        handle_key(&mut s, KeyCode::Right, KeyModifiers::NONE);
1059        assert_eq!(s.primary, VendorId::Anthropic);
1060        handle_key(&mut s, KeyCode::Left, KeyModifiers::NONE);
1061        assert_eq!(s.primary, VendorId::Grok);
1062    }
1063
1064    #[test]
1065    fn no_enabled_vendors_leaves_primary_selector_inert() {
1066        let mut s = blank_state(VendorId::Anthropic);
1067        s.primary_choices = vec![];
1068        handle_key(&mut s, KeyCode::Right, KeyModifiers::NONE);
1069        assert_eq!(s.primary, VendorId::Anthropic);
1070    }
1071
1072    #[test]
1073    fn save_does_not_write_a_disabled_primary() {
1074        // Saving an API key must not persist a primary the resolver would
1075        // ignore; an existing value in the file stays untouched.
1076        let (_dir, path) = temp_config(Some("[ui]\nprimary = \"anthropic\"\n"));
1077        let mut s = state_with("zk", "ok", VendorId::Grok);
1078        s.primary_choices = vec![VendorId::Anthropic];
1079        save_to_path(&s, &path).unwrap();
1080        let raw = std::fs::read_to_string(&path).unwrap();
1081        assert!(raw.contains("primary = \"anthropic\""));
1082        assert!(!raw.contains("primary = \"grok\""));
1083        // The keys still saved.
1084        assert!(raw.contains("zk"));
1085    }
1086
1087    #[test]
1088    fn save_removes_an_inline_key_the_user_cleared() {
1089        // Clearing the field in the overlay must delete the secret from the
1090        // file — otherwise there is no way to remove it short of hand-editing.
1091        let (_dir, path) = temp_config(Some(
1092            "[zai]\nenabled = true\napi_key = \"old-secret\"\nplan_tier = \"pro\"\n",
1093        ));
1094        let mut s = blank_state(VendorId::Zai);
1095        s.primary_choices = vec![VendorId::Zai];
1096        s.keys[key_index(VendorId::Zai)] = KeyInput::default();
1097        s.keys[key_index(VendorId::Zai)].dirty = true;
1098        save_to_path(&s, &path).unwrap();
1099        let raw = std::fs::read_to_string(&path).unwrap();
1100        assert!(!raw.contains("old-secret"));
1101        assert!(!raw.contains("api_key"));
1102        // Unrelated fields in the same section survive.
1103        assert!(raw.contains("plan_tier = \"pro\""));
1104    }
1105
1106    #[test]
1107    fn untouched_key_field_is_left_alone() {
1108        // Not dirty => the file's existing secret must survive a save.
1109        let (_dir, path) = temp_config(Some("[zai]\napi_key = \"keep-me\"\n"));
1110        let mut s = blank_state(VendorId::Zai);
1111        s.primary_choices = vec![VendorId::Zai];
1112        save_to_path(&s, &path).unwrap();
1113        let raw = std::fs::read_to_string(&path).unwrap();
1114        assert!(raw.contains("keep-me"));
1115    }
1116
1117    #[test]
1118    fn typing_edits_the_focused_key_only() {
1119        let mut s = blank_state(VendorId::Anthropic);
1120        s.focus = Focus::Key(key_index(VendorId::Grok));
1121        for c in "xai-abc".chars() {
1122            handle_key(&mut s, KeyCode::Char(c), KeyModifiers::NONE);
1123        }
1124        assert_eq!(s.keys[key_index(VendorId::Grok)].buf, "xai-abc");
1125        assert!(s.keys[key_index(VendorId::Grok)].dirty);
1126        // No other field was touched.
1127        assert!(s.keys[key_index(VendorId::Zai)].buf.is_empty());
1128    }
1129
1130    #[test]
1131    fn ctrl_v_toggles_reveal_on_focused_key_field() {
1132        let mut s = blank_state(VendorId::Anthropic);
1133        let zi = key_index(VendorId::Zai);
1134        s.focus = Focus::Key(zi);
1135        s.keys[zi] = KeyInput::from_config(Some("secret"));
1136        assert!(!s.keys[zi].revealed);
1137        handle_key(&mut s, KeyCode::Char('v'), KeyModifiers::CONTROL);
1138        assert!(s.keys[zi].revealed);
1139        handle_key(&mut s, KeyCode::Char('v'), KeyModifiers::CONTROL);
1140        assert!(!s.keys[zi].revealed);
1141    }
1142
1143    #[test]
1144    fn control_chorded_chars_do_not_type_into_fields() {
1145        let mut s = blank_state(VendorId::Anthropic);
1146        s.focus = Focus::Key(0);
1147        // Ctrl-A must NOT insert a literal 'a' or mark the field dirty.
1148        handle_key(&mut s, KeyCode::Char('a'), KeyModifiers::CONTROL);
1149        assert!(s.keys[0].buf.is_empty());
1150        assert!(!s.keys[0].dirty);
1151        // Ctrl-C quits the host TUI even while the overlay owns focus.
1152        assert_eq!(
1153            handle_key(&mut s, KeyCode::Char('c'), KeyModifiers::CONTROL),
1154            Action::Quit
1155        );
1156        // A plain char still types normally.
1157        handle_key(&mut s, KeyCode::Char('x'), KeyModifiers::NONE);
1158        assert_eq!(s.keys[0].buf, "x");
1159    }
1160
1161    #[test]
1162    fn ctrl_v_on_non_key_focus_is_noop() {
1163        let mut s = blank_state(VendorId::Anthropic);
1164        s.focus = Focus::Primary;
1165        // Must not panic when no key field is focused.
1166        assert_eq!(
1167            handle_key(&mut s, KeyCode::Char('v'), KeyModifiers::CONTROL),
1168            Action::Continue
1169        );
1170    }
1171
1172    fn state_focused_on_zai() -> SettingsState {
1173        let mut state = blank_state(VendorId::Anthropic);
1174        state.focus = Focus::Key(key_index(VendorId::Zai));
1175        state
1176    }
1177
1178    #[test]
1179    fn handle_key_ctrl_c_quits_without_typing_into_key_field() {
1180        let mut s = state_focused_on_zai();
1181        let zi = key_index(VendorId::Zai);
1182        assert_eq!(
1183            handle_key(&mut s, KeyCode::Char('c'), KeyModifiers::CONTROL),
1184            Action::Quit
1185        );
1186        assert!(s.keys[zi].buf.is_empty());
1187        // Untouched means save still leaves an existing key on disk alone.
1188        assert!(!s.keys[zi].dirty);
1189    }
1190
1191    #[test]
1192    fn handle_key_alt_chord_does_not_type_into_key_field() {
1193        let mut s = state_focused_on_zai();
1194        let zi = key_index(VendorId::Zai);
1195        handle_key(&mut s, KeyCode::Char('x'), KeyModifiers::ALT);
1196        assert!(s.keys[zi].buf.is_empty());
1197        assert!(!s.keys[zi].dirty);
1198    }
1199
1200    #[test]
1201    fn handle_key_platform_modifier_chords_do_not_type_into_key_field() {
1202        for modifier in [KeyModifiers::SUPER, KeyModifiers::HYPER, KeyModifiers::META] {
1203            let mut s = state_focused_on_zai();
1204            let zi = key_index(VendorId::Zai);
1205            handle_key(&mut s, KeyCode::Char('x'), modifier);
1206            assert!(s.keys[zi].buf.is_empty(), "modifier {modifier:?}");
1207            assert!(!s.keys[zi].dirty, "modifier {modifier:?}");
1208        }
1209    }
1210
1211    #[test]
1212    fn handle_key_shift_still_types_uppercase() {
1213        let mut s = state_focused_on_zai();
1214        let zi = key_index(VendorId::Zai);
1215        handle_key(&mut s, KeyCode::Char('A'), KeyModifiers::SHIFT);
1216        assert_eq!(s.keys[zi].buf, "A");
1217        assert!(s.keys[zi].dirty);
1218    }
1219
1220    #[test]
1221    fn handle_key_plain_space_still_cycles_primary_vendor() {
1222        let mut s = blank_state(VendorId::Anthropic);
1223        handle_key(&mut s, KeyCode::Char(' '), KeyModifiers::NONE);
1224        assert_eq!(s.primary, VendorId::AnthropicApi);
1225    }
1226
1227    #[test]
1228    fn handle_key_ctrl_s_attempts_save_from_any_field() {
1229        let (_dir, path) = temp_config(None);
1230        let s = state_with("zk", "ok", VendorId::Zai);
1231        save_to_path(&s, &path).unwrap();
1232        let raw = std::fs::read_to_string(&path).unwrap();
1233        assert!(raw.contains("api_key = \"zk\""));
1234    }
1235    #[test]
1236    fn save_to_path_writes_kimi_key_when_dirty() {
1237        let (_dir, path) = temp_config(None);
1238        let mut s = blank_state(VendorId::Anthropic);
1239        let kimi = key_index(VendorId::Kimi);
1240        s.keys[kimi] = KeyInput::from_config(Some("kk"));
1241        s.keys[kimi].dirty = true;
1242        save_to_path(&s, &path).unwrap();
1243        let raw = std::fs::read_to_string(&path).unwrap();
1244        assert!(raw.contains("[kimi]"));
1245        assert!(raw.contains("api_key = \"kk\""));
1246    }
1247
1248    #[test]
1249    fn settings_save_uses_the_same_config_path_as_load() {
1250        assert_eq!(
1251            default_config_path().unwrap(),
1252            crate::config::resolved_path().unwrap()
1253        );
1254    }
1255}