mnml-rs 0.2.13

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client.
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Wizard state for `Pane::NewCloudAgentWizard`. v2 redesigned
//! around the **Claude Agent SDK** as the only agent (per user
//! 2026-06-27). Picks a SOURCE (GitHub PR / Bitbucket PR / manual
//! prompt), optionally multi-selects N items from a list,
//! picks an ACTION template (triage/review/test/custom), then
//! fires one Claude Code session per selected item.
//!
//! Steps:
//!   1. Pick source
//!   2. (PR sources) Multi-select PR list
//!   3. Pick action
//!   4. (Custom action) Type the prompt
//!   5. Review + submit
//!
//! On submit, for each selected PR:
//!   - `gh pr checkout <num>` (or Bitbucket equivalent)
//!   - Spawn `claude --print "<action prompt> for PR #<num>"` in
//!     a Pty pane scoped to the worktree
//!
//! For the manual prompt source, spawn one Claude session in the
//! current workspace with the user-typed prompt.

use std::sync::mpsc::Receiver;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Source {
    /// Pick from `gh pr list` on the user's active repo.
    #[default]
    GitHubPr,
    /// Pick from the user's Bitbucket repo PRs (requires
    /// BITBUCKET_PERSONAL_TOKEN + BITBUCKET_USERNAME env vars).
    BitbucketPr,
    /// No list — type a single prompt, fire one agent in the
    /// current workspace.
    ManualPrompt,
}

impl Source {
    pub fn label(self) -> &'static str {
        match self {
            Source::GitHubPr => "GitHub PR",
            Source::BitbucketPr => "Bitbucket PR",
            Source::ManualPrompt => "Manual prompt",
        }
    }
    pub fn hint(self) -> &'static str {
        match self {
            Source::GitHubPr => "Open PRs from `gh pr list` on the active repo",
            Source::BitbucketPr => "Open PRs from Bitbucket (BITBUCKET_PERSONAL_TOKEN required)",
            Source::ManualPrompt => "Skip the list — type a single task and fire one agent",
        }
    }
    pub fn all() -> &'static [Source] {
        &[Source::GitHubPr, Source::BitbucketPr, Source::ManualPrompt]
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Action {
    /// "Triage this PR — summarise the change, list risks,
    /// suggest follow-up tickets."
    #[default]
    Triage,
    /// "Review this PR — find correctness / security / style
    /// issues; suggest fixes."
    Review,
    /// "Run the relevant tests for this PR and report results."
    Test,
    /// User types the prompt verbatim.
    Custom,
}

impl Action {
    pub fn label(self) -> &'static str {
        match self {
            Action::Triage => "Triage",
            Action::Review => "Review",
            Action::Test => "Test",
            Action::Custom => "Custom prompt",
        }
    }
    pub fn hint(self) -> &'static str {
        match self {
            Action::Triage => "Summarise the change, list risks, suggest follow-ups",
            Action::Review => "Find correctness / security / style issues; suggest fixes",
            Action::Test => "Run the relevant tests and report results",
            Action::Custom => "Type your own prompt — full agentic autonomy",
        }
    }
    pub fn all() -> &'static [Action] {
        &[Action::Triage, Action::Review, Action::Test, Action::Custom]
    }
    /// Render the action's default prompt as a template — the
    /// `<num>` placeholder is replaced with the actual PR number
    /// at submit time. Manual / Custom action returns the user's
    /// typed prompt verbatim from `pane.custom_prompt`.
    ///
    /// Baseline used when the user hasn't set a per-action override
    /// under `[ai.review_templates]` in config. See
    /// `prompt_template_from` for the config-aware resolution.
    pub fn prompt_template(self) -> &'static str {
        match self {
            Action::Triage => {
                "Triage PR #<num>: summarise the change in 3-5 bullets, \
                 enumerate risks (regressions, security, perf), and suggest \
                 follow-up tickets. Read the diff first, then any touched \
                 modules to ground the risk assessment."
            }
            Action::Review => {
                "Review PR #<num>: act as a senior reviewer. Find \
                 correctness issues, security issues, style nits, and \
                 missing tests. Comment with file:line citations. \
                 Prioritise blockers."
            }
            Action::Test => {
                "Run the relevant tests for PR #<num>. Identify which test \
                 suites cover the changed code, run them, and report any \
                 failures with reproduction steps."
            }
            Action::Custom => "<custom>",
        }
    }

    /// #997 (2026-08-19) — resolve a prompt template with per-user
    /// overrides. Users tune the Triage / Review / Test prompt via:
    ///
    /// ```toml
    /// [ai.review_templates]
    /// triage = "Your triage prompt referencing <num>"
    /// review = "..."
    /// test   = "..."
    /// ```
    ///
    /// Unset → falls back to `prompt_template()` (the shipped
    /// default). Blank string in config → also falls back (treats
    /// `""` as "unset", so users can't silently break their own
    /// wizard by clearing a value). Whitespace-only same story.
    /// Custom action is never resolved via config — it's the
    /// user's typed prompt for that one submission.
    pub fn prompt_template_from(self, cfg: &crate::config::Config) -> String {
        if matches!(self, Action::Custom) {
            return self.prompt_template().to_string();
        }
        let key = match self {
            Action::Triage => "triage",
            Action::Review => "review",
            Action::Test => "test",
            Action::Custom => unreachable!(),
        };
        let user_override = cfg
            .ai
            .as_table()
            .and_then(|t| t.get("review_templates"))
            .and_then(|v| v.as_table())
            .and_then(|t| t.get(key))
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .map(str::to_string);
        user_override.unwrap_or_else(|| self.prompt_template().to_string())
    }
}

/// One row in the PR multi-select list.
#[derive(Debug, Clone)]
pub struct PrRow {
    pub number: u32,
    pub title: String,
    pub author: String,
    pub state: String,
    /// True when the user has checked this row for inclusion.
    pub selected: bool,
}

/// Worker events for the PR-list fetcher (gh or Bitbucket).
pub enum PrListEvent {
    Rows(Vec<PrRow>),
    Done,
    Error(String),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WizardStep {
    Source,
    PrList,
    Action,
    CustomPrompt,
    Review,
}

#[derive(Debug)]
pub struct NewCloudAgentWizardPane {
    pub step: WizardStep,
    /// Cursor row over the focused step.
    pub focus_row: usize,

    // ─── source step ────────────────────────────────────────────
    pub source: Source,

    // ─── PR list step ───────────────────────────────────────────
    pub pr_rows: Vec<PrRow>,
    pub pr_loading: bool,
    pub pr_err: Option<String>,
    pub pr_rx: Option<Receiver<PrListEvent>>,
    /// `gh pr list` doesn't paginate by default; we cap display at
    /// 50 to keep things scannable.
    pub pr_cap: usize,

    // ─── action step ───────────────────────────────────────────
    pub action: Action,

    // ─── custom prompt step ─────────────────────────────────────
    pub custom_prompt: String,

    // ─── submission state ──────────────────────────────────────
    pub submitting: bool,
    pub last_message: Option<String>,
}

impl NewCloudAgentWizardPane {
    pub fn new() -> Self {
        Self {
            step: WizardStep::Source,
            focus_row: 0,
            source: Source::default(),
            pr_rows: Vec::new(),
            pr_loading: false,
            pr_err: None,
            pr_rx: None,
            pr_cap: 50,
            action: Action::default(),
            custom_prompt: String::new(),
            submitting: false,
            last_message: None,
        }
    }

    pub fn title(&self) -> &'static str {
        "+ New Cloud Agent"
    }

    /// Move forward in the step graph. Returns false on Review
    /// (caller should fire submit).
    pub fn next_step(&mut self) -> bool {
        let next = match self.step {
            WizardStep::Source => match self.source {
                Source::ManualPrompt => WizardStep::CustomPrompt,
                _ => WizardStep::PrList,
            },
            WizardStep::PrList => WizardStep::Action,
            WizardStep::Action => match self.action {
                Action::Custom => WizardStep::CustomPrompt,
                _ => WizardStep::Review,
            },
            WizardStep::CustomPrompt => WizardStep::Review,
            WizardStep::Review => return false,
        };
        self.step = next;
        self.focus_row = 0;
        true
    }

    pub fn prev_step(&mut self) {
        let prev = match self.step {
            WizardStep::Source => WizardStep::Source,
            WizardStep::PrList => WizardStep::Source,
            WizardStep::Action => match self.source {
                Source::ManualPrompt => WizardStep::CustomPrompt, // ManualPrompt skips PrList; back goes Source via prev
                _ => WizardStep::PrList,
            },
            WizardStep::CustomPrompt => match self.source {
                Source::ManualPrompt => WizardStep::Source,
                _ => WizardStep::Action,
            },
            WizardStep::Review => match self.action {
                Action::Custom => WizardStep::CustomPrompt,
                _ => WizardStep::Action,
            },
        };
        self.step = prev;
        self.focus_row = 0;
    }

    /// How many PRs are currently checked.
    pub fn selected_count(&self) -> usize {
        self.pr_rows.iter().filter(|r| r.selected).count()
    }

    /// Drain the PR-list worker channel.
    pub fn drain(&mut self) -> bool {
        let mut changed = false;
        if let Some(rx) = self.pr_rx.take() {
            let mut still_open = true;
            while let Ok(ev) = rx.try_recv() {
                changed = true;
                match ev {
                    PrListEvent::Rows(mut rows) => self.pr_rows.append(&mut rows),
                    PrListEvent::Done => {
                        self.pr_loading = false;
                        still_open = false;
                    }
                    PrListEvent::Error(e) => {
                        self.pr_err = Some(e);
                        self.pr_loading = false;
                        still_open = false;
                    }
                }
            }
            if still_open {
                self.pr_rx = Some(rx);
            }
        }
        changed
    }
}

impl Default for NewCloudAgentWizardPane {
    fn default() -> Self {
        Self::new()
    }
}

/// Spawn a worker that runs `gh pr list --json number,title,state,author` on
/// `repo_dir` and streams parsed rows back via the channel.
pub fn spawn_gh_pr_fetcher(repo_dir: std::path::PathBuf) -> Receiver<PrListEvent> {
    use std::process::{Command, Stdio};
    use std::sync::mpsc::{Sender, channel};

    let (tx, rx): (Sender<PrListEvent>, Receiver<PrListEvent>) = channel();
    std::thread::spawn(move || {
        let out = Command::new("gh")
            .args([
                "pr",
                "list",
                "--state",
                "open",
                "--limit",
                "50",
                "--json",
                "number,title,state,author",
            ])
            .current_dir(&repo_dir)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .output();
        let out = match out {
            Ok(o) => o,
            Err(e) => {
                let _ = tx.send(PrListEvent::Error(format!("spawn gh: {e}")));
                return;
            }
        };
        if !out.status.success() {
            let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
            let _ = tx.send(PrListEvent::Error(format!("gh pr list failed: {stderr}")));
            return;
        }
        let parsed: Result<Vec<GhPr>, _> = serde_json::from_slice(&out.stdout);
        let rows: Vec<PrRow> = match parsed {
            Ok(v) => v
                .into_iter()
                .map(|p| PrRow {
                    number: p.number,
                    title: p.title,
                    author: p.author.map(|a| a.login).unwrap_or_default(),
                    state: p.state,
                    selected: false,
                })
                .collect(),
            Err(e) => {
                let _ = tx.send(PrListEvent::Error(format!("parse gh JSON: {e}")));
                return;
            }
        };
        let _ = tx.send(PrListEvent::Rows(rows));
        let _ = tx.send(PrListEvent::Done);
    });
    rx
}

#[derive(serde::Deserialize)]
struct GhPr {
    number: u32,
    title: String,
    state: String,
    author: Option<GhAuthor>,
}

#[derive(serde::Deserialize)]
struct GhAuthor {
    login: String,
}

/// Spawn a worker that fetches Bitbucket PRs for the given repo.
/// Reads BITBUCKET_PERSONAL_TOKEN + BITBUCKET_USERNAME from the
/// environment; bails with an error if either is missing.
/// `repo_slug` is `<workspace>/<repo>` (Bitbucket convention).
pub fn spawn_bitbucket_pr_fetcher(repo_slug: String) -> Receiver<PrListEvent> {
    use std::sync::mpsc::{Sender, channel};

    let (tx, rx): (Sender<PrListEvent>, Receiver<PrListEvent>) = channel();
    std::thread::spawn(move || {
        let token = match std::env::var("BITBUCKET_PERSONAL_TOKEN") {
            Ok(t) => t,
            Err(_) => {
                let _ = tx.send(PrListEvent::Error(
                    "BITBUCKET_PERSONAL_TOKEN not set in environment".to_string(),
                ));
                return;
            }
        };
        let user = match std::env::var("BITBUCKET_USERNAME") {
            Ok(u) => u,
            Err(_) => {
                let _ = tx.send(PrListEvent::Error(
                    "BITBUCKET_USERNAME not set in environment".to_string(),
                ));
                return;
            }
        };
        // Bitbucket Cloud API:
        //   GET /2.0/repositories/{workspace}/{repo}/pullrequests
        // Basic auth: BB username + app password (the "personal token" is
        // typically an app password in the Bitbucket Cloud sense).
        let url = format!(
            "https://api.bitbucket.org/2.0/repositories/{repo_slug}/pullrequests?state=OPEN&pagelen=50"
        );
        use base64::Engine;
        let basic = base64::engine::general_purpose::STANDARD.encode(format!("{user}:{token}"));
        let req = crate::http::Request {
            method: "GET".to_string(),
            url,
            headers: vec![
                ("Authorization".to_string(), format!("Basic {basic}")),
                ("Accept".to_string(), "application/json".to_string()),
            ],
            body: None,
            insecure: false,
        };
        let resp = match crate::http::send(&req) {
            Ok(r) => r,
            Err(e) => {
                let _ = tx.send(PrListEvent::Error(format!("bitbucket fetch: {e}")));
                return;
            }
        };
        if resp.status < 200 || resp.status >= 300 {
            let _ = tx.send(PrListEvent::Error(format!(
                "bitbucket HTTP {} — check token + repo slug",
                resp.status
            )));
            return;
        }
        let body = resp.body;
        let parsed: Result<BbPrPage, _> = serde_json::from_str(&body);
        let rows: Vec<PrRow> = match parsed {
            Ok(p) => p
                .values
                .into_iter()
                .map(|pr| PrRow {
                    number: pr.id,
                    title: pr.title,
                    author: pr.author.map(|a| a.display_name).unwrap_or_default(),
                    state: pr.state,
                    selected: false,
                })
                .collect(),
            Err(e) => {
                let _ = tx.send(PrListEvent::Error(format!("parse bitbucket JSON: {e}")));
                return;
            }
        };
        let _ = tx.send(PrListEvent::Rows(rows));
        let _ = tx.send(PrListEvent::Done);
    });
    rx
}

#[derive(serde::Deserialize)]
struct BbPrPage {
    values: Vec<BbPr>,
}

#[derive(serde::Deserialize)]
struct BbPr {
    id: u32,
    title: String,
    state: String,
    author: Option<BbAuthor>,
}

#[derive(serde::Deserialize)]
struct BbAuthor {
    display_name: String,
}

#[cfg(test)]
mod tests {
    use super::Action;
    use crate::config::Config;

    fn cfg_with_ai(toml_str: &str) -> Config {
        Config {
            ai: toml::from_str(toml_str).expect("valid ai toml"),
            ..Config::default()
        }
    }

    #[test]
    fn prompt_template_from_falls_back_to_default_when_unset() {
        let cfg = Config::default();
        for action in [Action::Triage, Action::Review, Action::Test] {
            let resolved = action.prompt_template_from(&cfg);
            assert_eq!(
                resolved,
                action.prompt_template(),
                "{:?} should fall back to default",
                action
            );
        }
    }

    #[test]
    fn prompt_template_from_uses_user_override_when_set() {
        let cfg = cfg_with_ai(
            r#"
            [review_templates]
            triage = "MY TRIAGE for PR #<num>"
            review = "MY REVIEW for #<num>"
            test   = "run tests for <num>"
            "#,
        );
        assert_eq!(
            Action::Triage.prompt_template_from(&cfg),
            "MY TRIAGE for PR #<num>"
        );
        assert_eq!(
            Action::Review.prompt_template_from(&cfg),
            "MY REVIEW for #<num>"
        );
        assert_eq!(
            Action::Test.prompt_template_from(&cfg),
            "run tests for <num>"
        );
    }

    #[test]
    fn prompt_template_from_blank_string_falls_back() {
        let cfg = cfg_with_ai(
            r#"
            [review_templates]
            triage = "   "
            review = ""
            "#,
        );
        assert_eq!(
            Action::Triage.prompt_template_from(&cfg),
            Action::Triage.prompt_template()
        );
        assert_eq!(
            Action::Review.prompt_template_from(&cfg),
            Action::Review.prompt_template()
        );
    }

    #[test]
    fn prompt_template_from_custom_ignores_config() {
        let cfg = cfg_with_ai(
            r#"
            [review_templates]
            custom = "won't be used"
            "#,
        );
        assert_eq!(
            Action::Custom.prompt_template_from(&cfg),
            Action::Custom.prompt_template()
        );
    }
}