tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
use super::super::render::{confirm_delete_buttons, confirm_delete_prompt};
#[allow(clippy::wildcard_imports)]
use super::super::*;
use std::fs;
use tempfile::TempDir;

/// A test config with auto-migration off, so tests that use bare/legacy
/// fixtures stay about their own concern. Auto-migration is covered by
/// dedicated tests (`tests/cli.rs`, `tests/mcp.rs`, and storage).
pub(super) fn test_config() -> Config {
    let mut config = Config::default();
    config.layout.move_on_change = false;
    config
}

pub(super) fn make_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    (tmp, app)
}

pub(super) fn write_issue(
    dir: &std::path::Path,
    name: &str,
    number: u32,
    title: &str,
    status: &str,
    commit: Option<&str>,
) {
    let commit_line = match commit {
        Some(h) => format!("commit: \"{h}\""),
        None => String::new(),
    };
    let contents = format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{commit_line}\n---\n\nBody text."
    );
    fs::write(dir.join(name), contents).unwrap();
}

/// Temp fixture with `n` issues for the throughput harness, ~10% `todo` and
/// the rest `done` so the board resembles a real one.
pub(super) fn perf_fixture(n: u32) -> (TempDir, Config) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.save(&config_path).unwrap();
    for i in 1..=n {
        let status = if i % 10 == 0 { "todo" } else { "done" };
        write_issue(
            &dir,
            &format!("perf-{i:05}.md"),
            i,
            &format!("Card {i:05}"),
            status,
            None,
        );
    }
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    (tmp, config)
}

pub(super) fn press(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, crossterm::event::KeyModifiers::NONE)
}

pub(super) fn press_with_modifiers(
    code: KeyCode,
    modifiers: crossterm::event::KeyModifiers,
) -> KeyEvent {
    KeyEvent::new(code, modifiers)
}

/// A temp store seeded with two cycles (one referencing a stored issue), a
/// milestone file, and one issue referencing both. Cycles carry
/// far-future dates so no rollover dialog steals the initial mode.
pub(super) fn make_app_with_planning() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.cycles.insert(
        "Cycle 1".into(),
        crate::config::PlanningCycle {
            description: Some("kickoff".into()),
            start_date: Some("2026-10-01".into()),
            due_date: Some("2999-12-31".into()),
        },
    );
    config.cycles.insert(
        "Cycle 2".into(),
        crate::config::PlanningCycle {
            description: Some("next".into()),
            start_date: Some("2999-01-01".into()),
            due_date: Some("2999-01-15".into()),
        },
    );
    let issue = "---\nnumber: 1\ntitle: \"A\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncycles: [\"Cycle 1\"]\nmilestones: [\"GA\"]\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text.";
    fs::create_dir_all(dir.join("alice")).unwrap();
    fs::write(dir.join("alice/2026-01-01-a.md"), issue).unwrap();
    let milestones_dir = tmp.path().join("docs/milestones");
    fs::create_dir_all(&milestones_dir).unwrap();
    fs::write(
            milestones_dir.join("2026-01-01-ga.md"),
            "---\nname: \"GA\"\ntarget_date: \"2026-12-31\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nship it\n",
        )
        .unwrap();
    let config_path = tmp.path().join("tix.toml");
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    (tmp, app)
}

pub(super) fn make_app_with_rollover_dialog() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.cycles.clear();
    config.cycles.insert(
        "Cycle 1".into(),
        crate::config::PlanningCycle {
            description: Some("expired".into()),
            start_date: Some("2000-01-01".into()),
            due_date: Some("2000-01-02".into()),
        },
    );
    config.cycles.insert(
        "Cycle 2".into(),
        crate::config::PlanningCycle {
            description: Some("next".into()),
            start_date: Some("2999-01-01".into()),
            due_date: Some("2999-01-15".into()),
        },
    );
    let issue = "---\nnumber: 1\ntitle: \"A\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncycles: [\"Cycle 1\"]\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text.";
    fs::create_dir_all(dir.join("alice")).unwrap();
    fs::write(dir.join("alice/2026-01-01-a.md"), issue).unwrap();
    let config_path = tmp.path().join("tix.toml");
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    (tmp, app)
}

pub(super) fn filter_modal_focus(app: &App) -> crate::search::FilterField {
    app.filter_modal
        .as_ref()
        .expect("filter modal open")
        .focus()
}

/// An issue whose frontmatter carries a top-level key tix does not know — the
/// shape an editor leaves behind when a user adds their own metadata (#1506).
pub(super) fn write_issue_with_custom_key(dir: &std::path::Path, name: &str, key: &str) {
    write_issue(dir, name, 1, "A", "todo", None);
    let path = dir.join(name);
    let text = std::fs::read_to_string(&path).unwrap();
    let text = text.replace("labels: []\n", &format!("labels: []\n{key}: \"ci-4471\"\n"));
    std::fs::write(&path, text).unwrap();
}

/// A hand-built repair prompt, for the tests that exercise the *view* rather
/// than a round trip: no classified problems, no retained copy.
pub(super) fn repair_mode(message: &str, key: Option<&str>) -> Mode {
    Mode::EditRepair {
        filename: "2026-01-01-a.md".to_string(),
        message: message.to_string(),
        key: key.map(str::to_string),
        problems: Vec::new(),
        temp: None,
        written: true,
        discard_armed: false,
    }
}

pub(super) fn form_focus(app: &App) -> crate::ui::form::FormFocus {
    app.form.as_ref().expect("form open").focus
}

/// Render the date picker once and return the center point of the day cell
/// matching `target` (`YYYY-MM-DD`).
pub(super) fn drawn_date_picker_day(app: &App, target: &str) -> (u16, u16) {
    use ratatui::backend::TestBackend;

    let backend = TestBackend::new(app.frame_size.get().width, app.frame_size.get().height);
    let mut terminal = ratatui::Terminal::new(backend).unwrap();
    terminal
        .draw(|f| crate::app::render(app, f, f.area()))
        .unwrap();

    let picker = app.date_picker.as_ref().expect("picker open");
    let rect = picker.popup_rect(app.frame_size.get());
    let days_y = rect.y + 3;
    let weeks = rect.height.saturating_sub(6);
    for row in 0..weeks {
        for col in 0..7u16 {
            let x = rect.x + 1 + col * 3 + 1;
            let y = days_y + row;
            if picker
                .date_at(app.frame_size.get(), x, y)
                .map(crate::ui::date_picker::format_date)
                .as_deref()
                == Some(target)
            {
                return (x, y);
            }
        }
    }
    panic!("no day cell found for {target}");
}

/// A board with `n` cards in the first column, for the page-step tests.
pub(super) fn make_app_with_cards(n: u32) -> (TempDir, App) {
    let (tmp, mut app) = make_app();
    let dir = app.store.config.issues_dir.clone();
    for i in 1..=n {
        write_issue(
            &dir,
            &format!("card-{i:02}.md"),
            i,
            &format!("Card {i:02}"),
            "todo",
            None,
        );
    }
    app.refresh_corpus().unwrap();
    (tmp, app)
}

/// Four-column board (todo / in progress / in review / done) seeded with
/// one short title per column, framed at 80x40 so every card renders on a
/// single line. `double_click_window` is padded so tests never race the
/// wall clock.
pub(super) fn make_mouse_app() -> (TempDir, App) {
    let (tmp, mut app) = make_app();
    app.mouse.double_click_window = Duration::from_secs(60);
    let dir = app.store.config.issues_dir.clone();
    write_issue(&dir, "a.md", 1, "Alpha", "todo", None);
    write_issue(&dir, "b.md", 2, "Beta", "todo", None);
    write_issue(&dir, "c.md", 3, "Gamma", "in progress", None);
    write_issue(&dir, "d.md", 4, "Delta", "in review", None);
    write_issue(&dir, "e.md", 5, "Epsilon", "done", Some("abc123"));
    app.refresh_corpus().unwrap();
    app.frame_size.set(Rect::new(0, 0, 80, 40));
    (tmp, app)
}

pub(super) fn make_sparse_order_mouse_app() -> (TempDir, App) {
    let (tmp, mut app) = make_app();
    app.mouse.double_click_window = Duration::from_secs(60);
    let dir = app.store.config.issues_dir.clone();
    write_issue(&dir, "a.md", 1, "Alpha", "todo", None);
    write_issue(&dir, "b.md", 2, "Beta", "todo", None);
    write_issue(&dir, "c.md", 3, "Gamma", "todo", None);
    write_issue(&dir, "d.md", 4, "Delta", "todo", None);
    app.refresh_corpus().unwrap();
    app.frame_size.set(Rect::new(0, 0, 80, 40));
    (tmp, app)
}

/// The pointer fixtures, plus one **blocked** card: #1 blocks #2, so dragging
/// or menu-moving #2 into `done` has to raise the acknowledgement prompt.
///
/// WP04's TUI coverage went through the keyboard `>` binding only. A drag-drop
/// and a context-menu item are two more doors into `move_selected_to`, and a
/// door with no test is a door nobody checked.
pub(super) fn make_blocked_mouse_app() -> (TempDir, App) {
    let (tmp, mut app) = make_mouse_app();
    app.store
        .link("1", "2", crate::relationships::RelationKind::Blocks)
        .unwrap();
    app.refresh_corpus().unwrap();
    (tmp, app)
}

/// The index of the `done` column, resolved from the board rather than
/// hard-coded, so a column-order change does not silently retarget the test.
pub(super) fn done_col(app: &App) -> usize {
    let name = app
        .store
        .config
        .default_config()
        .effective_done_column()
        .expect("the fixture board has a done column");
    (0..app.board.total_cols())
        .find(|c| app.board.column_name(*c) == name)
        .unwrap_or_else(|| panic!("no column named {name}"))
}

pub(super) fn down_left(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

pub(super) fn down_right(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Right),
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

pub(super) fn up_left(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::Up(MouseButton::Left),
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

pub(super) fn drag_event(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::Drag(MouseButton::Left),
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

/// A pointer position on `row`-th card of column `col`, using the shared
/// board geometry so tests stay in lock-step with `hit_test`.
pub(super) fn card_cell(app: &App, col: usize, row: usize) -> (u16, u16) {
    let board_area = app.board_mouse_area(app.frame_size.get()).unwrap();
    let rect = board::compute_column_rects(board_area, app.board.total_cols())[col];
    let mut y = rect.y + 1;
    for before in 0..row {
        y += crate::ui::widgets::card_line_count(
            &app.board.columns[col].cards[before],
            rect.width as usize,
            true,
            3,
        );
    }
    (rect.x + 2, y)
}

/// A pointer position on empty space inside column `col` (below its cards).
pub(super) fn column_cell(app: &App, col: usize) -> (u16, u16) {
    let board_area = app.board_mouse_area(app.frame_size.get()).unwrap();
    let rect = board::compute_column_rects(board_area, app.board.total_cols())[col];
    (rect.x + 2, rect.y + rect.height - 2)
}

pub(super) fn moved_to(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::Moved,
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

pub(super) fn scroll_up(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::ScrollUp,
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

pub(super) fn scroll_down(x: u16, y: u16) -> MouseEvent {
    MouseEvent {
        kind: MouseEventKind::ScrollDown,
        column: x,
        row: y,
        modifiers: crossterm::event::KeyModifiers::NONE,
    }
}

/// The overlay's rendered text at `w`x`h`.
///
/// For the tests that care about what is *on screen* rather than what the state
/// says: a filter that changes a counter but not a row would pass a state test.
pub(super) fn draw_help(app: &App, w: u16, h: u16) -> String {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    let mut terminal = Terminal::new(TestBackend::new(w, h)).unwrap();
    terminal.draw(|f| render(app, f, f.area())).unwrap();
    let buf = terminal.backend().buffer();
    let mut text = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            text.push_str(buf[(x, y)].symbol());
        }
        text.push('\n');
    }
    text
}

pub(super) fn open_detail(app: &mut App) {
    let _ = app.handle_key(press(KeyCode::Enter)).unwrap();
    assert!(matches!(app.mode, Mode::ActionMenu { .. }));
    assert!(select_menu_action(app, &IssueAction::OpenDetail));
    let _ = app.handle_key(press(KeyCode::Enter)).unwrap();
    assert!(matches!(app.mode, Mode::Detail));
    assert!(app.detail.is_some());
}

pub(super) fn draw_board(app: &App, w: u16, h: u16) -> Vec<String> {
    render_to_cells(app, w, h).unwrap()
}

pub(super) fn flush_line(cells: &[String], width: u16, row: u16) -> String {
    let start = (row as usize) * (width as usize);
    cells[start..start + width as usize].concat()
}

/// A two-board config (`default` + `release`) so the tab bar renders.
pub(super) fn make_multi_board_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let config_path = tmp.path().join("tix.toml");
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.kanban.configurations.insert(
        "release".into(),
        crate::config::BoardConfiguration::default(),
    );
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    app.frame_size.set(Rect::new(0, 0, 80, 24));
    (tmp, app)
}

/// Render the app once so recorded hit regions are populated, then return
/// the Yes / No button cell coordinates for the drawn prompt.
pub(super) fn drawn_confirm_buttons(app: &App) -> ((u16, u16), (u16, u16)) {
    let backend =
        ratatui::backend::TestBackend::new(app.frame_size.get().width, app.frame_size.get().height);
    let mut terminal = ratatui::Terminal::new(backend).unwrap();
    terminal
        .draw(|f| crate::app::render(app, f, f.area()))
        .unwrap();
    let prompt = confirm_delete_prompt(app.frame_size.get());
    let (yes, no) = confirm_delete_buttons(prompt);
    ((yes.x + 2, yes.y), (no.x + 1, no.y))
}

/// Sync `app.filter_modal`'s focus and return it, for the picker tests.
pub(super) fn focus_filter_field(app: &mut App, field: FilterField) {
    app.filter_modal
        .as_mut()
        .expect("filter modal open")
        .focus_field(field);
}

/// A point inside the dashboards detail's row `row`. At the detail level the
/// section rail is hidden and the board rows occupy the whole content area,
/// so the click target follows `frame_size` rather than `config_body_rect`.
pub(super) fn drawn_detail_row(app: &App, row: usize) -> (u16, u16) {
    let backend =
        ratatui::backend::TestBackend::new(app.frame_size.get().width, app.frame_size.get().height);
    let mut terminal = ratatui::Terminal::new(backend).unwrap();
    terminal
        .draw(|f| crate::app::render(app, f, f.area()))
        .unwrap();
    let content = app.frame_size.get();
    (content.x + 2, content.y + 1 + row as u16)
}

/// Open the Config mode on the dashboards **detail** level, so a click test
/// targets the board rows rather than the index.
pub(super) fn open_dashboard_detail(app: &mut App) {
    let mut modal = crate::ui::settings::SettingsModal::new();
    modal.level = ConfigLevel::Detail;
    app.settings = Some(modal);
    app.mode = Mode::Settings;
}

/// The actions offered by the open menu, in draw order.
pub(super) fn menu_actions(app: &App) -> Vec<IssueAction> {
    app.action_menu
        .as_ref()
        .expect("menu open")
        .items()
        .iter()
        .map(|item| item.action.clone())
        .collect()
}

/// Move the menu cursor onto `wanted` without assuming an item index.
pub(super) fn select_menu_action(app: &mut App, wanted: &IssueAction) -> bool {
    let len = app.action_menu.as_ref().map_or(0, ActionMenu::visible_len);
    // Start from the top: `Open detail` is preselected, but Move entries are
    // drawn before it, so a search only downwards would miss them.
    for _ in 0..=len {
        let _ = app.handle_key(press(KeyCode::Up)).unwrap();
    }
    for _ in 0..=len {
        let selected = app
            .action_menu
            .as_ref()
            .and_then(ActionMenu::selected_item)
            .map(|item| item.action.clone());
        if selected.as_ref() == Some(wanted) {
            return true;
        }
        let _ = app.handle_key(press(KeyCode::Down)).unwrap();
    }
    false
}

/// A board with a terminal `wontfix` column and a `done` completion column,
/// plus a blocked card in `wontfix`.
pub(super) fn make_terminal_blocked_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    {
        let board = config
            .kanban
            .configurations
            .get_mut("default")
            .expect("default board");
        board.columns = vec!["todo".into(), "wontfix".into(), "done".into()];
        board.done_column = Some("done".into());
        board.category_map = [
            ("wontfix".to_string(), "canceled".to_string()),
            ("done".to_string(), "completed".to_string()),
        ]
        .into_iter()
        .collect();
    }
    let config_path = tmp.path().join("tix.toml");
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    // Write the issues **before** constructing the app: `App::new` takes its one
    // full enumeration at startup, and `refresh_corpus` then applies only the
    // internal write delta. A file written directly after `App::new` would be
    // absent from the corpus, because nothing but the watcher knows it changed.
    write_issue(&dir, "1.md", 1, "Blocker", "todo", None);
    write_issue(&dir, "2.md", 2, "Blocked", "wontfix", None);
    let mut app = App::new(&config).unwrap();
    app.store
        .link("1", "2", crate::relationships::RelationKind::Blocks)
        .unwrap();
    app.refresh_corpus().unwrap();
    app.frame_size.set(Rect::new(0, 0, 80, 40));
    let col = (0..app.board.real_cols())
        .find(|col| app.board.column_name(*col) == "wontfix")
        .expect("the fixture board has the wontfix column");
    app.board.select_column(col);
    app.board.selected = 0;
    (tmp, app)
}

/// An app whose config has a `[triage]` section, so the Triage mode can open.
pub(super) fn make_shell_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config::starter();
    config.layout.move_on_change = false;
    config.issues_dir = dir;
    let app = App::new(&config).unwrap();
    (tmp, app)
}

/// An app with two boards and two templates, so both the Boards and the
/// New Issue limbs have rows. Written through `tix.toml` and re-read, so the
/// limb comes from the same config the surfaces read.
pub(super) fn make_branchy_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config.kanban.configurations.insert(
        "release".into(),
        crate::config::BoardConfiguration::default(),
    );
    config.templates.insert(
        "bug".into(),
        crate::config::IssueTemplate {
            body: Some("## Steps\n".into()),
            labels: vec!["bug".into()],
            ..crate::config::IssueTemplate::default()
        },
    );
    config.templates.insert(
        "feature".into(),
        crate::config::IssueTemplate {
            body: Some("## Motivation\n".into()),
            labels: vec!["enhancement".into()],
            ..crate::config::IssueTemplate::default()
        },
    );
    let path = tmp.path().join("tix.toml");
    config.save(&path).unwrap();
    let config = Config::load_with_warning(&path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    (tmp, app)
}

/// An app with an archived, a current (no end date), and a future cycle,
/// plus one issue done and one open in the current cycle. The pending
/// rollover the expired cycle would raise is cleared so the tests start on
/// the board.
pub(super) fn make_cycle_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(dir.join("alice")).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    let cycle = |description: &str, start: &str, due: Option<&str>| crate::config::PlanningCycle {
        description: Some(description.to_string()),
        start_date: Some(start.to_string()),
        due_date: due.map(str::to_string),
    };
    config.cycles.insert(
        "Historical".into(),
        cycle("old", "2000-01-01", Some("2000-02-01")),
    );
    config
        .cycles
        .insert("Ongoing".into(), cycle("open", "2026-01-01", None));
    config.cycles.insert(
        "Later".into(),
        cycle("future", "2999-01-01", Some("2999-02-01")),
    );
    for (name, number, status, cycle) in [
        ("2026-01-01-done.md", 1, "done", "Ongoing"),
        ("2026-01-02-open.md", 2, "todo", "Ongoing"),
        ("2026-01-03-old.md", 3, "todo", "Historical"),
    ] {
        fs::write(
            dir.join("alice").join(name),
            format!(
                "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"{status}\"\n\
                     labels: []\npriority: \"medium\"\ncycles: [\"{cycle}\"]\n\
                     created: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody."
            ),
        )
        .unwrap();
    }
    let config_path = tmp.path().join("tix.toml");
    config.save(&config_path).unwrap();
    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let mut app = App::new(&config).unwrap();
    // The expired `Historical` cycle would otherwise raise the startup
    // rollover dialog; the mode tests want the board.
    app.rollover_dialog = None;
    app.mode = Mode::Board;
    (tmp, app)
}

/// An app whose `[templates.<name>]` holds two records. Written through
/// `tix.toml` and re-read, so the test depends on the config round trip the
/// feature promises rather than on a hand-set field.
pub(super) fn make_templated_app() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let mut config = Config::starter();
    config.layout.move_on_change = false;
    config.issues_dir = dir;
    config.templates.insert(
        "bug".into(),
        crate::config::IssueTemplate {
            body: Some("## Steps to reproduce\n\n## Expected\n".into()),
            labels: vec!["bug".into()],
            ..crate::config::IssueTemplate::default()
        },
    );
    config.templates.insert(
        "feature".into(),
        crate::config::IssueTemplate {
            body: Some("## Motivation\n".into()),
            labels: vec!["enhancement".into()],
            ..crate::config::IssueTemplate::default()
        },
    );
    let path = tmp.path().join("tix.toml");
    config.save(&path).unwrap();
    let config = Config::load_with_warning(&path, |_| {}).unwrap();
    assert!(
        config.templates.contains_key("bug"),
        "templates must survive the tix.toml round trip"
    );
    let app = App::new(&config).unwrap();
    (tmp, app)
}

pub(super) fn type_text(app: &mut App, text: &str) {
    for c in text.chars() {
        app.handle_key(press(KeyCode::Char(c))).unwrap();
    }
}

/// A project whose board and cycle **file stores** both exist:
/// `docs/boards/default.md` and `docs/cycles/sprint-7.md`, with one issue
/// that references `Sprint 7` and one milestone.
pub(super) fn make_app_with_config_stores() -> (TempDir, App) {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    let dir = root.join("issues");
    fs::create_dir_all(&dir).unwrap();

    // A stored cycle the issue references.
    crate::cycle_store::CycleStore::new(root)
        .save(
            "Sprint 7",
            &crate::config::PlanningCycle {
                description: Some("kickoff".into()),
                start_date: Some("2026-10-01".into()),
                due_date: Some("2999-12-31".into()),
            },
            None,
        )
        .unwrap();

    let issue = "---\nnumber: 1\ntitle: \"A\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncycles: [\"Sprint 7\"]\nmilestones: [\"GA\"]\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody text.";
    fs::create_dir_all(dir.join("alice")).unwrap();
    fs::write(dir.join("alice/2026-01-01-a.md"), issue).unwrap();

    let milestones_dir = root.join("docs/milestones");
    fs::create_dir_all(&milestones_dir).unwrap();
    fs::write(
            milestones_dir.join("2026-01-01-ga.md"),
            "---\nname: \"GA\"\ntarget_date: \"2026-12-31\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nship it\n",
        )
        .unwrap();

    // The board store is authoritative once `docs/boards/` exists, so the
    // board is written there and `tix.toml` carries no `[kanban.*]` copy.
    fs::create_dir_all(root.join("docs/boards")).unwrap();
    let mut config = Config {
        issues_dir: dir.clone(),
        ..test_config()
    };
    config
        .kanban
        .configurations
        .insert("default".into(), crate::config::starter_board());
    let config_path = root.join("tix.toml");
    config.save(&config_path).unwrap();

    let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
    let app = App::new(&config).unwrap();
    (tmp, app)
}

pub(super) fn open_config(app: &mut App) {
    let _ = app.handle_key(press(KeyCode::F(12))).unwrap();
    assert!(
        matches!(app.mode, Mode::Settings),
        "F12 opens the Config mode"
    );
}

/// Draw `app` into a `TestBackend` and hand back the buffer, so a test can
/// read cell styles (the `draw_board`/`flush_line` helpers keep text only).
pub(super) fn draw_buffer(app: &App, w: u16, h: u16) -> ratatui::buffer::Buffer {
    let backend = ratatui::backend::TestBackend::new(w, h);
    let mut terminal = ratatui::Terminal::new(backend).unwrap();
    terminal
        .draw(|f| crate::app::render(app, f, f.area()))
        .unwrap();
    terminal.backend().buffer().clone()
}

/// Write an issue carrying the given cycle and milestone memberships, so the
/// flat issue tables have something to list.
pub(super) fn write_planning_issue(
    dir: &std::path::Path,
    name: &str,
    number: u32,
    title: &str,
    status: &str,
    cycles: &[&str],
    milestones: &[&str],
) {
    let list = |values: &[&str]| {
        values
            .iter()
            .map(|v| format!("\"{v}\""))
            .collect::<Vec<_>>()
            .join(", ")
    };
    let cycles_line = if cycles.is_empty() {
        String::new()
    } else {
        format!("cycles: [{}]\n", list(cycles))
    };
    let milestones_line = if milestones.is_empty() {
        String::new()
    } else {
        format!("milestones: [{}]\n", list(milestones))
    };
    fs::write(
        dir.join(name),
        format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\n\
                 priority: \"medium\"\n{cycles_line}{milestones_line}\
                 created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nBody."
        ),
    )
    .unwrap();
}

/// The filenames of every recorded `OpenIssue` region, sorted.
pub(super) fn open_issue_regions(app: &App) -> Vec<String> {
    let mut names: Vec<String> = app
        .frame_hit_regions
        .borrow()
        .iter()
        .filter_map(|region| match &region.action {
            Action::OpenIssue(filename) => Some(filename.clone()),
            _ => None,
        })
        .collect();
    names.sort();
    names
}

/// An app whose store holds one issue with `body`, and whose "local user" is
/// pinned to `alice`.
///
/// The candidates are set directly rather than read from git: the local user of a
/// test must not be the machine's `~/.gitconfig`.
pub(super) fn app_with_mention(body: &str) -> (TempDir, App, u32) {
    let (tmp, mut app) = make_app();
    let number = seed_issue(&mut app, body);
    app.mention_candidates = vec!["alice".to_string()];
    recount_mentions(&mut app);
    (tmp, app, number)
}

/// Create one issue with `body` through the store, so its mentions are reconciled.
pub(super) fn seed_issue(app: &mut App, body: &str) -> u32 {
    let mut issue: Issue = serde_yaml::from_str(
            "number: 0\ntitle: \"Fix login\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n",
        )
        .expect("a minimal issue");
    app.store.create(&mut issue, body, None).expect("create");
    issue.number
}

/// Recompute the cached unread count for the pinned candidates, exactly as
/// `App::refresh_mentions` does once the candidates are known.
pub(super) fn recount_mentions(app: &mut App) {
    app.unread_mentions = app
        .mention_store()
        .map_or(0, |store| store.unread_count(&app.mention_candidates));
}

pub(super) fn frame_text(app: &App, width: u16, height: u16) -> String {
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;
    let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
    terminal.draw(|f| render(app, f, f.area())).unwrap();
    let buf = terminal.backend().buffer();
    let mut out = String::new();
    for y in 0..buf.area.height {
        for x in 0..buf.area.width {
            out.push_str(buf[(x, y)].symbol());
        }
        out.push('\n');
    }
    out
}