tix-tracker 0.7.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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
use ratatui::Frame;
use ratatui::buffer::{Buffer, CellDiffOption};
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};

use crate::model::Issue;

use std::num::NonZeroU16;

#[derive(Clone)]
pub struct DetailState {
    pub issue: Issue,
    /// The issue's resolved category label and color hint, from the service
    /// (WP05 T023, FR-004).
    ///
    /// `None` for a column the board does not configure, which the chip renders as
    /// `(unmapped)` — a statement about the file rather than a silent default. Filled
    /// in by the caller from the service, so the detail view cannot spell a category
    /// differently from the board card (T024).
    pub category: Option<(String, Option<crate::workflow::ColorHint>)>,
    /// The issue's relationships as the **service** resolves them, not
    /// `issue.relationships`.
    ///
    /// An edge is stored once in its canonical source's file, so the issue's own
    /// field holds only the edges it happens to own — for `2 related 1` it is
    /// empty, so rendering it showed a related issue with no relationships. The
    /// retired symmetric model mirrored the link on both sides by construction,
    /// so reading the raw field here was a regression, not a simplification.
    /// Populated by the caller from [`crate::storage::Store::relationships_for`].
    pub relationships: Vec<crate::relationships::Relationship>,
    /// The issue's dependency chain, exactly as the service ordered it, and
    /// whether a traversal bound truncated it.
    ///
    /// Taken from the service rather than derived here: re-deriving the walk in
    /// the renderer is how a detail pane ends up disagreeing with `tix chain`
    /// about the same snapshot (`contracts/surface-parity.md` §3).
    pub chain: crate::relationships::DependencyChain,
    /// The service's blocked reason, or `None` when the issue is not blocked.
    pub blocked: Option<String>,
    /// The issue's hierarchy facts, from the shared
    /// [`crate::commands::parent::HierarchyFacts`].
    ///
    /// Taken whole rather than as pre-rendered strings, so the detail pane and
    /// `tix parent show` are guaranteed to describe the same snapshot and the
    /// pane can lay them out its own way — which the parity contract allows:
    /// same facts, same order, presentation may differ.
    pub hierarchy: crate::commands::parent::HierarchyFacts,
    pub scroll_offset: u16,
    /// The pane's last-rendered viewport height, in rows (tix #1442).
    ///
    /// Recorded during the draw because the *key* handler is what needs it: "scroll
    /// one page" has to mean the page the reader is looking at, and only the renderer
    /// knows how tall that is. A `Cell` for the same reason `App::frame_hit_regions`
    /// is a `RefCell` — the renderer holds this state immutably.
    pub viewport: std::cell::Cell<u16>,
    /// The largest `scroll_offset` that still shows content (tix #1442).
    ///
    /// Scroll steps used to be unclamped, so paging past the end of a long issue left
    /// a blank pane with no way back except scrolling up the same distance. A page
    /// step makes that much easier to hit, so the bound travels with the step.
    pub max_scroll: std::cell::Cell<u16>,
    /// Which relationship `E` (re-kind) and `d` (remove) act on, as an index into
    /// `relationships` (#1359).
    ///
    /// An index and not an id, because the pane does not display ids — it shows
    /// `r.display`, which carries the kind and the target but not the stable
    /// `rel_…` token. A user picks an edge by looking at it.
    ///
    /// Always within `0..relationships.len()`; [`DetailState::clamp_rel_cursor`] is
    /// the only thing that writes it, so a removal that shrinks the list cannot leave
    /// the cursor pointing past the end.
    pub rel_cursor: usize,
    /// The issue's classified `related_issues` entries (tix #1513).
    ///
    /// Classified by [`crate::related::classify_all`] at open/refresh time, not at
    /// render time: the classification is stable for a given string and doing it once
    /// keeps the renderer a pure function of the pane's state. The list is empty for
    /// an issue with no `related_issues:` field, and the block is then not drawn.
    pub related: Vec<crate::related::RelatedRef>,
    /// Which related entry `o` follows, as an index into `related` (tix #1513).
    ///
    /// Moved only by the related picker (`r`), never by `j`/`k` — those keep moving
    /// the **relationship** cursor, which is a different list with a different
    /// meaning. Always within `0..related.len()`; [`DetailState::clamp_related_cursor`]
    /// is the only thing that writes it, so indexing cannot panic.
    pub related_cursor: usize,
    /// Whether the pane shows an issue it must not offer to mutate (tix #1513).
    ///
    /// `true` only for a `related_issues` *path* reference that parsed as an issue
    /// outside the store — the file is readable but its writes have no store to route
    /// through, so the pane refuses `e`/`c`/`a` and the relationship operations rather
    /// than failing with a lookup error.
    pub read_only: bool,
}

impl DetailState {
    /// Keep the relationship cursor inside the list.
    ///
    /// Called after every mutation that can change the list's length — a removal, and
    /// a refresh after a create. A cursor that survived a removal as `3` into a
    /// two-element list would make `E` and `d` act on nothing while still reporting
    /// a selection.
    pub fn clamp_rel_cursor(&mut self) {
        if self.relationships.is_empty() {
            self.rel_cursor = 0;
        } else if self.rel_cursor >= self.relationships.len() {
            self.rel_cursor = self.relationships.len() - 1;
        }
    }

    /// Keep the related-entry cursor inside the list (tix #1513).
    ///
    /// The same rule [`DetailState::clamp_rel_cursor`] follows: `o` indexes
    /// `related` and the picker writes the index, so the list shrinking (a refresh
    /// after the `related_issues` field was edited) must not leave it past the end.
    pub fn clamp_related_cursor(&mut self) {
        if self.related.is_empty() {
            self.related_cursor = 0;
        } else if self.related_cursor >= self.related.len() {
            self.related_cursor = self.related.len() - 1;
        }
    }

    /// Rows a **page** step moves: the last-rendered viewport, less one row of
    /// overlap (tix #1442).
    ///
    /// The overlap is the point. A step that moves exactly the height of the pane
    /// leaves no line on screen that was there before, so a reader paging through a
    /// long body has nothing to anchor the new page to. One row of context costs
    /// nothing and removes that.
    pub fn page(&self) -> u16 {
        self.viewport.get().saturating_sub(1).max(1)
    }

    /// Scroll by `rows` (negative scrolls up), clamped to the content.
    ///
    /// The clamp is what keeps a page step usable: without it, one `PgDn` past the
    /// end of an issue left a blank pane, and the only way back was to scroll up the
    /// same distance — which, on a page step, is the whole screen.
    pub fn scroll_by(&mut self, rows: i32) {
        let next = i32::from(self.scroll_offset) + rows;
        self.scroll_offset = next.clamp(0, i32::from(self.max_scroll.get())) as u16;
    }
}

/// An empty chain, for tests with no graph to hand.
#[cfg(test)]
fn no_chain() -> crate::relationships::DependencyChain {
    crate::relationships::DependencyChain {
        root: 0,
        paths: vec![],
        truncated: false,
    }
}

pub fn render(detail: &DetailState, f: &mut Frame, area: Rect, theme: &crate::ui::color::Theme) {
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut files_line_index: Option<usize> = None;

    let fields: Vec<(&str, String)> = vec![
        ("number", detail.issue.number.to_string()),
        ("title", detail.issue.title.clone()),
        ("status", detail.issue.status.to_string()),
        // The category label, from the service's own `label()` — never reworded
        // here (T023 step 1). Rendered as a plain field so it is greppable in the
        // detail view exactly as the other frontmatter fields are.
        (
            "category",
            detail
                .category
                .as_ref()
                .map(|(label, _)| label.clone())
                .unwrap_or_else(|| "(unmapped)".to_string()),
        ),
        ("priority", detail.issue.priority.to_string()),
        ("created", detail.issue.created.clone()),
        ("updated", detail.issue.updated.clone()),
    ];

    for (key, value) in &fields {
        lines.push(Line::from(vec![
            Span::styled(format!("{key}: "), Style::default().fg(Color::DarkGray)),
            Span::raw(value.clone()),
        ]));
    }

    if let Some(rendered) = render_assignee(detail.issue.assignee.as_deref()) {
        lines.push(Line::from(vec![
            Span::styled("assignee: ", Style::default().fg(Color::DarkGray)),
            Span::raw(rendered),
        ]));
    }

    if let Some(ref estimate) = detail.issue.estimate {
        lines.push(Line::from(vec![
            Span::styled("estimate: ", Style::default().fg(Color::DarkGray)),
            Span::raw(estimate.clone()),
        ]));
    }

    if let Some(ref commit) = detail.issue.commit {
        lines.push(Line::from(vec![
            Span::styled("commit: ", Style::default().fg(Color::DarkGray)),
            Span::raw(commit.clone()),
        ]));
    }

    if !detail.issue.labels.is_empty() {
        // Each label renders in its tag color when `docs/tags` configures one
        // (tix #1530); an unconfigured label keeps the default foreground.
        let mut spans = vec![Span::styled(
            "labels: ",
            Style::default().fg(Color::DarkGray),
        )];
        for (index, label) in detail.issue.labels.iter().enumerate() {
            if index > 0 {
                spans.push(Span::raw(", "));
            }
            let style = theme
                .tag(label)
                .map_or_else(Style::default, |color| Style::default().fg(color));
            spans.push(Span::styled(label.clone(), style));
        }
        lines.push(Line::from(spans));
    }

    // The `related:` block (tix #1513). Prominent and **near the top**, above the
    // relationship rows: `related_issues` is the cross-repository surface the user
    // came to this pane for, and a block below the dependency graph would be below
    // the fold on a long issue. Non-empty only — an issue with no `related_issues:`
    // field draws nothing, because an empty heading would be noise on every issue.
    //
    // The selected entry carries a `>` marker exactly like the relationship row, so
    // `o` (follow) acts on something the reader can see. `related_cursor` is clamped
    // on every mutation, so indexing here cannot panic.
    if !detail.related.is_empty() {
        let accent = Style::default()
            .fg(Color::Magenta)
            .add_modifier(Modifier::BOLD);
        lines.push(Line::from(vec![
            Span::styled("related: ", accent),
            // The count, so a long list is legible at a glance. Stated rather than
            // implied by the number of following lines, which the viewport may clip.
            Span::styled(detail.related.len().to_string(), accent),
        ]));
        let cursor = detail.related_cursor;
        for (index, entry) in detail.related.iter().enumerate() {
            let marker = if index == cursor {
                Span::styled("  > ", Style::default().fg(Color::Cyan))
            } else {
                Span::styled("    ", Style::default())
            };
            lines.push(Line::from(vec![
                marker,
                Span::styled(entry.display(), Style::default().fg(Color::Magenta)),
            ]));
        }
    }

    if !detail.relationships.is_empty() {
        // The selected edge is marked, because `E` and `d` act on it and a key that
        // acts on an invisible selection is a key the user cannot use. The marker is
        // `>` on the row itself rather than a separate "selected: …" line, so the
        // row's text is unchanged and stays byte-comparable with `tix view`'s.
        //
        // `rel_cursor` is clamped by `DetailState::clamp_rel_cursor` on every
        // mutation, so indexing here cannot panic even if a future caller forgets.
        let cursor = detail.rel_cursor;
        // Owned strings, because `lines` is `Vec<Line<'static>>` — the pane builds
        // every row that way, and borrowing `rel.display` here would pin the whole
        // vector to the detail's lifetime.
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            "links: ",
            Style::default().fg(Color::DarkGray),
        )];
        for (index, rel) in detail.relationships.iter().enumerate() {
            if index > 0 {
                spans.push(Span::raw(", "));
            }
            if index == cursor {
                spans.push(Span::styled("> ", Style::default().fg(Color::Cyan)));
            }
            spans.push(Span::raw(rel.display.clone()));
        }
        lines.push(Line::from(spans));
    }

    // Field order matches `tix view --show relationships` exactly:
    // relationships, then chain, then blocked (`surface-parity.md` §2 requires the
    // *outcome* to match and permits presentation to differ **if documented**;
    // WP06 T027 asks for the same order outright, and one order for both surfaces
    // is one fewer thing to explain).
    //
    // WP04 deliberately put the blocked reason first, on the grounds that it is
    // "the fact that changes what the reader should do next". That is a
    // presentation preference rather than a correctness claim — the row is on the
    // same screen either way — so it yields to the shared order. The reasoning is
    // recorded rather than deleted, because if this ever moves back the reason
    // should come with it.
    if detail.chain.paths.is_empty() {
        // The empty state is **stated**, not omitted. `tix view` prints
        // "No dependency chain for #N", and a detail pane that prints nothing
        // cannot distinguish "there is no chain" from "the chain was not
        // computed" — two very different facts about the same issue.
        lines.push(Line::from(vec![
            Span::styled("chain: ", Style::default().fg(Color::DarkGray)),
            Span::styled("none", Style::default().fg(Color::DarkGray)),
        ]));
    } else {
        for (depth, path) in detail.chain.paths.iter().enumerate() {
            let rendered: Vec<String> = path
                .iter()
                .map(|node| {
                    let title = node.title.trim();
                    if title.is_empty() {
                        format!("#{}", node.number)
                    } else {
                        format!("#{} {}", node.number, title)
                    }
                })
                .collect();
            let label = if depth == 0 { "chain: " } else { "        " };
            lines.push(Line::from(vec![
                Span::styled(label, Style::default().fg(Color::DarkGray)),
                Span::raw(rendered.join(" -> ")),
            ]));
        }
    }

    // Likewise the blocked state. An unblocked issue says so. Silently omitting
    // the row would make "not blocked" and "not looked at" the same picture.
    match &detail.blocked {
        Some(reason) => lines.push(Line::from(vec![
            Span::styled("blocked: ", Style::default().fg(Color::Red)),
            Span::styled(
                reason.clone(),
                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
            ),
        ])),
        None => lines.push(Line::from(vec![
            Span::styled("blocked: ", Style::default().fg(Color::DarkGray)),
            Span::styled("not blocked", Style::default().fg(Color::DarkGray)),
        ])),
    }

    // The hierarchy block. **Same facts, same order as the CLI block** (parent,
    // child count, rollup, children) — the parity contract requires the content
    // to match even though the presentation does not.
    lines.push(Line::from(Span::styled("", Style::default())));
    lines.push(Line::from(Span::styled(
        "hierarchy:",
        Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::BOLD),
    )));
    lines.push(Line::from(vec![
        Span::styled("  parent: ", Style::default().fg(Color::DarkGray)),
        Span::raw(crate::commands::parent::parent_text(&detail.hierarchy)),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  ", Style::default()),
        Span::raw(detail.hierarchy.child_count_line()),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  ", Style::default()),
        Span::raw(detail.hierarchy.completion_line()),
    ]));
    for child in &detail.hierarchy.children {
        lines.push(Line::from(vec![
            Span::styled("    ", Style::default()),
            Span::raw(child.display.clone()),
        ]));
    }
    // An explicit empty state, not a bare heading — the CLI block says
    // "No children for #N" and a silent omission would read as "not looked at".
    if !detail.hierarchy.has_children() {
        lines.push(Line::from(vec![
            Span::styled("    ", Style::default()),
            Span::raw(crate::commands::parent::no_children_text(
                detail.hierarchy.number,
            )),
        ]));
    }

    if detail.chain.truncated {
        // Said, not silently dropped: a partial chain shown as a whole one is a
        // false statement about the graph.
        lines.push(Line::from(Span::styled(
            format!(
                "note: chain display truncated at {} nodes; the chain may continue",
                crate::relationships::MAX_CHAIN_NODES
            ),
            Style::default().fg(Color::Yellow),
        )));
    }

    if !detail.issue.files.is_empty() {
        lines.push(Line::from(vec![
            Span::styled("files: ", Style::default().fg(Color::DarkGray)),
            Span::raw(detail.issue.files.join(", ")),
        ]));
        files_line_index = Some(lines.len() - 1);
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "---",
        Style::default().fg(Color::DarkGray),
    )));
    lines.push(Line::from(""));

    for line_text in detail.issue.body.lines() {
        lines.push(Line::from(Span::raw(line_text.to_string())));
    }

    let content_lines = lines.len();
    let title = if detail.read_only {
        // An external file has no store to write through, so the pane says so
        // rather than offering an `e` that would fail (#1513).
        "Detail [read-only] [Esc=back]"
    } else {
        "Detail [Esc=back e=edit A=agent]"
    };
    let para = Paragraph::new(lines)
        .scroll((detail.scroll_offset, 0))
        .block(Block::default().borders(Borders::ALL).title(title));

    // tix #1442: the pane records its own geometry, so a page step means the page
    // the reader is looking at and no step can scroll past the last line into a
    // blank pane. Recorded here because only the renderer knows either number.
    let viewport = area.height.saturating_sub(2); // the block's two border rows
    detail.viewport.set(viewport);
    detail.max_scroll.set(
        u16::try_from(content_lines)
            .unwrap_or(u16::MAX)
            .saturating_sub(viewport),
    );

    f.render_widget(para, area);

    if let Some(idx) = files_line_index {
        inject_files_hyperlinks(
            f.buffer_mut(),
            area,
            idx,
            detail.scroll_offset,
            &detail.issue.files,
        );
    }
}

/// Render an assignee for the detail view (FR-030):
/// - a full git identity (`Name <email>`) is shown verbatim (identity form
///   sniffed on the `<>` pair),
/// - a bare handle gets the cosmetic `@` prefix,
/// - an already `@`-prefixed value passes through unchanged,
/// - unassigned renders no line at all.
pub fn render_assignee(assignee: Option<&str>) -> Option<String> {
    let raw = assignee?;
    if raw.contains('<') && raw.contains('>') {
        return Some(raw.to_string());
    }
    if raw.starts_with('@') {
        return Some(raw.to_string());
    }
    Some(format!("@{raw}"))
}

/// A zero-width OSC 8 terminal hyperlink wrapping `label` around `uri`, so a
/// `files:` entry renders as a clickable link in supporting terminals. The
/// sequence is invisible and only has an effect when emitted verbatim.
pub fn hyperlink(uri: &str, label: &str) -> String {
    format!("{}{}{}", osc8_start(uri), label, osc8_end())
}

fn osc8_start(uri: &str) -> String {
    format!("\u{1b}]8;;{uri}\u{1b}\\")
}

fn osc8_end() -> String {
    "\u{1b}]8;;\u{1b}\\".to_string()
}

/// Best-effort `file://` URI for a repo-relative path, resolved against the
/// current working directory (the repo root when tix runs from it). No path
/// validation — a missing file still gets a clickable entry (D3 non-goal).
fn file_uri(path: &str) -> String {
    if path.starts_with("file://") {
        return path.to_string();
    }
    let abs = std::path::absolute(path).unwrap_or_else(|_| path.into());
    format!("file://{}", abs.to_string_lossy())
}

/// Wrap every `files:` entry on its rendered line in an OSC 8 hyperlink.
///
/// ratatui's [`Buffer::set_stringn`] strips control characters from span
/// content, so the escape sequences are spliced into the already-rendered
/// cells instead: the opening sequence is prepended to the first cell of each
/// path and the reset sequence appended to its last cell. The text between
/// them passes through untouched, keeping the visible layout identical. Both
/// spliced cells are forced to single-cell width
/// ([`CellDiffOption::ForcedWidth`]) so the render diff treats the escape
/// sequence as zero-width and does not skip the following path cells as the
/// trailing columns of a wide glyph. Entries truncated by the block's inner
/// width are skipped best-effort.
fn inject_files_hyperlinks(
    buf: &mut Buffer,
    area: Rect,
    line_index: usize,
    scroll_offset: u16,
    files: &[String],
) {
    let inner_top = area.top() + 1;
    let scrolled = line_index as i32 - scroll_offset as i32;
    if scrolled < 0 {
        return;
    }
    let y0 = inner_top + scrolled as u16;
    if y0 >= area.bottom() {
        return;
    }
    let (x0, inner_right) = (area.left() + 1, area.right().saturating_sub(1));
    let mut x = x0 + "files: ".len() as u16;
    for entry in files {
        if entry.is_empty() {
            continue;
        }
        let len = entry.chars().count() as u16;
        if x + len > inner_right {
            break;
        }
        let uri = file_uri(entry);
        let first = &mut buf[(x, y0)];
        first.set_symbol(&format!("{}{}", osc8_start(&uri), first.symbol()));
        first.set_diff_option(CellDiffOption::ForcedWidth(
            NonZeroU16::new(1).expect("one is non-zero"),
        ));
        let last = &mut buf[(x + len - 1, y0)];
        last.set_symbol(&format!("{}{}", last.symbol(), osc8_end()));
        last.set_diff_option(CellDiffOption::ForcedWidth(
            NonZeroU16::new(1).expect("one is non-zero"),
        ));
        x += len + 2; // `, ` separator
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::*;

    fn sample_issue() -> Issue {
        Issue {
            number: 1,
            title: "Test Issue".into(),
            status: Status::new("todo"),
            labels: vec!["bug".into()],
            priority: Priority::High,
            assignee: Some("alice".into()),
            estimate: Some("2".into()),
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![crate::relationships::Relationship::new(
                1,
                12,
                crate::relationships::RelationKind::Related,
                "Twelve",
            )],
            related_issues: vec![],
            history: crate::model::History::new(),
            has_retired_links_key: false,
            parent: None,
            files: vec!["openspec/changes/x/proposal.md".into()],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".into(),
            type_: None,
            updated: "2026-01-01".into(),
            filename: "test.md".into(),
            body: "Line one\n\nLine two".into(),
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        }
    }

    /// Render a `DetailState` and return the pane's text.
    fn render_text(detail: &DetailState) -> String {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let backend = TestBackend::new(120, 40);
        let mut terminal = Terminal::new(backend).unwrap();
        terminal
            .draw(|f| render(detail, f, f.area(), &crate::ui::color::Theme::default()))
            .unwrap();
        let buf = terminal.backend().buffer();
        buf.content()
            .iter()
            .map(|c| c.symbol())
            .collect::<Vec<_>>()
            .chunks(120)
            .map(|row| {
                row.iter()
                    .copied()
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn detail_with(
        relationships: Vec<crate::relationships::Relationship>,
        chain: crate::relationships::DependencyChain,
        blocked: Option<String>,
    ) -> DetailState {
        let issue = sample_issue();
        DetailState {
            category: None,
            // `sample_issue()` has no parent and no children, so the facts are the
            // empty ones. Read through the real reader rather than hand-constructed,
            // so a fixture cannot drift from the shape the renderer consumes.
            hierarchy: crate::commands::parent::facts_over(
                std::slice::from_ref(&issue),
                "done",
                issue.number,
            ),
            issue,
            relationships,
            chain,
            blocked,
            scroll_offset: 0,
            viewport: std::cell::Cell::new(0),
            max_scroll: std::cell::Cell::new(0),
            rel_cursor: 0,
            related: Vec::new(),
            related_cursor: 0,
            read_only: false,
        }
    }

    /// The three cases T027 step 4 names, in one test so the *order* and the
    /// empty states are asserted against each other rather than in isolation.
    #[test]
    fn the_relationship_block_covers_a_blocks_edge_a_related_only_issue_and_the_empty_state() {
        // **A `blocks` edge.** The row carries the kind, the target, and the
        // display name — the three facts T027 step 1 names — and the blocked
        // state and chain are stated, not implied.
        let blocks = detail_with(
            vec![crate::relationships::Relationship::new(
                1,
                2,
                crate::relationships::RelationKind::Blocks,
                "Refactor store",
            )],
            no_chain(),
            Some("Blocked by #1 Ship the thing".to_string()),
        );
        let text = render_text(&blocks);
        assert!(text.contains("blocks #2 Refactor store"), "got:\n{text}");
        assert!(text.contains("blocked: Blocked by #1"), "got:\n{text}");
        assert!(text.contains("chain: none"), "got:\n{text}");

        // **Only `related` edges**, and an issue that is not blocked. A
        // relationship that merely *exists* must not be presented as blocking
        // anything — the whole point of the typed model.
        let related = detail_with(
            vec![crate::relationships::Relationship::new(
                1,
                3,
                crate::relationships::RelationKind::Related,
                "Notes",
            )],
            no_chain(),
            None,
        );
        let text = render_text(&related);
        assert!(text.contains("related #3 Notes"), "got:\n{text}");
        assert!(
            text.contains("blocked: not blocked"),
            "a `related` edge must not read as blocking: got:\n{text}"
        );
        assert!(
            !text.contains("blocked: related"),
            "and nothing may present a non-blocks edge as a blocker: got:\n{text}"
        );

        // **No relationships at all.** The empty state says so, rather than
        // leaving the reader to guess between "none" and "not computed".
        let empty = detail_with(vec![], no_chain(), None);
        let text = render_text(&empty);
        assert!(text.contains("blocked: not blocked"), "got:\n{text}");
        assert!(text.contains("chain: none"), "got:\n{text}");
        assert!(
            !text.contains("links: "),
            "an issue with no relationships has no links row: got:\n{text}"
        );
    }

    /// Field order is the same as `tix view --show relationships`:
    /// relationships, then chain, then blocked.
    ///
    /// Asserted by position rather than by presence, because presence alone would
    /// pass with any order — and the order is the part T027 step 2 constrains.
    #[test]
    fn the_relationship_block_is_ordered_like_the_cli_detail() {
        let mut chain = no_chain();
        chain.paths.push(vec![crate::relationships::ChainNode {
            number: 1,
            title: "Ship it".into(),
        }]);
        let text = render_text(&detail_with(
            vec![crate::relationships::Relationship::new(
                1,
                2,
                crate::relationships::RelationKind::Blocks,
                "Refactor store",
            )],
            chain,
            Some("Blocked by #3 Something".to_string()),
        ));
        let links = text.find("links: ").expect("a links row");
        let chain_at = text.find("chain: ").expect("a chain row");
        let blocked = text.find("blocked: ").expect("a blocked row");
        assert!(
            links < chain_at && chain_at < blocked,
            "relationships, then chain, then blocked — got:\n{text}"
        );
    }

    #[test]
    fn render_files_line_emits_clickable_hyperlink() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(120, 40);
        let mut terminal = Terminal::new(backend).unwrap();
        // `sample_issue` owns its relationship, so a store-resolved set for it
        // is exactly its own stored field.
        let detail = DetailState {
            category: None,
            issue: sample_issue(),
            relationships: sample_issue().relationships,
            chain: no_chain(),
            blocked: None,
            // `sample_issue()` has no parent and no children, so the facts are the
            // empty ones. Built through the real reader rather than hand-constructed,
            // so a fixture cannot drift from the shape the renderer consumes.
            hierarchy: crate::commands::parent::facts_over(
                std::slice::from_ref(&sample_issue()),
                "done",
                sample_issue().number,
            ),
            scroll_offset: 0,
            viewport: std::cell::Cell::new(0),
            max_scroll: std::cell::Cell::new(0),
            rel_cursor: 0,
            related: Vec::new(),
            related_cursor: 0,
            read_only: false,
        };
        terminal
            .draw(|f| render(&detail, f, f.area(), &crate::ui::color::Theme::default()))
            .unwrap();

        let buf = terminal.backend().buffer();
        let text: String = buf
            .content()
            .iter()
            .map(|c| c.symbol().to_string())
            .collect::<Vec<_>>()
            .join("");
        let link = hyperlink(
            &file_uri("openspec/changes/x/proposal.md"),
            "openspec/changes/x/proposal.md",
        );
        assert!(
            text.contains(&link),
            "files must render as an OSC 8 hyperlink to the resolved file"
        );
        assert!(text.contains("related #12 Twelve"), "got:\n{text}");
    }

    #[test]
    fn hyperlink_wraps_label_and_keeps_file_uris() {
        assert_eq!(
            hyperlink("file:///a/b.md", "b.md"),
            "\u{1b}]8;;file:///a/b.md\u{1b}\\b.md\u{1b}]8;;\u{1b}\\"
        );
        assert_eq!(file_uri("file:///already/abs.md"), "file:///already/abs.md");
        assert!(file_uri("openspec/x.md").starts_with("file:///"));
    }

    #[test]
    fn render_smoke_small_frame() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(10, 5);
        let mut terminal = Terminal::new(backend).unwrap();
        // `sample_issue` owns its relationship, so a store-resolved set for it
        // is exactly its own stored field.
        let detail = DetailState {
            category: None,
            issue: sample_issue(),
            relationships: sample_issue().relationships,
            chain: no_chain(),
            blocked: None,
            // `sample_issue()` has no parent and no children, so the facts are the
            // empty ones. Built through the real reader rather than hand-constructed,
            // so a fixture cannot drift from the shape the renderer consumes.
            hierarchy: crate::commands::parent::facts_over(
                std::slice::from_ref(&sample_issue()),
                "done",
                sample_issue().number,
            ),
            scroll_offset: 0,
            viewport: std::cell::Cell::new(0),
            max_scroll: std::cell::Cell::new(0),
            rel_cursor: 0,
            related: Vec::new(),
            related_cursor: 0,
            read_only: false,
        };
        terminal
            .draw(|f| render(&detail, f, f.area(), &crate::ui::color::Theme::default()))
            .unwrap();
    }

    #[test]
    fn render_smoke_large_frame() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(80, 40);
        let mut terminal = Terminal::new(backend).unwrap();
        // `sample_issue` owns its relationship, so a store-resolved set for it
        // is exactly its own stored field.
        let detail = DetailState {
            category: None,
            issue: sample_issue(),
            relationships: sample_issue().relationships,
            chain: no_chain(),
            blocked: None,
            // `sample_issue()` has no parent and no children, so the facts are the
            // empty ones. Built through the real reader rather than hand-constructed,
            // so a fixture cannot drift from the shape the renderer consumes.
            hierarchy: crate::commands::parent::facts_over(
                std::slice::from_ref(&sample_issue()),
                "done",
                sample_issue().number,
            ),
            scroll_offset: 0,
            viewport: std::cell::Cell::new(0),
            max_scroll: std::cell::Cell::new(0),
            rel_cursor: 0,
            related: Vec::new(),
            related_cursor: 0,
            read_only: false,
        };
        terminal
            .draw(|f| render(&detail, f, f.area(), &crate::ui::color::Theme::default()))
            .unwrap();
    }

    #[test]
    fn render_scroll_offset() {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;

        let backend = TestBackend::new(80, 10);
        let mut terminal = Terminal::new(backend).unwrap();
        // `sample_issue` owns its relationship, so a store-resolved set for it
        // is exactly its own stored field.
        let issue = sample_issue();
        let relationships = issue.relationships.clone();
        let detail = DetailState {
            category: None,
            hierarchy: crate::commands::parent::facts_over(
                std::slice::from_ref(&issue),
                "done",
                issue.number,
            ),
            issue,
            relationships,
            chain: no_chain(),
            blocked: None,
            scroll_offset: 5,
            viewport: std::cell::Cell::new(0),
            max_scroll: std::cell::Cell::new(0),
            rel_cursor: 0,
            related: Vec::new(),
            related_cursor: 0,
            read_only: false,
        };
        terminal
            .draw(|f| render(&detail, f, f.area(), &crate::ui::color::Theme::default()))
            .unwrap();
    }

    /// tix #1513 T007: the `related:` block is drawn near the top (above the
    /// relationship row), carries a count, styles each entry as a chip, and marks
    /// the entry `o` will follow with a `>` — and is drawn at all only when the
    /// issue has `related_issues`.
    #[test]
    fn the_related_block_renders_a_count_chips_and_the_selection_marker() {
        let mut detail = detail_with(
            vec![crate::relationships::Relationship::new(
                1,
                2,
                crate::relationships::RelationKind::Related,
                "Twelve",
            )],
            no_chain(),
            None,
        );
        detail.related = crate::related::classify_all(&[
            "12".to_string(),
            "../other-repo/issues/2026-01-01-x.md".to_string(),
            "https://gitlab.com/foo/bar#7".to_string(),
        ]);
        detail.related_cursor = 1;
        let text = render_text(&detail);

        assert!(
            text.contains("related: 3"),
            "a count is drawn: got:\n{text}"
        );
        // Rows carry the block border, so a cell's text is the row with the border
        // and padding stripped.
        let cell = |line: &str| {
            line.trim_matches(|c: char| c == '│' || c == ' ')
                .to_string()
        };
        // Chips: the local selector, the relative path, and the URL.
        assert!(
            text.lines().any(|line| cell(line) == "12"),
            "the local chip is drawn: got:\n{text}"
        );
        assert!(
            text.lines()
                .any(|line| cell(line).contains("../other-repo/issues/2026-01-01-x.md")),
            "the path chip is drawn: got:\n{text}"
        );
        assert!(
            text.lines()
                .any(|line| cell(line).contains("https://gitlab.com/foo/bar#7")),
            "the URL chip is drawn: got:\n{text}"
        );
        // The `>` marker sits on the **selected** entry, and only on it.
        let selected = text
            .lines()
            .find(|line| cell(line).contains("../other-repo"))
            .expect("the selected line");
        assert!(
            cell(selected).starts_with("> "),
            "the selected related entry needs a marker: {selected:?}"
        );
        let first = text
            .lines()
            .find(|line| cell(line) == "12")
            .expect("the first line");
        assert!(
            !cell(first).contains('>'),
            "unselected related entries carry no marker: {first:?}"
        );
        // "Near the top, before the relationship row" — asserted by position.
        let related_at = text.find("related: 3").expect("the related block");
        let links_at = text.find("links: ").expect("the relationship row");
        assert!(
            related_at < links_at,
            "the related block must precede the links row: got:\n{text}"
        );

        // Absent when there is nothing to show: no empty heading on every issue.
        let empty = detail_with(vec![], no_chain(), None);
        let empty_text = render_text(&empty);
        assert!(
            !empty_text.contains("related:"),
            "an issue with no related_issues must draw no block: got:\n{empty_text}"
        );
    }

    #[test]
    fn assignee_render_identity_verbatim_bare_gets_at() {
        assert_eq!(render_assignee(None), None);
        assert_eq!(
            render_assignee(Some("Herbert Maschke <thyseus@pm.me>")),
            Some("Herbert Maschke <thyseus@pm.me>".to_string())
        );
        assert_eq!(render_assignee(Some("alice")), Some("@alice".to_string()));
        assert_eq!(render_assignee(Some("@alice")), Some("@alice".to_string()));
    }
}