mutiny-diff 0.1.22

TUI git diff viewer with worktree management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::theme::{apply_overrides, Theme, ThemeOverrides};

/// API keys for LLM providers, stored in config.toml [api_keys] section.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct ApiKeysConfig {
    #[serde(default)]
    pub openai: Option<String>,
    #[serde(default)]
    pub anthropic: Option<String>,
    #[serde(default)]
    pub moonshot: Option<String>,
}

/// Configuration for agentic review mode.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgenticReviewConfig {
    /// Legacy single provider field — used as fallback when per-role providers are absent.
    #[serde(default)]
    pub provider: Option<String>,
    pub parent_model: String,
    pub child_model: String,
    #[serde(default)]
    pub parent_provider: Option<String>,
    #[serde(default)]
    pub child_provider: Option<String>,
    #[serde(default)]
    pub base_url: Option<String>,
    #[serde(default = "default_max_agent_turns")]
    pub max_agent_turns: usize,
}

fn default_max_agent_turns() -> usize {
    50
}

impl AgenticReviewConfig {
    /// Resolved parent provider (falls back to legacy `provider`, then "anthropic").
    pub fn resolved_parent_provider(&self) -> &str {
        self.parent_provider
            .as_deref()
            .or(self.provider.as_deref())
            .unwrap_or("anthropic")
    }

    /// Resolved child provider (falls back to legacy `provider`, then "anthropic").
    pub fn resolved_child_provider(&self) -> &str {
        self.child_provider
            .as_deref()
            .or(self.provider.as_deref())
            .unwrap_or("anthropic")
    }
}

impl Default for AgenticReviewConfig {
    fn default() -> Self {
        Self {
            provider: None,
            parent_model: "claude-sonnet-4-6".to_string(),
            child_model: "claude-sonnet-4-5".to_string(),
            parent_provider: Some("anthropic".to_string()),
            child_provider: Some("anthropic".to_string()),
            base_url: None,
            max_agent_turns: 50,
        }
    }
}

#[derive(Debug, Clone, Deserialize)]
#[allow(dead_code)]
pub struct AgentProviderConfig {
    pub name: String,
    pub command: String,
    #[serde(default)]
    pub models: Vec<String>,
    #[serde(default)]
    pub default_model: String,
    #[serde(default)]
    pub description: String,
}

#[derive(Debug, Clone, Deserialize)]
pub struct MouseConfig {
    #[serde(default = "default_mouse_enabled")]
    pub enabled: bool,
}

impl Default for MouseConfig {
    fn default() -> Self {
        Self { enabled: true }
    }
}

fn default_mouse_enabled() -> bool {
    true
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChecklistItemConfig {
    pub label: String,
    pub key: String, // Single character as string for TOML compatibility
}

#[derive(Debug, Clone, Deserialize)]
pub struct ChecklistConfig {
    pub items: Vec<ChecklistItemConfig>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct MdiffConfig {
    pub agents: Vec<AgentProviderConfig>,
    pub agents_by_name: HashMap<String, usize>,
    pub theme: Theme,
    pub unified: Option<bool>,
    pub ignore_whitespace: Option<bool>,
    pub context_lines: Option<usize>,
    /// Last-used model per agent name (e.g. "claude" -> "claude-opus-4-6").
    pub agent_models: HashMap<String, String>,
    pub mouse: MouseConfig,
    /// Checklist configuration for review templates
    pub checklist: Option<ChecklistConfig>,
    pub tree_mode: Option<bool>,
    /// API keys for LLM providers
    pub api_keys: Option<ApiKeysConfig>,
    /// Agentic review configuration
    pub agentic_review: AgenticReviewConfig,
}

impl Default for MdiffConfig {
    fn default() -> Self {
        let agents = detect_agents();
        let agents_by_name = agents
            .iter()
            .enumerate()
            .map(|(i, a)| (a.name.clone(), i))
            .collect();
        Self {
            agents,
            agents_by_name,
            theme: Theme::from_name("one-dark"),
            unified: None,
            ignore_whitespace: None,
            context_lines: None,
            agent_models: HashMap::new(),
            mouse: MouseConfig::default(),
            checklist: None,
            tree_mode: None,
            api_keys: None,
            agentic_review: AgenticReviewConfig::default(),
        }
    }
}

/// Check if an executable exists on PATH.
fn has_command(name: &str) -> bool {
    std::process::Command::new("which")
        .arg(name)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .is_ok_and(|s| s.success())
}

/// Known CLI agents with their default configurations.
fn known_agents() -> Vec<AgentProviderConfig> {
    vec![
        AgentProviderConfig {
            name: "claude".to_string(),
            command: "claude --permission-mode acceptEdits --model {model} '{rendered_prompt}'"
                .to_string(),
            models: vec![
                "claude-sonnet-4-6".to_string(),
                "claude-opus-4-6".to_string(),
                "claude-haiku-4-5".to_string(),
            ],
            default_model: "claude-sonnet-4-6".to_string(),
            description: "Anthropic Claude Code".to_string(),
        },
        AgentProviderConfig {
            name: "codex".to_string(),
            command: "codex --model {model} --sandbox workspace-write --ask-for-approval untrusted '{rendered_prompt}'"
                .to_string(),
            models: vec![
                "gpt-5.4".to_string(),
                "gpt-5.3-codex".to_string(),
                "gpt-5.2-codex".to_string(),
            ],
            default_model: "gpt-5.4".to_string(),
            description: "OpenAI Codex CLI".to_string(),
        },
        AgentProviderConfig {
            name: "opencode".to_string(),
            command: "opencode -m {model} --prompt '{rendered_prompt}'".to_string(),
            models: vec![
                "openai/gpt-5.4".to_string(),
                "openai/gpt-5.3-codex".to_string(),
                "anthropic/claude-sonnet-4-6".to_string(),
                "openai/gpt-5.2-codex".to_string(),
                "openai/o3".to_string(),
            ],
            default_model: "anthropic/claude-sonnet-4-6".to_string(),
            description: "OpenCode CLI".to_string(),
        },
        AgentProviderConfig {
            name: "gemini".to_string(),
            command: "gemini --approval-mode auto_edit '{rendered_prompt}'".to_string(),
            models: vec![
                "gemini-3-flash-preview".to_string(),
                "gemini-3-pro-preview".to_string(),
                "gemini-2.5-pro".to_string(),
                "gemini-2.5-flash".to_string(),
            ],
            default_model: "gemini-3-flash-preview".to_string(),
            description: "Google Gemini CLI".to_string(),
        },
    ]
}

/// Auto-detect which known agent CLIs are available on PATH.
fn detect_agents() -> Vec<AgentProviderConfig> {
    known_agents()
        .into_iter()
        .filter(|a| has_command(&a.name))
        .collect()
}

#[derive(Debug, Deserialize)]
struct ConfigFile {
    #[serde(default)]
    agents: Vec<AgentProviderConfig>,
    #[serde(default)]
    theme: Option<String>,
    #[serde(default)]
    colors: Option<ThemeOverrides>,
    #[serde(default)]
    unified: Option<bool>,
    #[serde(default)]
    ignore_whitespace: Option<bool>,
    #[serde(default)]
    context_lines: Option<usize>,
    #[serde(default)]
    agent_models: HashMap<String, String>,
    #[serde(default)]
    mouse: MouseConfig,
    #[serde(default)]
    checklist: Option<ChecklistConfig>,
    #[serde(default)]
    tree_mode: Option<bool>,
    #[serde(default)]
    api_keys: Option<ApiKeysConfig>,
    #[serde(default)]
    agentic_review: Option<AgenticReviewConfig>,
}

fn config_path() -> PathBuf {
    let mut path = dirs_home().unwrap_or_else(|| PathBuf::from("."));
    path.push(".config");
    path.push("mdiff");
    path.push("config.toml");
    path
}

fn dirs_home() -> Option<PathBuf> {
    std::env::var_os("HOME").map(PathBuf::from)
}

/// Build the agents_by_name index from an agents list.
fn build_agents_index(agents: &[AgentProviderConfig]) -> HashMap<String, usize> {
    agents
        .iter()
        .enumerate()
        .map(|(i, a)| (a.name.clone(), i))
        .collect()
}

/// Load config from `~/.config/mdiff/config.toml`, falling back to defaults.
/// If no agents are configured, auto-detects known CLIs on PATH.
pub fn load_config() -> MdiffConfig {
    let path = config_path();

    let contents = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(_) => return MdiffConfig::default(),
    };

    let file: ConfigFile = match toml::from_str(&contents) {
        Ok(f) => f,
        Err(_) => return MdiffConfig::default(),
    };

    // Use configured agents, or fall back to auto-detection
    let agents = if file.agents.is_empty() {
        detect_agents()
    } else {
        file.agents
    };

    let agents_by_name = build_agents_index(&agents);

    // Load theme by name, apply color overrides
    let theme_name = file.theme.as_deref().unwrap_or("one-dark");
    let mut theme = Theme::from_name(theme_name);
    if let Some(ref overrides) = file.colors {
        apply_overrides(&mut theme, overrides);
    }

    MdiffConfig {
        agents,
        agents_by_name,
        theme,
        unified: file.unified,
        ignore_whitespace: file.ignore_whitespace,
        context_lines: file.context_lines,
        agent_models: file.agent_models,
        mouse: file.mouse,
        checklist: file.checklist,
        tree_mode: file.tree_mode,
        api_keys: file.api_keys,
        agentic_review: file.agentic_review.unwrap_or_default(),
    }
}

/// Settings that get persisted to config.toml when the settings modal closes.
pub struct PersistentSettings {
    pub theme: String,
    pub unified: bool,
    pub ignore_whitespace: bool,
    pub context_lines: usize,
    pub tree_mode: bool,
    pub agentic_parent_provider: String,
    pub agentic_parent_model: String,
    pub agentic_child_provider: String,
    pub agentic_child_model: String,
    pub max_agent_turns: usize,
}

/// Save persistent settings to `~/.config/mdiff/config.toml`.
/// Reads the existing file (if any), updates only the settings fields, and writes back.
/// Preserves other config values (agents, prompt_template, color overrides).
pub fn save_settings(settings: &PersistentSettings) {
    let path = config_path();

    // Read existing config as a TOML table to preserve unknown fields
    let mut table = if let Ok(contents) = std::fs::read_to_string(&path) {
        contents
            .parse::<toml::Table>()
            .unwrap_or_else(|_| toml::Table::new())
    } else {
        toml::Table::new()
    };

    table.insert(
        "theme".to_string(),
        toml::Value::String(settings.theme.clone()),
    );
    table.insert(
        "unified".to_string(),
        toml::Value::Boolean(settings.unified),
    );
    table.insert(
        "ignore_whitespace".to_string(),
        toml::Value::Boolean(settings.ignore_whitespace),
    );
    table.insert(
        "context_lines".to_string(),
        toml::Value::Integer(settings.context_lines as i64),
    );
    table.insert(
        "tree_mode".to_string(),
        toml::Value::Boolean(settings.tree_mode),
    );

    // Persist agentic review settings
    let agentic = table
        .entry("agentic_review")
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));
    if let toml::Value::Table(ref mut t) = agentic {
        t.insert(
            "parent_provider".to_string(),
            toml::Value::String(settings.agentic_parent_provider.clone()),
        );
        t.insert(
            "parent_model".to_string(),
            toml::Value::String(settings.agentic_parent_model.clone()),
        );
        t.insert(
            "child_provider".to_string(),
            toml::Value::String(settings.agentic_child_provider.clone()),
        );
        t.insert(
            "child_model".to_string(),
            toml::Value::String(settings.agentic_child_model.clone()),
        );
        t.insert(
            "max_agent_turns".to_string(),
            toml::Value::Integer(settings.max_agent_turns as i64),
        );
    }

    // Ensure directory exists
    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let toml_string = toml::to_string_pretty(&table).unwrap_or_default();
    let _ = std::fs::write(&path, toml_string);
}

/// Load checklist configuration, checking project-specific .mdiff.toml first,
/// then falling back to global config.
pub fn load_checklist_config(repo_path: &Path) -> Option<ChecklistConfig> {
    // Check for project-specific config first
    let project_config_path = repo_path.join(".mdiff.toml");
    if let Ok(contents) = std::fs::read_to_string(&project_config_path) {
        if let Ok(file) = toml::from_str::<ConfigFile>(&contents) {
            if let Some(checklist) = file.checklist {
                return Some(checklist);
            }
        }
    }

    // Fall back to global config
    let global_config = load_config();
    global_config.checklist
}

/// Convert checklist config to (label, key) pairs, validating keys.
pub fn checklist_config_to_items(config: &ChecklistConfig) -> Vec<(String, char)> {
    config
        .items
        .iter()
        .take(20) // Limit to 20 items as per spec
        .filter_map(|item| {
            // Validate key is a single character
            let chars: Vec<char> = item.key.chars().collect();
            if chars.len() == 1 {
                Some((item.label.clone(), chars[0]))
            } else {
                None // Skip invalid keys
            }
        })
        .collect()
}

/// Available providers for agentic review.
pub const AGENTIC_PROVIDERS: &[&str] = &["anthropic", "openai", "moonshot"];

/// Available models per provider for agentic review.
pub fn agentic_models_for_provider(provider: &str) -> &'static [&'static str] {
    match provider {
        "anthropic" => &["claude-opus-4-6", "claude-sonnet-4-6", "claude-sonnet-4-5"],
        "openai" => &[
            "gpt-5.4",
            "gpt-5.3-codex",
            "gpt-5.2",
            "gpt-5.1",
            "gpt-5.4-mini",
            "gpt-4.1-mini",
        ],
        "moonshot" => &["kimi-k2.5", "kimi-k2-thinking-turbo"],
        _ => &[],
    }
}

/// Cycle to the next model for a given provider, returning the new model string.
pub fn next_agentic_model(provider: &str, current: &str) -> String {
    let models = agentic_models_for_provider(provider);
    if models.is_empty() {
        return current.to_string();
    }
    let idx = models.iter().position(|m| *m == current).unwrap_or(0);
    models[(idx + 1) % models.len()].to_string()
}

/// Cycle to the previous model for a given provider, returning the new model string.
pub fn prev_agentic_model(provider: &str, current: &str) -> String {
    let models = agentic_models_for_provider(provider);
    if models.is_empty() {
        return current.to_string();
    }
    let idx = models.iter().position(|m| *m == current).unwrap_or(0);
    models[(idx + models.len() - 1) % models.len()].to_string()
}

/// Cycle to the next agentic review provider.
pub fn next_agentic_provider(current: &str) -> &'static str {
    let idx = AGENTIC_PROVIDERS
        .iter()
        .position(|p| *p == current)
        .unwrap_or(0);
    AGENTIC_PROVIDERS[(idx + 1) % AGENTIC_PROVIDERS.len()]
}

/// Cycle to the previous agentic review provider.
pub fn prev_agentic_provider(current: &str) -> &'static str {
    let idx = AGENTIC_PROVIDERS
        .iter()
        .position(|p| *p == current)
        .unwrap_or(0);
    AGENTIC_PROVIDERS[(idx + AGENTIC_PROVIDERS.len() - 1) % AGENTIC_PROVIDERS.len()]
}

/// Save the last-used model for a specific agent to config.toml.
pub fn save_agent_model(agent_name: &str, model: &str) {
    let path = config_path();

    let mut table = if let Ok(contents) = std::fs::read_to_string(&path) {
        contents
            .parse::<toml::Table>()
            .unwrap_or_else(|_| toml::Table::new())
    } else {
        toml::Table::new()
    };

    let agent_models = table
        .entry("agent_models")
        .or_insert_with(|| toml::Value::Table(toml::Table::new()));

    if let toml::Value::Table(ref mut t) = agent_models {
        t.insert(
            agent_name.to_string(),
            toml::Value::String(model.to_string()),
        );
    }

    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    let toml_string = toml::to_string_pretty(&table).unwrap_or_default();
    let _ = std::fs::write(&path, toml_string);
}