mnml-rs 0.2.22

A NvChad-style terminal IDE in Rust — vim or standard editing, LSP, git, and an embedded HTTP client. Final Rust release; the project continues in Zig at the same repository.
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
//! Findings activity-bar panel — workspace-scoped tester / review
//! report archive (`.mnml/findings/*.md`).
//!
//! Zero-config cross-project: `cd ~/Projects/mixr && mnml .` picks up
//! `~/Projects/mixr/.mnml/findings/` automatically. Testers write into
//! that dir; the panel surfaces the results for review.
//!
//! v1 scope: flat list of finding files sorted by mtime desc + a
//! filter row. Click a row → opens the markdown in an editor pane.
//! v2 will add right-click actions (archive / delete / mark reviewed).
//!
//! Structurally mirrors `notes_panel` — same file-cache lifecycle,
//! same filter idiom, same click routing.

use ratatui::{
    Frame,
    layout::Rect,
    style::Style,
    text::{Line, Span},
    widgets::{Block, Paragraph},
};

use crate::app::App;
use crate::ui::theme;

pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) {
    let t = theme::cur();
    let bg = t.bg_darker;
    frame.render_widget(Block::default().style(Style::default().bg(bg)), area);
    if area.height < 2 || area.width < 8 {
        return;
    }
    app.rects.findings_panel_files.clear();
    app.rects.findings_panel_filter_input = None;

    if !app.findings_panel_scanned_once {
        app.findings_panel_refresh();
    }
    let all_files = app.findings_panel_files_cache.clone();
    // 2026-08-23 (user ask) — apply the `/` filter against each
    // file's rendered relative name (same string the row shows),
    // case-insensitive. Empty filter passes everything through.
    let root = findings_dir(&app.workspace);
    let filter_lc = app.findings_panel_filter.to_ascii_lowercase();
    let files: Vec<std::path::PathBuf> = all_files
        .iter()
        .filter(|p| {
            if filter_lc.is_empty() {
                return true;
            }
            let rel = p.strip_prefix(&root).unwrap_or(p);
            let name = rel.with_extension("").to_string_lossy().into_owned();
            name.to_ascii_lowercase().contains(&filter_lc)
        })
        .cloned()
        .collect();

    // Header — "FINDINGS  (N)" — count is cheap + useful. When
    // the filter is active, show `M of N` (mirrors Notes / TODOs).
    // 2026-08-24 (user ask) — refresh chip in top-right, matching
    // git + todos + notes.
    let subtitle = if filter_lc.is_empty() {
        format!("  ({})", all_files.len())
    } else {
        format!("  ({} of {})", files.len(), all_files.len())
    };
    // The `sort:` chip is the same idiom as CLOUD AGENTS' `view:`
    // chip — click cycles, right-click lists every mode with a ✓ on
    // the current one.
    // Pad to the widest mode label so the chip keeps a fixed width and
    // cannot slide out from under a repeat-clicking pointer.
    let sort_widest = crate::ui::list_sort::ListSort::all()
        .iter()
        .map(|m| m.label().chars().count())
        .max()
        .unwrap_or(0);
    let sort_chip = crate::ui::panel_chrome::mode_chip_text(
        "sort",
        app.panel_sort("findings").label(),
        sort_widest,
    );
    let (findings_sort, findings_refresh) = crate::ui::panel_chrome::draw_caps_header_with_chips(
        frame,
        Rect {
            x: area.x,
            y: area.y,
            width: area.width,
            height: 1,
        },
        "FINDINGS",
        Some(&subtitle),
        Some(&sort_chip),
        bg,
        &t,
        app.config.ui.ascii_icons,
    );
    app.rects.findings_panel_sort_chip = findings_sort;
    app.rects.findings_panel_refresh_chip = findings_refresh;

    // Filter row (row 1) — mirrors todos_panel exactly: chip bg,
    // magnifier glyph, `/ filter` placeholder, `▏` cursor when
    // focused, `type to filter…` placeholder while focused-empty.
    {
        let y_filter = area.y + 1;
        if y_filter < area.y + area.height {
            let focused = app.findings_panel_filter_focused;
            let bg_chip = crate::ui::panel_chrome::filter_chip_bg(&t);
            let fg_chip = if app.findings_panel_filter.is_empty() && !focused {
                t.comment
            } else {
                t.fg
            };
            let display = if app.findings_panel_filter.is_empty() {
                crate::ui::filter_placeholder::for_state(focused).to_string()
            } else {
                app.findings_panel_filter.clone()
            };
            let cursor = if focused { "\u{258F}" } else { " " };
            let pad = (area.width as usize).saturating_sub(3 + display.chars().count() + 1 + 1);
            let line = Line::from(vec![
                Span::styled(" ", Style::default().bg(bg)),
                Span::styled(
                    format!("{} ", crate::ui::search_glyph::NERD),
                    Style::default().fg(t.comment).bg(bg_chip),
                ),
                Span::styled(display, Style::default().fg(fg_chip).bg(bg_chip)),
                Span::styled(cursor, Style::default().fg(t.cyan).bg(bg_chip)),
                Span::styled(" ".repeat(pad), Style::default().bg(bg_chip)),
                Span::styled(" ", Style::default().bg(bg)),
            ]);
            let row_rect = Rect {
                x: area.x,
                y: y_filter,
                width: area.width,
                height: 1,
            };
            frame.render_widget(Paragraph::new(line), row_rect);
            app.rects.findings_panel_filter_input = Some(row_rect);
        }
    }

    // The row at `area.y + 2` was left blank by R16 design-critic
    // (2026-08-24) precisely BECAUSE this panel had no `+ New finding`
    // chip to put in it. It has one now (user ask 2026-09-01), so the
    // reserved row is finally occupied and the layout matches
    // NOTES/SESSIONS instead of being a lone exception.
    let mut y = area.y + 2;
    if y < area.y + area.height {
        let label = "+ New finding";
        let chip_w = crate::ui::action_button::chip_width(label);
        let avail = area.width.saturating_sub(1);
        let new_rect = Rect {
            x: area.x + 1,
            y,
            width: chip_w.min(avail),
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(crate::ui::action_button::chip_line(
                label,
                crate::ui::action_button::primary(&t),
            )),
            new_rect,
        );
        app.rects.findings_panel_new_chip = Some(new_rect);
        y += 2;
    }

    if files.is_empty() {
        // Distinguish "no files at all" from "filter matched nothing"
        // so the user knows whether the filter is what's hiding rows.
        let empty_msg = if filter_lc.is_empty() {
            "No findings yet.".to_string()
        } else {
            format!(
                "No findings match /{} — {} in workspace",
                app.findings_panel_filter,
                all_files.len()
            )
        };
        crate::ui::empty_state::draw(
            frame,
            Rect {
                x: area.x,
                y,
                width: area.width,
                height: area.height.saturating_sub(y - area.y),
            },
            &empty_msg,
            Some("Stored under .mnml/findings/*.md"),
            bg,
            &t,
        );
        return;
    }

    // Rows — icon + name + right-aligned age (mtime).
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);
    // `root` computed above alongside the filter — reused here so
    // nested tester-round dirs render `round/foo` instead of
    // losing all context to file_stem.
    // Clamp the cursor to the filtered length so a stale index left by
    // a narrowing filter doesn't highlight nothing.
    let clamped_cursor = app.findings_panel_cursor.min(files.len().saturating_sub(1));
    app.findings_panel_cursor = clamped_cursor;
    let visible_rows = (area.height as usize).saturating_sub(4);
    let mut scroll = app.findings_panel_scroll;
    let (first, shown, needs_sb) = crate::ui::panel_chrome::list_scroll_window(
        &mut scroll,
        clamped_cursor,
        files.len(),
        visible_rows,
    );
    app.findings_panel_scroll = scroll;
    let row_w = if needs_sb {
        area.width.saturating_sub(1)
    } else {
        area.width
    };
    #[allow(clippy::explicit_counter_loop)]
    for (row_i, path) in files.iter().enumerate().skip(first).take(shown) {
        if y >= area.y + area.height {
            break;
        }
        let is_focused_row = row_i == clamped_cursor;
        let row_bg = if is_focused_row { t.bg2 } else { bg };
        // Relative-to-findings-root name so nested rows keep their
        // round-dir context. Strip the `.md` extension for compactness.
        let rel = path.strip_prefix(&root).unwrap_or(path);
        let name = rel.with_extension("").to_string_lossy().into_owned();
        let name = if name.is_empty() {
            path.file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("finding")
                .to_string()
        } else {
            name
        };
        let icon = if app.config.ui.ascii_icons {
            "◧"
        } else {
            // nf-md-file-search — same glyph as the activity-bar icon.
            "\u{F1623}"
        };
        let age_str: String = std::fs::metadata(path)
            .and_then(|m| m.modified())
            .ok()
            .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
            .map(|d| {
                let secs = now.saturating_sub(d.as_secs() as i64);
                crate::ui::git_graph_view::humanize_age(secs)
            })
            .unwrap_or_default();
        // Budgeted against `row_w`, not `area.width` — with a
        // scrollbar present this clipped the last character of the age
        // column (`13m` → `13`, `now` → `no`). NOTES had the identical
        // arithmetic fixed already; this one was missed.
        const AGE_GAP: usize = 2;
        let name_width = (row_w as usize)
            .saturating_sub(5)
            .saturating_sub(AGE_GAP)
            .saturating_sub(age_str.chars().count());
        let name_clipped: String = name.chars().take(name_width).collect();
        let name_padded = format!("{name_clipped:<width$}", width = name_width);
        let row_rect = Rect {
            x: area.x,
            y,
            width: row_w,
            height: 1,
        };
        frame.render_widget(
            Paragraph::new(Line::from(vec![
                // Two unhighlighted cells keep the band off the panel
                // edge, then the focused row's blue `▌` accent — kept in
                // step across TODOS / FINDINGS / NOTES. Widening one
                // alone is what put TODOS out of line with its siblings
                // before.
                Span::styled(" ", Style::default().bg(bg)),
                Span::styled(
                    crate::ui::gutter::marker(is_focused_row),
                    Style::default().fg(t.green).bg(row_bg),
                ),
                Span::styled(format!("{icon} "), Style::default().fg(t.cyan).bg(row_bg)),
                Span::styled(name_padded, Style::default().fg(t.fg).bg(row_bg)),
                Span::styled(
                    format!("{}{age_str}", " ".repeat(AGE_GAP)),
                    Style::default().fg(t.comment).bg(row_bg),
                ),
            ])),
            row_rect,
        );
        app.rects
            .findings_panel_files
            .push((row_rect, path.clone()));
        y += 1;
    }
    // Content rect, so a wheel event over the list can be routed
    // to this panel's scroll offset.
    app.rects.findings_panel_area = Some(Rect {
        x: area.x,
        y: area.y + 4,
        width: area.width,
        height: visible_rows as u16,
    });
    if needs_sb {
        let sb = Rect {
            x: area.x + row_w,
            y: area.y + 4,
            width: 1,
            height: visible_rows as u16,
        };
        crate::ui::scrollbar::paint_simple_scrollbar(
            frame,
            sb,
            &t,
            files.len(),
            visible_rows,
            first,
        );
        app.rects.scrollbars.push(crate::app::ScrollbarHit {
            area: sb,
            pane_id: 0,
            total: files.len(),
            viewport: visible_rows,
            kind: crate::app::ScrollbarKind::FindingsPanel,
        });
    }
}

/// The findings directory for a workspace. Not created eagerly —
/// only when something writes there (test agent, or a future
/// `+ New finding` action).
pub fn findings_dir(workspace: &std::path::Path) -> std::path::PathBuf {
    workspace.join(".mnml").join("findings")
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    fn app_with_findings(names: &[&str]) -> (tempfile::TempDir, crate::app::App) {
        let d = tempfile::tempdir().unwrap();
        let mut app =
            crate::app::App::new(d.path().to_path_buf(), crate::config::Config::default()).unwrap();
        app.config.ui.ascii_icons = true;
        let fd = findings_dir(d.path());
        std::fs::create_dir_all(&fd).unwrap();
        for n in names {
            std::fs::write(fd.join(format!("{n}.md")), "x").unwrap();
        }
        app.findings_panel_refresh();
        (d, app)
    }

    fn render(app: &mut crate::app::App, w: u16) -> ratatui::buffer::Buffer {
        let mut term = Terminal::new(TestBackend::new(w, 12)).unwrap();
        term.draw(|f| {
            draw(
                f,
                app,
                Rect {
                    x: 0,
                    y: 0,
                    width: w,
                    height: 12,
                },
            )
        })
        .unwrap();
        term.backend().buffer().clone()
    }

    /// FINDINGS had no cursor at all, so no row could be highlighted and
    /// the panel was the odd one out beside TODOS and NOTES (user ask:
    /// "right now i cant highlight, it shoudl be same as notes and todos
    /// ands also have colored gutter").
    #[test]
    fn the_focused_row_is_inset_and_carries_the_blue_accent_bar() {
        let (_d, mut app) = app_with_findings(&["alpha"]);
        let t = theme::cur();
        let buf = render(&mut app, 60);
        let y = (0..12u16)
            .find(|&y| (0..60).any(|x| buf[(x, y)].symbol() == "▌"))
            .expect("no row carries an accent bar");

        assert_eq!(
            buf[(0, y)].bg,
            t.bg_darker,
            "column 0 is highlighted — the band is welded to the panel edge"
        );
        assert_eq!(
            buf[(1, y)].symbol(),
            "▌",
            "the accent bar is not at column 1 — it should sit under the \
             filter row's magnifier"
        );
        assert_eq!(buf[(1, y)].fg, t.green, "the accent bar is not green");
        assert_eq!(
            buf[(1, y)].bg,
            t.bg2,
            "the accent sits outside the highlight band"
        );
        // Column 2 is where the row's TEXT begins now — the icon. Asserted
        // so the shift can't silently drift back and leave a dead cell
        // between the accent and the content.
        assert_ne!(
            buf[(2, y)].symbol(),
            " ",
            "column 2 is blank — the row content did not follow the accent"
        );
    }

    /// The `+ New finding` chip must render — including on an EMPTY
    /// panel, which is exactly when a user needs it most. The panel had
    /// no create action at all until 2026-09-01, while NOTES and TODOS
    /// both did; its own module docstring referred to one that did not
    /// exist.
    #[test]
    fn the_new_finding_chip_renders_even_when_empty() {
        let (_d, mut app) = app_with_findings(&[]);
        let buf = render(&mut app, 60);
        let text: String = (0..12u16)
            .map(|y| (0..60).map(|x| buf[(x, y)].symbol()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            text.contains("+ New finding"),
            "no create chip on an empty FINDINGS panel:\n{text}"
        );
        assert!(
            app.rects.findings_panel_new_chip.is_some(),
            "the chip painted but registered no click rect — a dead button"
        );
    }

    /// ...and it must still be there once the panel HAS rows, rather
    /// than being pushed out by the list.
    #[test]
    fn the_new_finding_chip_survives_a_populated_list() {
        let (_d, mut app) = app_with_findings(&["alpha", "beta"]);
        let buf = render(&mut app, 60);
        let text: String = (0..12u16)
            .map(|y| (0..60).map(|x| buf[(x, y)].symbol()).collect::<String>())
            .collect::<Vec<_>>()
            .join("\n");
        assert!(
            text.contains("+ New finding"),
            "chip vanished once rows existed"
        );
        assert!(text.contains("alpha"), "rows stopped rendering");
    }

    /// The accent must FOLLOW the cursor, not sit on row 0 forever.
    #[test]
    fn the_accent_bar_moves_with_the_cursor() {
        let (_d, mut app) = app_with_findings(&["alpha", "beta"]);
        let first = (0..12u16)
            .find(|&y| {
                let b = render(&mut app, 60);
                (0..60).any(|x| b[(x, y)].symbol() == "▌")
            })
            .expect("no accent row before moving");

        app.findings_panel_cursor_down();
        let buf = render(&mut app, 60);
        let second = (0..12u16)
            .find(|&y| (0..60).any(|x| buf[(x, y)].symbol() == "▌"))
            .expect("no accent row after moving");

        assert_ne!(
            first, second,
            "the accent bar stayed on row {first} after the cursor moved down"
        );
    }

    /// A cursor left past the end by a narrowing filter must not leave
    /// the panel with no highlight at all.
    #[test]
    fn a_stale_cursor_is_clamped_into_range() {
        let (_d, mut app) = app_with_findings(&["alpha", "beta"]);
        app.findings_panel_cursor = 99;
        let buf = render(&mut app, 60);
        assert!(
            (0..12u16).any(|y| (0..60).any(|x| buf[(x, y)].symbol() == "▌")),
            "a stale cursor left the panel with no highlighted row"
        );
        assert!(
            app.findings_panel_cursor < 2,
            "cursor {} was not clamped to the row count",
            app.findings_panel_cursor
        );
    }
}

#[cfg(test)]
mod sort_chip_tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    /// USER 2026-09-03 — "todos and findings and nots still dont have
    /// the sorting options". The sort existed and was persisted, but
    /// the only way to reach it was right-clicking the REFRESH chip,
    /// so nothing on screen said the panel could be sorted at all.
    ///
    /// Asserts the chip is visible in the real panel, and that the
    /// registered rect covers it — a rect that misses the pixels is a
    /// chip you can see but not click.
    #[test]
    fn the_findings_header_shows_a_clickable_sort_chip() {
        let d = tempfile::tempdir().unwrap();
        let mut app =
            crate::app::App::new(d.path().to_path_buf(), crate::config::Config::default()).unwrap();
        app.config.ui.ascii_icons = true;

        let (w, h) = (70u16, 10u16);
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| {
            draw(
                f,
                &mut app,
                Rect {
                    x: 0,
                    y: 0,
                    width: w,
                    height: h,
                },
            )
        })
        .unwrap();
        let buf = term.backend().buffer();
        let header: String = (0..w).map(|x| buf[(x, 0)].symbol()).collect();

        assert!(
            header.contains("sort:"),
            "no sort chip in the FINDINGS header: {header:?}"
        );
        let r = app
            .rects
            .findings_panel_sort_chip
            .expect("the chip painted but registered no click target");
        let covered: String = header
            .chars()
            .skip(r.x as usize)
            .take(r.width as usize)
            .collect();
        assert!(
            covered.contains("sort:"),
            "the click rect does not cover the chip: {covered:?}"
        );
    }

    /// Clicking the chip must CYCLE the mode and persist it. Guards
    /// the whole path, not just the paint.
    #[test]
    fn clicking_the_sort_chip_cycles_the_mode() {
        // `set_panel_sort` PERSISTS, so redirect MNML_DATA_ROOT or the
        // click writes into the developer's real config.toml. Lock
        // first; the EnvGuard is declared after so it drops BEFORE the
        // lock (locals drop in reverse declaration order).
        let cfg_dir = tempfile::tempdir().unwrap();
        let _lock = crate::test_env_lock()
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        let _env = crate::EnvGuard::set("MNML_DATA_ROOT", cfg_dir.path());
        let d = tempfile::tempdir().unwrap();
        let mut app =
            crate::app::App::new(d.path().to_path_buf(), crate::config::Config::default()).unwrap();
        app.config.ui.ascii_icons = true;

        let (w, h) = (70u16, 10u16);
        let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
        term.draw(|f| {
            draw(
                f,
                &mut app,
                Rect {
                    x: 0,
                    y: 0,
                    width: w,
                    height: h,
                },
            )
        })
        .unwrap();
        let r = app.rects.findings_panel_sort_chip.expect("no chip rect");
        let before = app.panel_sort("findings");
        crate::tui::mouse::dispatch_mouse(
            &mut app,
            ratatui::crossterm::event::MouseEvent {
                kind: ratatui::crossterm::event::MouseEventKind::Down(
                    ratatui::crossterm::event::MouseButton::Left,
                ),
                column: r.x + 1,
                row: r.y,
                modifiers: ratatui::crossterm::event::KeyModifiers::NONE,
            },
        );
        assert_ne!(
            app.panel_sort("findings"),
            before,
            "clicking the sort chip did not change the mode"
        );
    }
}