tix-tracker 0.11.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
#[allow(clippy::wildcard_imports)]
use super::*;

/// The parse diagnostic inside a [`TixError`], without the `parse error:` prefix
/// the prompt's message already implies.
pub(in crate::app) fn error_message(error: &TixError) -> String {
    match error {
        TixError::Parse(message) => message.clone(),
        other => other.to_string(),
    }
}

/// `message`, with the recoverable copy of the previous version appended when
/// one was made (tix #1506).
pub(in crate::app) fn names_backup(message: &str, backup: Option<&PathBuf>) -> String {
    match backup {
        Some(path) => format!("{message}; previous version saved at {}", path.display()),
        None => message.to_string(),
    }
}

/// Drain disclosures raised by a TUI action into the status line.
///
/// Extracted from the event loop so the wiring is reachable from a test. Cycle 5
/// deleted the inlined loop and all 1012 tests stayed green: the unit test for
/// `note_disclosure` calls it directly, so it could not fail for the regression it
/// is named for. `run` needs a real terminal, so this function is the only seam
/// available. The call site inside `run` is still not covered; it says so.
pub fn drain_disclosures(app: &mut App) {
    for disclosure in crate::storage::take_disclosures() {
        app.note_disclosure(disclosure);
    }
}

pub fn run(config: &Config) -> Result<()> {
    run_session(config, false)
}

/// `tix new` (#1398): the same session, opened on the create-issue form.
///
/// The form wins over the pending-rollover dialog an expired cycle would normally
/// raise at startup. That is deliberate: `tix new` was asked to file an issue, the
/// rollover is a prompt rather than a task, and it is still pending — the next
/// session and the one-line hint every other command prints both raise it again.
pub fn run_new_issue(config: &Config) -> Result<()> {
    run_session(config, true)
}

#[allow(clippy::too_many_lines)]
fn run_session(config: &Config, new_issue_form: bool) -> Result<()> {
    let mut app = App::new(config)?;
    if new_issue_form {
        app.open_new_issue_form();
    }
    // tix #1632: the "did you know?" modal, on unless the repository turned it
    // off with `tips_on_startup = false`. It opens over whatever the session is
    // on — the board, or the create-issue form `tix new` opened — and closing it
    // lands there.
    if app.store.config.tips_on_startup {
        app.open_tips();
    }
    let mut watcher = crate::watcher::FsWatcher::new(app.store.issues_dir.clone());
    let mut coalescer = crate::watcher::DeltaCoalescer::default();
    enable_raw_mode().map_err(io_err)?;
    execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
    mouse_capture_on(io::stdout()).map_err(io_err)?;
    let guard = RestoreGuard;
    let backend = CrosstermBackend::new(io::stdout());
    let mut terminal = Terminal::new(backend).map_err(io_err)?;

    let result = loop {
        // A write performed by any TUI action can raise a disclosure; surface
        // it rather than letting it sit in the queue for the rest of the session.
        //
        // Uncovered: `run` needs a real terminal, so no test reaches this line.
        // `drain_disclosures` itself is tested; this call site is not, and saying
        // so here is the point — a reader must not infer that deleting it would be
        // caught. Cycle-6 F5: the function's own comment used to promise a
        // statement here that was never written.
        drain_disclosures(&mut app);
        terminal
            .draw(|f| render(&app, f, f.area()))
            .map_err(io_err)?;

        // The idle tick is 1 Hz (tix #1518): one redraw per second is enough for
        // this TUI, and the loop draws unconditionally at the top of each
        // iteration, so the tick *is* the idle redraw rate. A key or mouse event
        // wakes `poll` immediately and is handled at once — the cap applies to
        // idle redraws, not to input latency. The tree walk in `watcher.poll`
        // below runs on the same 1 Hz beat, so an external edit surfaces within
        // about a second.
        if event::poll(Duration::from_secs(1)).map_err(io_err)? {
            let action = match event::read().map_err(io_err)? {
                Event::Key(key) => app.handle_key(key)?,
                Event::Mouse(mouse) => app.handle_mouse(mouse)?,
                // Resize (and any unknown event) is a no-op: the loop redraws
                // on the 1 Hz tick anyway (D2).
                _ => Action::None,
            };
            match action {
                Action::Quit => break Ok(()),
                other => terminal = apply_session_action(&mut app, terminal, other)?,
            }
        }

        // Issue #10: reflect edits made outside `tix` (another editor, `tix`
        // CLI, git checkout). A burst of writes is coalesced into **one**
        // rebuild: `DeltaCoalescer` buffers deltas and hands back the merged
        // one only on the first quiet tick (a poll that reports nothing while a
        // delta is pending), so N writes cost one `refresh_from_disk`. The cost
        // is at most one extra idle tick (~1s, tix #1518) of latency before an external
        // edit shows. A failed apply — a file caught mid-write is a parse error
        // now and a good read once the writer finishes — stays pending and is
        // retried, so its sibling changes are not lost.
        if let Some(delta) = coalescer.observe(watcher.poll()) {
            if let Err(e) = app.refresh_from_disk(&delta) {
                app.status_msg = Some(format!("watch: {e}"));
                coalescer.retry(delta);
            }
        }
    };
    drop(guard);
    result
}

/// Apply one non-quit event to the app, handing the terminal over for the
/// actions that shell out and returning it re-created.
#[allow(clippy::too_many_lines)]
fn apply_session_action(
    app: &mut App,
    mut terminal: Terminal<CrosstermBackend<io::Stdout>>,
    action: Action,
) -> Result<Terminal<CrosstermBackend<io::Stdout>>> {
    match action {
        // `run_session` handles `Quit` itself and never forwards it.
        Action::Quit => {}
        Action::None => {}
        Action::SwitchBoard(index) => {
            app.switch_board(index);
        }
        Action::ConfirmDeleteYes => {
            let _ = app.confirm_delete_yes();
        }
        Action::ConfirmDeleteNo => {
            let _ = app.confirm_delete_no();
        }
        Action::FilterModalFocus(_) | Action::FilterPickerOption(_) | Action::FilterPickerClose => {
            let _ = app.apply_filter_modal_action(action);
        }
        Action::SettingsRow(row) => {
            // A dashboards-index row: focus it (and thus the index level).
            app.apply_config_click(Action::SettingsRow(row));
        }
        Action::ConfigDetailRow(row) => {
            // A dashboard-detail row: select it and run the row's own
            // activation (the detail's Enter, or `Space`).
            app.apply_config_click(Action::ConfigDetailRow(row));
            let _ = app.settings_toggle_selected();
        }
        Action::ConfigSection(section) => {
            app.apply_config_click(Action::ConfigSection(section));
        }
        Action::ConfigPlanningRow(row) => {
            app.apply_config_click(Action::ConfigPlanningRow(row));
        }
        Action::ConfigListRow(row) => {
            app.apply_config_click(Action::ConfigListRow(row));
        }
        Action::SelectBoard(_)
        | Action::SelectCycle(_)
        | Action::SelectMilestone(_)
        | Action::NewFromTemplate(_) => {
            let _ = app.activate_branch(&action);
        }
        Action::DatePickerHit(hit) => match hit {
            DatePickerHit::Day(date) => {
                if let Some(picker) = app.date_picker.as_mut() {
                    picker.select_date_str(&date);
                }
            }
            DatePickerHit::PrevMonth => {
                if let Some(picker) = app.date_picker.as_mut() {
                    picker.shift_month(-1);
                }
            }
            DatePickerHit::NextMonth => {
                if let Some(picker) = app.date_picker.as_mut() {
                    picker.shift_month(1);
                }
            }
            DatePickerHit::Submit => {
                let _ = app.handle_date_picker_key(KeyEvent::new(
                    KeyCode::Enter,
                    crossterm::event::KeyModifiers::NONE,
                ));
            }
        },
        Action::HelpClose => {
            app.close_help();
        }
        Action::SwitchMode(mode) => {
            let _ = app.switch_top_mode(mode);
        }
        Action::TriageOpenStatus
        | Action::TriageOpenAssignee
        | Action::TriageCreate
        | Action::TriageFocusQueue
        | Action::TriagePickOption(_)
        | Action::TriageDropdownClose => {
            let _ = app.apply_triage_action(action);
        }
        Action::CycleSelect(index) => app.select_cycle_row(index),
        Action::OpenIssue(filename) => {
            if let Err(e) = app.open_issue_by_filename(&filename) {
                app.status_msg = Some(format!("open: {e}"));
            }
        }
        Action::TemplateOpen | Action::TemplatePickOption(_) => {
            let _ = app.apply_new_issue_action(action);
        }
        Action::OpenEditor(filename) => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // #1510. The whole round trip — snapshot, temp copy, editor,
            // read-back, conflict decision, write and lint report — is
            // `open_editor_round_trip`; the terminal handover around it is
            // all this arm adds, which is the one thing a test cannot
            // provide and the one thing that has nothing to do with what
            // the edit means.
            if let Err(e) = app.open_editor_round_trip(&filename) {
                app.status_msg = Some(format!("editor: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::CompareEdit => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // The conflict prompt's `c`: reopen the editor on the temp
            // copy and come back to the prompt (#1510). An error leaves the
            // prompt exactly as it was — the temp copy and the newer file
            // are both still there — so the failure cannot strand the user
            // with nothing to press.
            if let Err(e) = app.compare_conflicting_edit() {
                app.status_msg = Some(format!("editor: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::ReeditRepair => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // The repair prompt's `r`: the editor reopens on the retained
            // copy (#1506). An error leaves the prompt — and the copy —
            // exactly as they were, so a failed launch cannot strand the
            // user with nothing to press.
            if let Err(e) = app.reedit_repair() {
                app.status_msg = Some(format!("editor: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::OpenAgent(filename) => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            let edit_result = (|| -> Result<()> {
                let agent = editor::resolve_agent(app.store.config.agent.as_deref())?;
                let issue = app.store.get(IssueSelector::Filename(filename.clone()))?;
                let temp = std::env::temp_dir().join(format!(
                    "tix-agent-{}-{}.md",
                    std::process::id(),
                    issue.number
                ));
                std::fs::write(&temp, issue.body.as_bytes()).map_err(io_err)?;
                let result = std::process::Command::new(&agent)
                    .arg(&temp)
                    .status()
                    .map_err(|e| {
                        crate::error::TixError::Editor(format!("failed to launch {agent}: {e}"))
                    });
                let _ = std::fs::remove_file(&temp);
                result?;
                Ok(())
            })();
            if let Err(e) = edit_result {
                app.status_msg = Some(format!("agent: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::OpenViewer(filename) => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // Read-only: no temp file, no read-back, no write. The shell-out
            // mechanics match `OpenEditor` — the terminal is handed over and
            // restored around the child — but nothing after the child runs
            // sees the file.
            let view_result = (|| -> Result<()> {
                let viewer = editor::resolve_viewer(app.store.config.viewer.as_deref())?;
                let issue = app.store.get(IssueSelector::Filename(filename.clone()))?;
                let path = app.store.issues_dir.join(&issue.filename);
                editor::run_viewer(&viewer, &path)?;
                app.status_msg = Some(format!("Viewed with {viewer}"));
                Ok(())
            })();
            if let Err(e) = view_result {
                app.status_msg = Some(format!("viewer: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::OpenViewerAt(path) => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // The same read-only handover as `OpenViewer`, but the path is
            // already resolved: a `related_issues` path entry may point
            // outside the store, so there is no store lookup to do (#1513).
            let view_result = (|| -> Result<()> {
                let viewer = editor::resolve_viewer(app.store.config.viewer.as_deref())?;
                editor::run_viewer(&viewer, &path)?;
                app.status_msg = Some(format!("Viewed with {viewer}"));
                Ok(())
            })();
            if let Err(e) = view_result {
                app.status_msg = Some(format!("viewer: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
        }
        Action::OpenRepo(path) => {
            drop(terminal);
            let _ = disable_raw_mode();
            let _ = mouse_capture_off(io::stdout());
            let _ = execute!(io::stdout(), LeaveAlternateScreen);

            // Run tix in the chosen repository with our own project root as
            // `TIX_PARENT_REPO`, so the child can jump straight back (tix
            // #1529). On exit the parent TUI is restored — the jump is
            // inherently reversible — and the refresh below picks up
            // anything the child changed in this repository.
            if let Err(e) = run_child_tix(&path, &app.project_root()) {
                app.status_msg = Some(format!("repo: {e}"));
            }

            enable_raw_mode().map_err(io_err)?;
            execute!(io::stdout(), EnterAlternateScreen).map_err(io_err)?;
            mouse_capture_on(io::stdout()).map_err(io_err)?;
            let backend = CrosstermBackend::new(io::stdout());
            terminal = Terminal::new(backend).map_err(io_err)?;
            let _ = app.refresh_corpus();
        }
    }
    Ok(terminal)
}
/// Render the board once using startup state and return the plain-text frame.
pub fn render_once(config: &Config) -> Result<String> {
    let size = resolve_render_size(crossterm::terminal::size().ok());
    render_once_at(config, size.0, size.1)
}

pub(in crate::app) fn resolve_render_size(measured: Option<(u16, u16)>) -> (u16, u16) {
    let (width, height) = measured.unwrap_or((RENDER_FALLBACK_WIDTH, RENDER_FALLBACK_HEIGHT));
    (width.max(1), height.max(1))
}

pub(in crate::app) fn render_once_at(config: &Config, width: u16, height: u16) -> Result<String> {
    let render_h = height.max(1).saturating_sub(RENDER_BOTTOM_MARGIN).max(1);
    let mut app = App::new(config)?;
    app.mode = Mode::Board;
    app.rollover_dialog = None;
    app.one_shot = true;
    let cells = render_to_cells(&app, width, render_h)?;
    Ok(cells_to_text(&cells, width, render_h))
}

pub(in crate::app) fn render_to_cells(app: &App, width: u16, height: u16) -> Result<Vec<String>> {
    let backend = ratatui::backend::TestBackend::new(width.max(1), height.max(1));
    let mut terminal = ratatui::Terminal::new(backend).map_err(io_err)?;
    terminal
        .draw(|f| render(app, f, f.area()))
        .map_err(io_err)?;
    let buffer = terminal.backend().buffer();
    Ok(buffer
        .content
        .iter()
        .map(|cell| cell.symbol().to_string())
        .collect())
}

pub(in crate::app) fn cells_to_text(cells: &[String], width: u16, height: u16) -> String {
    let mut lines = Vec::new();
    for row in 0..height as usize {
        let start = row * width as usize;
        let end = start + width as usize;
        let line = cells[start..end].concat();
        lines.push(line.trim_end().to_string());
    }
    while matches!(lines.last(), Some(last) if last.is_empty()) {
        let _ = lines.pop();
    }
    if lines.is_empty() {
        String::new()
    } else {
        format!("{}\n", lines.join("\n"))
    }
}

/// Enable terminal mouse capture on `stream` (D1): one command pair shared by
/// the startup, editor/agent shell-out re-entry, and restore paths so capture
/// toggling can never drift between call sites.
fn mouse_capture_on(mut stream: io::Stdout) -> Result<()> {
    execute!(stream, EnableMouseCapture).map_err(io_err)
}

/// Disable terminal mouse capture on `stream` (D1): mirror of
/// [`mouse_capture_on`]. Must run while the alternate screen is still active,
/// so the terminal leaves a clean state on quit/error.
fn mouse_capture_off(mut stream: io::Stdout) -> Result<()> {
    execute!(stream, DisableMouseCapture).map_err(io_err)
}

struct RestoreGuard;

impl Drop for RestoreGuard {
    fn drop(&mut self) {
        let _ = disable_raw_mode();
        let _ = mouse_capture_off(io::stdout());
        let _ = execute!(io::stdout(), LeaveAlternateScreen);
    }
}

pub(in crate::app) fn io_err<E: std::fmt::Display>(e: E) -> TixError {
    TixError::Io(io::Error::other(e.to_string()))
}