Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,196 @@
//! The review overview — what the change is, and everything it touches.
//!
//! The review's front page. Read before the diff, not after it: a reviewer who reaches the first
//! hunk already knowing the intent spends their attention on judgement instead of reconstruction —
//! the part of review that does not automate away. It ends with the whole change as a contents
//! page, chapter by chapter and file by file, so "where is everything" is answered here rather
//! than in a third place.
//!
//! **Short on purpose.** Labeled sections between the intent and the contents would only repeat
//! what the reader has been told: the counts are on the rail, the accounted-for evidence is printed
//! on the item it accounts for, and the harness signals ride on the file they belong to. What is
//! here is what nothing else says. Facts that are worth raising only when they are *bad* — nothing
//! ran after the last edit, a source with no record behind it, files excluded from the capture —
//! are one line each in [`notice_lines`], and silent otherwise.
mod coverage;
mod files;
mod notices;
mod pull_request;
use crate::app::App;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
pub(super) use files::file_line;
pub(crate) use files::FileOwners;
use luxe_core::guided_review::GuidedReview;
pub(super) use notices::notice_lines;
#[cfg(test)]
use pull_request::description_opening;
#[cfg(test)]
use pull_request::is_closing_reference;
pub(super) use pull_request::pull_request_facts;
use pull_request::{earlier_conversation_lines, pull_request_account};
/// Judgement items past which a review is honestly more than one sitting.
///
/// Roughly an hour at the 200-lines-an-hour rate the inspection literature settles on — the point
/// where the useful advice is "review a smaller unit", not "keep going".
const LARGE_REVIEW_JUDGEMENT_ITEMS: usize = 40;
/// The change's own intent, as the guide wrote it — or the raw record of the turn, labeled, when
/// the guide pass did not land.
///
/// The document's opening, before any chapter. Everything a reviewer wants before they read a line
/// of code and nothing they have already been told: the counts are in the head above it, and what
/// accounts for an exclusion is printed on the item it accounts for.
pub(super) fn intent_lines(app: &App, review: &GuidedReview, width: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines: Vec<Line<'static>> = Vec::new();
let provenance = review.provenance.as_ref();
let pull_request = review.context.pull_request.as_ref();
match review.brief.as_ref() {
Some(brief) => {
lines.extend(prose_lines(&brief.intent, app, width, " "));
if !brief.account.is_empty() {
lines.push(Line::default());
for claim in &brief.account {
lines.extend(bullet_lines(claim, app, width));
}
}
}
None => {
if let Some(requests) =
provenance.map(|provenance| &provenance.requests).filter(|it| !it.is_empty())
{
for request in requests {
lines.extend(prose_lines(request, app, width, " "));
}
lines.push(Line::default());
}
if let Some(account) = provenance.and_then(|provenance| provenance.account.as_deref()) {
lines.extend(prose_lines(account, app, width, " "));
lines.push(Line::from(Span::styled(
" the agent\u{2019}s own words \u{2014} no summary was written for this review",
styles.dim,
)));
}
}
}
// The author's own account: a claim to weigh against the chapters, which is why it follows the
// narrator's reading rather than leading it
if let Some(pr) = pull_request {
lines.extend(pull_request_account(app, pr, width));
}
if let Some(conversation) = review.conversation.as_ref() {
lines.extend(earlier_conversation_lines(app, conversation, width));
}
// What the reviewed commits say. Finished work has no turn to account for it, so its own
// messages are the intent — without this a `base`/`commit` review opens on nothing. The heading
// counts them because "the commits" invites the question of *which*: these are the ones in the
// reviewed range, never the project's history.
//
// Not for a pull request: its description is the author's account, and for a one-commit pull
// request GitHub prefills that description from the commit message, so the section repeats it
// nearly word for word. The guide still reads both.
if let Some(intent) = review
.context
.source_intent
.as_deref()
.filter(|it| !it.is_empty() && review.context.pull_request.is_none())
{
lines.push(Line::default());
lines.push(Line::from(Span::styled(
match review.context.source_commits {
0 | 1 => "What this commit says".to_string(),
count => format!("What these {count} commits say"),
},
styles.accent,
)));
lines.extend(prose_lines(intent, app, width, " "));
}
if !lines.is_empty() {
lines.push(Line::default());
}
lines
}
/// Model-written prose as wrapped, indented markdown lines.
///
/// Rendered, not printed: a summary arrives with headings, emphasis and bullets in it, and one
/// multi-line string in a single `Line` loses its newlines, so `## What was happening` runs into
/// the sentence before it.
///
/// Wrapped here rather than by the widget, because the caller counts these rows to decide what is
/// on screen: a line the paragraph wraps behind its back is a row the scroll offset does not know
/// about, and the selection drifts by one for every one of them.
pub(super) fn prose_lines(text: &str, app: &App, width: usize, indent: &str) -> Vec<Line<'static>> {
let budget = width.saturating_sub(indent.width()).max(20);
crate::markdown::render_markdown(text, &app.theme_styles)
.into_iter()
.flat_map(|line| crate::widgets::wrap_line(&line, budget))
.map(|line| {
let mut spans = vec![Span::raw(indent.to_owned())];
spans.extend(line.spans);
Line::from(spans)
})
.collect()
}
/// One claim, bulleted, with its wrapped tail indented under the text rather than the bullet.
fn bullet_lines(text: &str, app: &App, width: usize) -> Vec<Line<'static>> {
let mut rendered = prose_lines(text, app, width, " ");
if rendered.is_empty() {
return Vec::new();
}
let first = rendered.remove(0);
let mut spans = vec![Span::styled(" \u{2022} ", app.theme_styles.dim)];
spans.extend(first.spans.into_iter().skip(1));
let mut lines = vec![Line::from(spans)];
lines.extend(rendered);
lines
}
#[cfg(test)]
mod tests {
use super::*;
/// A long description opens with its first paragraphs and says there is more; a template
/// heading and a bare `Fixes #n` are left for the sections that show them better.
#[test]
fn a_description_opens_with_its_first_paragraphs() {
let body = format!(
"Fixes #14404\n\n### Description\n\nThe owner casing differed.\n\n{}\n\n{}",
"a".repeat(300),
"b".repeat(400)
);
let (opening, more) = description_opening(&body);
assert!(opening.starts_with("The owner casing differed."), "{opening}");
assert!(opening.contains(&"a".repeat(300)));
assert!(!opening.contains('b'), "past the budget");
assert!(!opening.contains("Fixes") && !opening.contains("###"), "{opening}");
assert!(more);
assert_eq!(
description_opening("Short and complete."),
("Short and complete.".into(), false)
);
assert_eq!(description_opening("Fixes #3"), (String::new(), false));
let lone = "x".repeat(900);
assert_eq!(description_opening(&lone), (lone.clone(), false), "one paragraph is never cut");
}
#[test]
fn a_closing_reference_is_one_verb_and_one_issue() {
for line in ["Fixes #12", "closes acme/app#3", "Resolves #9"] {
assert!(is_closing_reference(line), "{line}");
}
for line in ["Fixes the parser", "Fixes #12 and #13", "#12", "See #12"] {
assert!(!is_closing_reference(line), "{line}");
}
}
}

View File

@@ -0,0 +1,68 @@
//! Coverage — what a review leaves out, said where the reader starts.
//!
//! Counted, never silent: a review that shows less than the diff has to say so, whether a project
//! asked for the omission or the capture could not hold a file.
use luxe_core::guided_review::GuidedReview;
use ratatui::text::{Line, Span};
use crate::theme::styles::ThemeStyles;
/// The rows saying what this review does not show, in the order they matter.
pub(super) fn coverage_lines(review: &GuidedReview, styles: &ThemeStyles) -> Vec<Line<'static>> {
let mut lines = Vec::new();
if let Some(uncovered) = uncovered_note(review) {
lines.push(Line::from(Span::styled(uncovered, styles.warning)));
}
if review.stats.excluded_files > 0 {
lines.push(Line::from(Span::styled(
format!(
"{} {} excluded by review.exclude",
review.stats.excluded_files,
if review.stats.excluded_files == 1 { "file" } else { "files" }
),
styles.dim,
)));
}
lines
}
/// Names the changed files the capture could not include, a few of them, so a clean review of the
/// rest never reads as a clean review of everything.
fn uncovered_note(review: &GuidedReview) -> Option<String> {
const NAMED: usize = 3;
let paths = &review.source.uncovered_paths;
if paths.is_empty() {
return None;
}
let named: Vec<String> =
paths.iter().take(NAMED).map(|path| luxe_core::paths::display(path)).collect();
let more = match paths.len().saturating_sub(NAMED) {
0 => String::new(),
rest => format!(" and {rest} more"),
};
Some(format!(
"Changed but not shown, too large or not a readable file: {}{more}",
named.join(", ")
))
}
#[cfg(test)]
mod tests {
use super::*;
/// A review missing files names them, a few at a time, and a complete one says nothing.
#[test]
fn a_review_says_which_files_it_could_not_cover() {
let mut review = crate::fixture::fixture_demo_guided_review();
assert_eq!(uncovered_note(&review), None);
review.source.uncovered_paths = vec!["docs/big.md".into()];
let note = uncovered_note(&review).expect("said");
assert!(note.ends_with(": docs/big.md"), "{note}");
review.source.uncovered_paths = ["a", "b", "c", "d", "e"].map(Into::into).to_vec();
let note = uncovered_note(&review).expect("said");
assert!(note.ends_with(": a, b, c and 2 more"), "{note}");
}
}

View File

@@ -0,0 +1,163 @@
//! Brief files — which chapter owns each file, and the file rows the brief lists.
use super::super::context::review_file_status_style;
use crate::app::App;
use luxe_core::guided_review::{
Accounted, FileId, GuidedReview, HunkId, ItemVerdict, ReviewChapter, ReviewFile, ReviewHunk,
ReviewItemRef,
};
use ratatui::text::{Line, Span};
use std::collections::HashMap;
/// Which file owns each id a chapter can reference.
///
/// A chapter names files and hunks by id, and resolving one by scanning every file's every hunk
/// is quadratic in the review — a forty-file change spent a few hundred thousand comparisons a
/// frame answering the same question. Built once per pass and asked per item.
pub(crate) struct FileOwners<'a> {
by_file: HashMap<&'a FileId, &'a ReviewFile>,
by_hunk: HashMap<&'a HunkId, &'a ReviewFile>,
}
impl<'a> FileOwners<'a> {
/// Indexes every file and hunk in `review`.
pub(crate) fn of(review: &'a GuidedReview) -> Self {
let mut by_file = HashMap::with_capacity(review.files.len());
let mut by_hunk = HashMap::new();
for file in &review.files {
by_file.insert(&file.id, file);
for hunk in &file.hunks {
by_hunk.insert(&hunk.id, file);
}
}
Self { by_file, by_hunk }
}
/// The file one chapter item lives in.
fn owner(&self, item: &ReviewItemRef) -> Option<&'a ReviewFile> {
match item {
ReviewItemRef::File(file_id) => self.by_file.get(file_id).copied(),
ReviewItemRef::Hunk(hunk_id) => self.by_hunk.get(hunk_id).copied(),
}
}
/// The files a chapter owns, in the order it lists them.
///
/// A chapter references hunks as often as whole files, so a hunk resolves to the file that
/// holds it and repeats are dropped — otherwise a chapter that touches one file six times
/// lists it six times.
pub(crate) fn chapter_files(&self, chapter: &ReviewChapter) -> Vec<&'a ReviewFile> {
let mut files: Vec<&ReviewFile> = Vec::new();
for item in &chapter.items {
if let Some(file) = self.owner(item) {
if !files.iter().any(|seen| seen.id == file.id) {
files.push(file);
}
}
}
files
}
}
/// One file under its chapter: status, path, its share of the change, and why it is accounted for.
pub(in crate::view::guided_review) fn file_line(
app: &App,
file: &ReviewFile,
selected: bool,
width: usize,
) -> Line<'static> {
use luxe_core::guided_review::ReviewFileStatus as Status;
let styles = &app.theme_styles;
let letter = match file.status {
Status::Added => "A",
Status::Modified => "M",
Status::Deleted => "D",
Status::Renamed => "R",
Status::Copied => "C",
Status::Untracked => "?",
};
let path = file
.new_path
.as_deref()
.or(file.old_path.as_deref())
.map_or_else(|| "(unknown path)".to_owned(), |path| path.display().to_string());
// The path is elided from the left where it must be: the basename is what identifies a file,
// and a pane sized for prose has little room for the rest.
let shown = crate::widgets::elide_path_components(
&path,
width.saturating_sub(FILE_ROW_LEAN + crate::widgets::SELECTION_FRAME + 14).max(8),
);
let mut spans = vec![
Span::styled(format!("{letter} "), review_file_status_style(file.status, app)),
Span::styled(shown, styles.text),
];
spans.extend(change_spans(app, file, &file.hunks.iter().collect::<Vec<_>>()));
// One reason, said once, when it covers the whole file. Repeating it per hunk was how a
// forty-file listing turned into four hundred identical claims.
if let Some(reason) = shared_reason(app, file) {
spans.push(Span::styled(
format!(" {reason}"),
if selected { styles.muted } else { styles.dim },
));
}
// Attention rides on the file it belongs to, where the decision to open it is made — but not
// on the file being read, where the detail pane is already spelling the same concern out in a
// sentence beside its code. A badge there is the warning said twice in two widths.
let mut flags = app.review.flags.iter().filter(|_| !selected);
if let Some(signal) = flags.find(|signal| signal.path.as_deref() == Some(path.as_str())) {
spans.push(Span::styled(format!(" {}", signal.kind.badge()), styles.warning));
}
// Cut from the slab that means *chosen* everywhere else, over the pane's own fill rather than
// the color behind it. The frame is spent on every row, which is what indents the list under
// the chapter that owns it and stops names sliding sideways as the cursor arrives.
crate::widgets::selection_row_on(
spans,
// The lean is spent *outside* the slab, so the room it gets is what is left after it.
width.saturating_sub(FILE_ROW_LEAN),
FILE_ROW_LEAN,
selected,
styles.tool_bg.bg.unwrap_or(styles.slab.canvas),
styles,
)
}
/// Cells a file row leans in under the chapter heading that owns it.
const FILE_ROW_LEAN: usize = 2;
/// The one thing that accounts for *every* hunk in this file, when there is one.
fn shared_reason(app: &App, file: &ReviewFile) -> Option<String> {
let mut reasons =
file.hunks.iter().map(|hunk| match app.review.budget.hunk_verdict(&hunk.id) {
ItemVerdict::Accounted(accounted) => Some(accounted),
ItemVerdict::NeedsReview => None,
});
let first: Accounted = reasons.next()??;
reasons.all(|reason| reason.as_ref() == Some(&first)).then(|| format!("all {}", first.label()))
}
/// `+12 −3` for a text file, or what the change actually was for one with no lines to count.
fn change_spans(app: &App, file: &ReviewFile, owned: &[&ReviewHunk]) -> Vec<Span<'static>> {
let styles = &app.theme_styles;
if let Some(change) = file.non_text.as_ref() {
return vec![Span::styled(format!(" {}", change.summary), styles.muted)];
}
// Git's own figures where it gave them, so the guide and the dock agree about the same file.
// Summing the visible hunks would report the *shown* change, which is a different number the
// moment anything is folded.
let (additions, deletions) = match (file.additions, file.deletions) {
(Some(additions), Some(deletions)) => (additions as usize, deletions as usize),
_ if owned.is_empty() => return Vec::new(),
_ => owned.iter().flat_map(|hunk| hunk.lines.iter()).fold(
(0usize, 0usize),
|(add, del), line| match line.kind {
luxe_core::guided_review::ReviewLineKind::Addition => (add + 1, del),
luxe_core::guided_review::ReviewLineKind::Deletion => (add, del + 1),
_ => (add, del),
},
),
};
vec![
Span::styled(format!(" +{additions}"), styles.success),
Span::styled(format!(" \u{2212}{deletions}"), styles.error),
]
}

View File

@@ -0,0 +1,120 @@
//! Brief notices — where the work came from and what needs the reader's attention.
//!
//! Facts about the review that are worth a row only when they are *bad*. Inside a labeled section
//! that ran whether or not it had anything to say, the one row that mattered would be buried in
//! filler. Here they are silent by default, and each one is a sentence a reviewer would want
//! interrupting them.
use super::{coverage, LARGE_REVIEW_JUDGEMENT_ITEMS};
use crate::app::App;
use luxe_core::guided_review::{AttentionSignal, GuidedReview};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// What this review will not tell you unless it is told to, in the order it matters.
///
/// Bounded by construction rather than by a cap: every entry is conditional and rare, and the
/// aggregate harness signals — the only unbounded source — contribute at most one row a kind.
pub(in crate::view::guided_review) fn notice_lines(
app: &App,
review: &GuidedReview,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines: Vec<Line<'static>> = Vec::new();
if let Some(warning) = unverified_note(review) {
lines.push(Line::from(Span::styled(warning, styles.warning)));
}
// A review this size is not one sitting. Name the smaller unit rather than letting the
// reviewer discover the problem forty hunks in.
if app.review.budget.needs_review > LARGE_REVIEW_JUDGEMENT_ITEMS {
lines.push(Line::from(Span::styled(
"More than one sitting · s picks a smaller source",
styles.warning,
)));
}
// Say why the budget could not help, rather than presenting a wall of work as if that were the
// reviewer's problem. A pull request was written somewhere else, which its reader knows.
if review.context.pull_request.is_none()
&& app.review.budget.needs_review > 0
&& no_provenance(review)
{
lines
.push(Line::from(Span::styled("No record of the work behind this source", styles.dim)));
}
lines.extend(coverage::coverage_lines(review, styles));
// A kind past its cap gets its total, one row each. Every flagged file wears its own badge in
// the contents, so the call-outs' "2 more" would read as two hidden somewhere.
for signal in app.review.attention.iter().filter(|signal| signal.aggregate) {
let total = flagged_total(app, signal.kind);
let said = format!("{total} {}", signal.kind.plural());
lines.push(Line::from(Span::styled(said, attention_style(app, signal))));
}
// What this session did elsewhere is a fact about the session, and a pull request is not it
if let Some(outside) = work_done_outside(app).filter(|_| review.context.pull_request.is_none())
{
// `info`, not a warning: this is a fact about what the review's source is, not a suspicion
// about the change inside it.
lines.push(Line::from(Span::styled(outside, styles.info)));
}
lines
}
/// What the harness knows about whether anything was run, said only when the answer is unwelcome.
///
/// Silent when a command ran after the last edit, because "the tests passed" is the expected state
/// and a row that always renders stops being read. Silent too when there is nothing to judge it
/// against — a `base` or `commit` review has no turn behind it, so it is not *unverified*, it is
/// simply not that kind of source.
fn unverified_note(review: &GuidedReview) -> Option<&'static str> {
let provenance = review.provenance.as_ref()?;
if provenance.written_paths.is_empty() {
return None;
}
if provenance.commands.is_empty() {
Some("No command was run in this work")
} else if !provenance.verified_after_last_edit {
Some("Nothing ran after the last edit")
} else {
None
}
}
/// What this session changed outside the project, or `None` when it stayed inside.
///
/// A review is captured from the project's worktree, so those files are not in it and no amount of
/// reading the diff will reveal them. Saying so is the difference between a review that is
/// *scoped* and one that quietly claims to be the whole session.
fn work_done_outside(app: &App) -> Option<String> {
let external = &app.workspace.as_ref()?.external;
if external.is_empty() {
return None;
}
let files = external.total_files;
Some(format!(
"{files} {} changed elsewhere this session",
if files == 1 { "file" } else { "files" }
))
}
/// Whether the review has no record of the work that produced it (a base/commit review, or a
/// working tree Luxe did not write).
fn no_provenance(review: &GuidedReview) -> bool {
review.provenance.as_ref().is_none_or(|provenance| {
provenance.commands.is_empty() && provenance.written_paths.is_empty()
})
}
/// Color by urgency: a possible credential or a weakened gate outranks an unread edit.
fn attention_style(app: &App, signal: &AttentionSignal) -> Style {
use luxe_core::guided_review::AttentionKind;
match signal.kind {
AttentionKind::SecretShaped | AttentionKind::GateWeakened => app.theme_styles.error,
AttentionKind::BlindEdit => app.theme_styles.warning,
}
}
/// How many lines or files of `kind` the review flags: a credential or a weakened gate is a line,
/// an unread edit a file.
fn flagged_total(app: &App, kind: luxe_core::guided_review::AttentionKind) -> usize {
app.review.flags.iter().filter(|flag| flag.kind == kind).count()
}

View File

@@ -0,0 +1,343 @@
//! Brief pull request — what the author said, the facts about the pull request, and the conversation
//! before this review.
use super::super::diff_render::{display_author, is_feedback, thread_is_feedback};
use super::{bullet_lines, prose_lines};
use crate::app::App;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// One row of facts about a pull request: who opened it, and where it stands.
///
/// Drawn in the pane's fixed head under the row that names the pull request, so it is on screen
/// however far the guide has scrolled. Every fact is a word, colored only for emphasis: `draft`,
/// `2 failing`, `changes requested`.
pub(in crate::view::guided_review) fn pull_request_facts(
app: &App,
pr: &luxe_core::guided_review::PullRequestContext,
width: usize,
) -> Vec<Line<'static>> {
use luxe_core::guided_review::{PullRequestStatus, PullRequestVerdict};
let styles = &app.theme_styles;
let separator = || Span::styled(" \u{b7} ", styles.dim);
let mut spans = vec![Span::styled(
match pr.author_is_bot {
true => format!("by {} (bot)", pr.author_name()),
false => format!("by {}", pr.author_name()),
},
styles.text,
)];
let mut fact = |text: String, style: Style| {
spans.push(separator());
spans.push(Span::styled(text, style));
};
if pr.draft {
fact("draft".into(), styles.warning);
}
match pr.status {
PullRequestStatus::Open => {}
PullRequestStatus::Merged => fact("merged".into(), styles.success),
PullRequestStatus::Closed => fact("closed".into(), styles.dim),
}
let checks = pr.checks;
if checks.passed + checks.failed + checks.pending + checks.skipped > 0 {
let mut parts = Vec::new();
if checks.failed > 0 {
parts.push((format!("{} failing", checks.failed), styles.error));
}
if checks.pending > 0 {
parts.push((format!("{} running", checks.pending), styles.warning));
}
if checks.passed > 0 {
let noun = if checks.passed == 1 { "check" } else { "checks" };
parts.push((format!("{} {noun} passed", checks.passed), styles.dim));
}
for (text, style) in parts {
fact(text, style);
}
}
match pr.verdict {
Some(PullRequestVerdict::Approved) => fact("approved".into(), styles.success),
Some(PullRequestVerdict::ChangesRequested) => {
fact("changes requested".into(), styles.warning)
}
Some(PullRequestVerdict::ReviewRequired) => fact("review required".into(), styles.dim),
None => {}
}
crate::widgets::wrap_line(&Line::from(spans), width.max(20))
}
/// The author's description and the issues it says it closes, each under its own heading.
pub(super) fn pull_request_account(
app: &App,
pr: &luxe_core::guided_review::PullRequestContext,
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
lines.push(Line::default());
lines.push(Line::from(Span::styled("What the pull request says", styles.accent)));
lines.extend(prose_lines(&pr.title, app, width, " "));
lines.push(Line::from(Span::styled(
format!(" {} \u{2192} {}", pr.head_ref, pr.base_ref),
styles.dim,
)));
let (opening, more) = description_opening(&pr.body);
if opening.is_empty() {
lines.push(Line::from(Span::styled(" The author wrote no description.", styles.dim)));
} else {
lines.push(Line::default());
lines.extend(prose_lines(&opening, app, width, " "));
if more {
lines.push(Line::from(Span::styled(
" The rest of the description is on GitHub \u{b7} o",
styles.dim,
)));
}
}
if !pr.closing_issues.is_empty() {
lines.push(Line::default());
lines.push(Line::from(Span::styled("What it closes", styles.accent)));
for issue in &pr.closing_issues {
let reference = if issue.repository.eq_ignore_ascii_case(&pr.repository) {
format!("#{}", issue.number)
} else {
format!("{}#{}", issue.repository, issue.number)
};
let title = issue.title.as_deref().unwrap_or("could not be read");
lines.extend(bullet_lines(&format!("{reference} {title}"), app, width));
}
if pr.more_closing_issues > 0 {
lines.push(Line::from(Span::styled(
format!(" and {} more", pr.more_closing_issues),
styles.dim,
)));
}
}
lines
}
/// What reviewers already said: a count, then every thread that has no line to sit on.
///
/// Two kinds of thing live here, and GitHub keeps them apart the same way: a *thread* is a review
/// comment on the code, with replies and a resolved state; a *comment* is a post in the pull
/// request's conversation, on no line at all. The threads that do map are drawn under their lines
/// in the diff, so this lists only the rest — outdated, on a whole file, or on a line no hunk shows
/// — and never drops one. A conversation that could not be read says so, rather than looking like
/// one nobody started.
pub(super) fn earlier_conversation_lines(
app: &App,
conversation: &luxe_core::guided_review::EarlierConversation,
width: usize,
) -> Vec<Line<'static>> {
use luxe_core::guided_review::EarlierConversation;
let styles = &app.theme_styles;
let heading = || Line::from(Span::styled("Discussion on GitHub", styles.accent));
let (threads, more, said) = match conversation {
EarlierConversation::Unreadable => {
return vec![
Line::default(),
heading(),
Line::from(Span::styled(
" Could not be read from GitHub \u{b7} o opens the pull request",
styles.dim,
)),
];
}
EarlierConversation::Read { threads, more, said } => (threads, *more, said),
};
// Threads and comments that became feedback are listed there, not here
let as_feedback = threads.iter().filter(|thread| thread_is_feedback(app, thread)).count()
+ said.iter().filter(|entry| is_feedback(app, &entry.id)).count();
let threads: Vec<&luxe_core::guided_review::EarlierThread> =
threads.iter().filter(|thread| !thread_is_feedback(app, thread)).collect();
let said: Vec<&luxe_core::guided_review::ConversationEntry> =
said.iter().filter(|entry| !is_feedback(app, &entry.id)).collect();
if threads.is_empty() && more == 0 && as_feedback == 0 && said.is_empty() {
return Vec::new();
}
let parts = discussion_rollup(&threads, more, as_feedback, said.len());
let summary = format!(" {}", parts.join(" \u{b7} "));
let mut lines = vec![Line::default(), heading(), Line::from(Span::styled(summary, styles.dim))];
lines.extend(off_diff_thread_rows(app, &threads, width));
lines.extend(conversation_entry_rows(app, &said, width));
if more > 0 {
lines.push(Line::from(Span::styled(
format!(" {more} more on GitHub \u{b7} o"),
styles.dim,
)));
}
lines
}
/// The discussion's one-line count: what became feedback, the threads left and how many are
/// unresolved, and the comments in the conversation.
fn discussion_rollup(
threads: &[&luxe_core::guided_review::EarlierThread],
more: usize,
as_feedback: usize,
said: usize,
) -> Vec<String> {
let unresolved = threads.iter().filter(|thread| !thread.resolved).count();
let total = threads.len() + more;
let noun = if total == 1 { "thread" } else { "threads" };
let mut parts = Vec::new();
if as_feedback > 0 {
parts.push(format!("{as_feedback} in your feedback"));
if total > 0 {
parts.push(format!("{total} more {noun}"));
}
} else {
parts.push(format!("{total} {noun}"));
}
if total > 0 {
parts.push(format!("{unresolved} unresolved"));
}
// A conversation with no threads at all still says so, rather than counting zero of them
if total == 0 && as_feedback == 0 {
parts.clear();
}
match said {
0 => {}
1 => parts.push("1 comment".into()),
n => parts.push(format!("{n} comments")),
}
parts
}
/// The threads on code the diff no longer shows, each as where it is and how it opened.
fn off_diff_thread_rows(
app: &App,
threads: &[&luxe_core::guided_review::EarlierThread],
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
for thread in threads.iter().filter(|thread| thread.anchor.is_none()) {
let mut place = vec![Span::styled(thread.path.clone(), styles.text)];
let mut facts = Vec::new();
match (thread.file_level, thread.line) {
(true, _) => facts.push("whole file".to_owned()),
(false, Some(line)) if !thread.outdated => {
place.push(Span::styled(format!(":{line}"), styles.text));
}
_ => {}
}
if thread.outdated {
facts.push("outdated".into());
}
if thread.resolved {
facts.push("resolved".into());
}
if !facts.is_empty() {
place.push(Span::styled(format!(" \u{b7} {}", facts.join(" \u{b7} ")), styles.dim));
}
let opening = thread.comments.first();
let author = opening.map_or_else(String::new, |comment| display_author(&comment.author));
let said = opening.and_then(|comment| comment.body.lines().next()).unwrap_or_default();
lines.extend(discussion_item(app, &author, place, said, width));
}
lines
}
/// The comments in the conversation itself, each as who said it and its first line.
fn conversation_entry_rows(
app: &App,
said: &[&luxe_core::guided_review::ConversationEntry],
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
for entry in said {
let first = entry.body.lines().map(str::trim).find(|line| !line.is_empty());
let author = display_author(&entry.author);
let place = vec![Span::styled("in the conversation", styles.dim)];
lines.extend(discussion_item(app, &author, place, first.unwrap_or_default(), width));
}
lines
}
/// One entry of the discussion: who and where on one line, what they said under it.
///
/// Built from spans rather than handed to the markdown renderer with the path in backticks, because
/// the quote is a stranger's text and whatever markup it carries must stay text. The name wears the
/// secondary accent and the place the brightest ink, so a reader scanning the list finds both
/// without the quote competing for either.
fn discussion_item(
app: &App,
author: &str,
place: Vec<Span<'static>>,
said: &str,
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let budget = width.saturating_sub(3).max(20);
let mut head = vec![
Span::styled(author.to_owned(), styles.accent_secondary),
Span::styled(" \u{b7} ", styles.dim),
];
head.extend(place);
let mut lines = Vec::new();
for (index, row) in crate::widgets::wrap_line(&Line::from(head), budget).into_iter().enumerate()
{
let lead =
if index == 0 { Span::styled(" \u{2022} ", styles.dim) } else { Span::raw(" ") };
let mut spans = vec![lead];
spans.extend(row.spans);
lines.push(Line::from(spans));
}
let said = said.trim();
if !said.is_empty() {
let quote = Line::from(Span::styled(said.to_owned(), styles.muted));
for row in crate::widgets::wrap_line(&quote, budget).into_iter().take(3) {
let mut spans = vec![Span::raw(" ")];
spans.extend(row.spans);
lines.push(Line::from(spans));
}
}
lines
}
/// Characters of a pull request's description the brief shows before pointing at GitHub.
const DESCRIPTION_OPENING_CHARS: usize = 600;
/// The first paragraphs of a description, and whether there is more.
///
/// The guide scrolls to keep the current chapter in view, so a long description in full pushes the
/// chapters down and opens the pane in the middle of someone's prose with its heading gone — which
/// the first real pull request did. The guide's prompt still gets all of it. Template headings and
/// a bare `Fixes #n` are skipped: the issues it closes have their own section.
pub(super) fn description_opening(body: &str) -> (String, bool) {
let paragraphs: Vec<&str> = body
.split("\n\n")
.map(str::trim)
.filter(|paragraph| !paragraph.is_empty())
.filter(|paragraph| !paragraph.starts_with('#') || paragraph.contains('\n'))
.filter(|paragraph| !is_closing_reference(paragraph))
.collect();
let mut opening = String::new();
let mut taken = 0;
for paragraph in &paragraphs {
if taken > 0
&& opening.chars().count() + paragraph.chars().count() > DESCRIPTION_OPENING_CHARS
{
break;
}
if taken > 0 {
opening.push_str("\n\n");
}
opening.push_str(paragraph);
taken += 1;
}
(opening, taken < paragraphs.len())
}
/// `Fixes #12`, `closes owner/repo#3`: a line GitHub reads as a link to an issue, and nothing more.
pub(super) fn is_closing_reference(paragraph: &str) -> bool {
let lower = paragraph.to_ascii_lowercase();
let Some((verb, reference)) = lower.split_once(char::is_whitespace) else { return false };
matches!(verb, "fixes" | "fix" | "closes" | "close" | "resolves" | "resolve")
&& reference.trim().contains('#')
&& !reference.trim().contains(char::is_whitespace)
}

View File

@@ -0,0 +1,159 @@
//! Guided Review context panes — narrow/medium headers, Guide/Files summaries, and
//! the finding/outcome summary strings.
mod foot;
mod guide;
mod metadata;
mod summary;
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
pub(super) use guide::render_guide_pane;
pub(super) use metadata::medium_context_lines;
use metadata::{review_metadata_summary, review_title};
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::Frame;
pub(super) use summary::{submission_dispatch_label, with_the_agent};
use unicode_width::UnicodeWidthStr;
pub(super) fn render_narrow_context(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
let chapter_index = app
.guided_review_workspace
.position
.chapter_id
.as_ref()
.and_then(|id| review.chapters.iter().position(|chapter| &chapter.id == id))
.unwrap_or_default();
let chapter_title = review
.chapters
.get(chapter_index)
.map_or_else(|| "Review".into(), |chapter| chapter.title.clone());
let file_path = app
.guided_review_workspace
.position
.file_id
.as_ref()
.and_then(|id| review.files.iter().find(|file| &file.id == id))
.and_then(|file| file.new_path.as_deref().or(file.old_path.as_deref()))
.map_or_else(|| "(unknown path)".into(), |path| path.display().to_string());
let (hidden_hunks, _) = app.guided_review_workspace.hidden_counts(&review.files);
let hidden = if hidden_hunks > 0 {
if app.guided_review_workspace.noise_details_visible {
format!(" · {hidden_hunks} fmt/gen/lock/mech")
} else {
format!(" · {hidden_hunks} collapsed")
}
} else {
Default::default()
};
// Budget the path last and left-truncate it, so the filename and the folded-hunk count both
// survive. A plain format string let the terminal cut the row mid-path and drop the count.
let prefix = format!(
"{:02}/{:02} · {chapter_title} · ",
chapter_index + 1,
review.chapters.len().max(1)
);
let budget =
usize::from(area.width).saturating_sub(prefix.width()).saturating_sub(hidden.width());
let lines = vec![
Line::from(Span::styled(
clip_terminal_cells_ellipsis(review_title(review), usize::from(area.width)),
app.theme_styles.accent.add_modifier(ratatui::style::Modifier::BOLD),
)),
Line::from(Span::styled(
clip_terminal_cells_ellipsis(
&review_metadata_summary(app, review),
usize::from(area.width),
),
app.theme_styles.muted,
)),
Line::from(Span::styled(
format!(
"{prefix}{}{hidden}",
crate::widgets::elide_path_components(&file_path, budget)
),
app.theme_styles.muted,
)),
];
frame.render_widget(Paragraph::new(lines), area);
}
pub(super) fn render_medium_context(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
frame.render_widget(
Paragraph::new(medium_context_lines(app, review)).wrap(Wrap { trim: true }),
area,
);
}
/// Formats `count` with the singular noun when it is exactly 1, else the plural noun.
fn plural(count: usize, singular: &str, plural: &str) -> String {
format!("{count} {}", if count == 1 { singular } else { plural })
}
/// The git-status color for a Files-mode status letter, matching the dock's FILES palette.
pub(super) fn review_file_status_style(
status: luxe_core::guided_review::ReviewFileStatus,
app: &App,
) -> ratatui::style::Style {
use luxe_core::guided_review::ReviewFileStatus as Status;
match status {
Status::Added | Status::Untracked => app.theme_styles.success,
Status::Modified => app.theme_styles.warning,
Status::Deleted => app.theme_styles.error,
Status::Renamed | Status::Copied => app.theme_styles.info,
}
}
// === The guide pane ===
//
// The left half of the review: what the change is, in the order a person would explain it, with
// the reviewer's place marked in it. The right half is the evidence under whatever it has
// selected.
//
// Three zones, which is the Context Dock's own shape. The head says what is being read, the foot
// says what it wants from you, and everything between is the thing itself — so the only part that
// moves is the part worth watching. The pane takes clicks and the wheel and holds no cursor of its
// own: [`crate::guided_review::ReviewPosition`] is the surface's one selection, and this follows
// it.
/// One line of context where the guide pane is put away, so the reader still knows where they are.
pub(super) fn render_hidden_guide_header(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
let styles = &app.theme_styles;
let mut spans = vec![Span::raw(" ")];
if let Some((index, chapter)) = review.chapters.iter().enumerate().find(|(_, chapter)| {
app.guided_review_workspace.position.chapter_id.as_ref() == Some(&chapter.id)
}) {
spans.push(Span::styled(
format!("{:02} / {:02} ", index + 1, review.chapters.len()),
styles.dim,
));
spans.push(Span::styled(chapter.title.clone(), styles.accent));
} else {
spans.push(Span::styled(review_title(review).to_string(), styles.accent));
}
if let Some((at, total)) = app.guided_review_workspace.walkthrough_step(review) {
spans.push(Span::styled(format!(" Step {at} of {total}"), styles.muted));
}
spans.push(Span::styled(" alt+v shows the guide", styles.dim));
frame.render_widget(Paragraph::new(Line::from(spans)), area);
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,271 @@
//! The guide's foot — the feedback written so far, and what to do next.
use super::super::overlays::finding_state_glyph;
use super::super::{chord, feedback_window};
use super::summary::{
checks_label, collapsed_banner, feedback_tally, folded_reasons, review_outcome_label,
review_summary, ChecksTone,
};
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
/// Most comments the foot lists before pointing at the feedback window for the rest.
const FOOT_COMMENTS: usize = 4;
/// The guide's foot: the feedback, and what the review wants from you next.
///
/// Pinned to the bottom of the pane so "what have I said, and what is waiting on me" is always in
/// the same place. With no feedback yet there is no heading for it, and a foot with nothing to say
/// is not drawn at all: a `FEEDBACK none yet` row told the reader only that the rail had a slot. The comments are listed rather than counted, the way the post preview lists
/// them, so the foot is a way back to each one rather than a number to remember. Where you are is
/// the head's job now (`Step 3 of 7`), and the folded churn says what it is on its own row in the
/// diff, so neither costs the foot a line.
pub(super) fn guide_foot_lines(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
width: u16,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let pull_request = crate::app::github_post_is_pull_request(app);
let mut lines = vec![Line::default()];
lines.extend(feedback_foot(app, usize::from(width), pull_request));
if walkthrough_is_empty(app, review) {
// Nothing to walk is worth saying; it is the one thing a missing step counter cannot
lines.push(Line::from(Span::styled(review_summary(app), styles.success)));
}
// Posted is the answer to "what comes next", so it takes the prompt's place: a toast saying
// it went is gone in seconds, and a foot still offering to post read as if it had not
let posted = pull_request.then(|| posted_verdict(app.review.session())).flatten();
if let Some(verdict) = posted {
lines.extend(posted_next_action(app, verdict));
}
// Read to the end is when the reader wants to know what comes next, and nothing else says it
let (walked, total) = app.guided_review_workspace.chapters_walked(review);
if total > 0 && walked == total && posted.is_none() {
lines.push(walkthrough_next_action(app, pull_request));
}
if let Some(outcome) = review_outcome_label(app.review.session()).filter(|_| posted.is_none()) {
lines.push(Line::from(Span::styled(format!("Outcome: {outcome}"), styles.muted)));
}
if let Some((tone, label)) = checks_label(review) {
let style = match tone {
ChecksTone::Passed => styles.success,
ChecksTone::Failed => styles.error,
ChecksTone::Unsettled => styles.warning,
};
lines.push(Line::from(Span::styled(label, style)));
}
lines.extend(folded_reason_rows(app, review));
if lines.len() == 1 {
lines.clear();
}
lines
}
/// The feedback heading and the first few comments, with a pointer to the window for the rest;
/// nothing until there is feedback.
fn feedback_foot(app: &App, width: usize, pull_request: bool) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
if let Some(session) = app.review.session().filter(|s| !s.findings.is_empty()) {
lines.push(feedback_heading(app, pull_request));
for finding in session.findings.iter().take(FOOT_COMMENTS) {
lines.push(feedback_row(app, finding, width));
}
let more = session.findings.len().saturating_sub(FOOT_COMMENTS);
if more > 0 {
let window = chord(app, luxe_core::keymap::UiAction::ReviewFindings, "alt+c");
lines.push(Line::from(vec![
Span::styled(format!(" +{more} more \u{b7} "), styles.dim),
Span::styled(window, styles.accent),
]));
}
}
lines
}
/// That the review went to GitHub and with what, then the key that posts what was written since,
/// or the one that opens it.
fn posted_next_action(app: &App, verdict: &str) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let posted =
Line::from(Span::styled(format!("Posted to GitHub \u{b7} {verdict}"), styles.success));
let unposted = unsent_comment_count(app);
let line = if unposted > 0 {
let finish = chord(app, luxe_core::keymap::UiAction::ReviewFinish, "alt+enter");
let what = match unposted {
1 => " to post your new comment".to_owned(),
count => format!(" to post your {count} new comments"),
};
vec![Span::styled(finish, styles.accent), Span::styled(what, styles.text)]
} else {
let open = chord(app, luxe_core::keymap::UiAction::ReviewOpenInBrowser, "o");
vec![Span::styled(open, styles.accent), Span::styled(" opens it", styles.text)]
};
vec![posted, Line::from(line)]
}
/// `All read`, and the key that finishes, named for what the finish dialog will offer.
fn walkthrough_next_action(app: &App, pull_request: bool) -> Line<'static> {
let styles = &app.theme_styles;
let finish = app
.keymap
.chords_for(luxe_core::keymap::UiAction::ReviewFinish)
.and_then(|chords| chords.first())
.map_or_else(|| "alt+enter".to_owned(), ToString::to_string);
// Named for what the dialog will offer, which is the one thing the key cannot say itself
let then = if pull_request {
" to post your review"
} else if crate::app::pull_request_opening_offered(app) {
" to open a pull request"
} else if crate::app::is_own_pull_request(app) {
" to answer on GitHub"
} else {
" to finish"
};
Line::from(vec![
Span::styled("All read · ", styles.success),
Span::styled(finish, styles.accent),
Span::styled(then, styles.text),
])
}
/// Why each folded hunk was folded, counted by class, once the reader asks with `d`.
fn folded_reason_rows(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
// Asked for with `d`, never volunteered: each folded row already names what it is
let (hidden_hunks, hidden_lines) = app.guided_review_workspace.hidden_counts(&review.files);
if hidden_hunks > 0 && app.guided_review_workspace.noise_details_visible {
lines.push(Line::from(Span::styled(
collapsed_banner(hidden_hunks, hidden_lines),
styles.dim,
)));
// Per-class counts, not a generic blurb: "why was *this* folded" is the question
for (label, count) in folded_reasons(app, review) {
lines.push(Line::from(Span::styled(format!(" {count} {label}"), styles.dim)));
}
lines.push(Line::from(Span::styled("Semantic and comment-only changes stay", styles.dim)));
lines.push(Line::from(Span::styled("d close", styles.dim)));
}
lines
}
/// The verdict a pull request's review went to GitHub with, as GitHub's page says it, once it has.
///
/// A pull request's outcome is recorded by the post landing and by nothing else, so having one is
/// what having posted means.
fn posted_verdict(
session: Option<&luxe_core::guided_review::ReviewSession>,
) -> Option<&'static str> {
use luxe_core::guided_review::ReviewOutcome;
Some(match session?.outcome? {
ReviewOutcome::Accepted => "approved",
ReviewOutcome::ChangesRequested => "changes requested",
ReviewOutcome::Commented => "commented",
})
}
/// Whether there is no walkthrough to step through, which the foot says in so many words.
fn walkthrough_is_empty(app: &App, review: &luxe_core::guided_review::GuidedReview) -> bool {
app.guided_review_workspace.walkthrough_step(review).is_none()
}
/// `FEEDBACK 3 · 2 unposted`, a section heading like the dock's, with the tally riding beside it.
fn feedback_heading(app: &App, pull_request: bool) -> Line<'static> {
let styles = &app.theme_styles;
let mut spans = if app.config.statusline.style() == luxe_core::config::StatuslineStyle::Flat {
vec![Span::styled("FEEDBACK", styles.accent.add_modifier(ratatui::style::Modifier::BOLD))]
} else {
let canvas = styles.tool_bg.bg.unwrap_or(styles.slab.canvas);
crate::widgets::badge("FEEDBACK", crate::theme::styles::Depth::Raised, canvas, styles)
};
let (tally, waiting) = match feedback_tally(app.review.session(), pull_request) {
Some(tally) => (tally, unsent_comment_count(app) > 0),
None => (String::new(), false),
};
spans.push(Span::styled(
format!(" {tally}"),
if waiting { styles.warning } else { styles.muted },
));
Line::from(spans)
}
/// One comment in the foot: its state, where it is, and how it starts.
///
/// No `R1` here. The label is how the agent names a comment back to you, and a list whose every row
/// is its own place needs no second name.
fn feedback_row(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
width: usize,
) -> Line<'static> {
use luxe_core::guided_review::FindingState;
let styles = &app.theme_styles;
let glyph_style = match finding.state {
_ if finding.posted.is_some() => styles.dim,
FindingState::Draft => styles.warning,
FindingState::Open | FindingState::NeedsVerification => styles.info,
FindingState::Resolved => styles.success,
FindingState::Stale => styles.dim,
};
let glyph = format!(" {} ", finding_state_glyph(finding));
let place = format!("{} ", feedback_place(app, &finding.anchor));
// The title the feedback window lists it by, or its first line when it was never given one
let first = finding.body.lines().map(str::trim).find(|line| !line.is_empty()).unwrap_or("");
let said = if finding.title.trim().is_empty() { first } else { finding.title.trim() };
let said = feedback_window::plain(said);
let budget = width.saturating_sub(glyph.width() + place.width());
Line::from(vec![
Span::styled(glyph, glyph_style),
Span::styled(place, styles.muted),
Span::styled(clip_terminal_cells_ellipsis(&said, budget), styles.text),
])
}
/// Where a comment sits, short enough for the rail: `notification.rs:13`, `on the review`.
fn feedback_place(app: &App, anchor: &luxe_core::guided_review::FindingAnchor) -> String {
use luxe_core::guided_review::FindingAnchor;
let name = |file_id: &luxe_core::guided_review::FileId| {
app.guided_review
.as_ref()
.and_then(|review| review.files.iter().find(|file| &file.id == file_id))
.and_then(|file| file.new_path.as_deref().or(file.old_path.as_deref()))
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().into_owned())
};
match anchor {
FindingAnchor::Line { file_id, line, .. } => {
name(file_id).map_or_else(|| format!("line {line}"), |name| format!("{name}:{line}"))
}
FindingAnchor::Hunk { file_id, .. } => name(file_id).unwrap_or_else(|| "a hunk".into()),
FindingAnchor::Chapter { .. } => "on the chapter".into(),
FindingAnchor::Review => "on the review".into(),
}
}
/// Comments written but not yet sent, which is the only finding count with a key attached to it.
///
/// A comment already on GitHub is sent, though it stays a draft locally, and a question on a pull
/// request stays with the agent: counting either kept the heading's warning lit over a review that
/// had gone out whole.
fn unsent_comment_count(app: &App) -> usize {
let pull_request = crate::app::github_post_is_pull_request(app);
app.review.session().map_or(0, |session| {
session
.findings
.iter()
.filter(|finding| {
finding.state == luxe_core::guided_review::FindingState::Draft
&& finding.posted.is_none()
&& !(pull_request
&& finding.severity == luxe_core::guided_review::FindingSeverity::Question)
})
.count()
})
}

View File

@@ -0,0 +1,430 @@
//! The guide pane — the walkthrough document, where its focus sits, and what its rows open.
use super::super::brief;
use super::super::overlays::chapter_kind_label;
use super::foot::guide_foot_lines;
use super::metadata::review_metadata_lines;
use crate::app::App;
use crate::workspace_layout::gutter_inset;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph, Wrap};
use ratatui::Frame;
/// Rows the guide spends on one chapter's files before the rest become a count.
///
/// A chapter can own forty files. The reader wants the shape of it and their own place in it, and
/// the count says the rest is there — stepping with `Ctrl+↑/↓` walks every one of them.
const MAX_CHAPTER_FILE_ROWS: usize = 6;
/// Rows the head and the foot claim, so the document knows what is left.
const GUIDE_HEAD_ROWS: u16 = 1;
/// Rows a review's title may take before it is cut with an ellipsis.
pub(super) const TITLE_ROWS: usize = 2;
/// Rows kept below what the guide follows when it has to scroll to reach it, so the file being
/// read is never the last thing on the pane.
const GUIDE_SELECTION_MARGIN: usize = 1;
/// The stretch of the guide document the pane keeps in view, in unwrapped lines.
struct GuideFocus {
/// The line the position is on: the hunk being read, else its file, else the chapter's title
at: usize,
/// The last line of the block it belongs to — the open file's last hunk row — so the list
/// `Space` steps through is on screen whole when it fits
through: usize,
}
/// The slice of files to show: `rows` of them, keeping the selection visible.
///
/// Beyond that it prefers to show what comes *after* the cursor, since that is where the reading
/// is going.
fn file_window(total: usize, selected: Option<usize>, rows: usize) -> (usize, usize) {
if total <= rows {
return (0, total);
}
let selected = selected.unwrap_or(0);
// One row of context behind the cursor, the rest ahead.
let start = selected.saturating_sub(1).min(total.saturating_sub(rows));
(start, start + rows)
}
/// Draws the guide pane: identity, the document, and what the review wants from the reader.
pub(in crate::view::guided_review) fn render_guide_pane(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
// Raised surface, inset off the divider, matching the Context Dock's presentation
let screen = frame.area();
frame.render_widget(Block::default().style(app.theme_styles.tool_bg), area);
let inner = gutter_inset(area, screen);
if inner.width == 0 || inner.height == 0 {
return;
}
let mut head = review_metadata_lines(app, review, inner.width);
let mut foot = guide_foot_lines(app, review, inner.width);
// A rule under the head and over the foot, so the part that scrolls reads as its own zone. Each
// takes the place of the blank row that would space them off, so it costs the document
// nothing
let head_rule = head.last().is_some_and(|line| line.width() == 0);
let foot_rule = foot.first().is_some_and(|line| line.width() == 0);
if head_rule {
head.pop();
}
if foot_rule {
foot.remove(0);
}
let (head_rule, foot_rule) = (u16::from(head_rule), u16::from(foot_rule));
let head_height = wrapped_height(&head, inner.width).min(inner.height);
let foot_height = wrapped_height(&foot, inner.width)
.min(inner.height.saturating_sub(head_height + head_rule + foot_rule));
let zones = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(head_height),
Constraint::Length(head_rule),
Constraint::Min(GUIDE_HEAD_ROWS),
Constraint::Length(foot_rule),
Constraint::Length(foot_height),
])
.split(inner);
let rule = |zone: Rect| {
Paragraph::new(Line::from(Span::styled(
"─".repeat(usize::from(zone.width)),
app.theme_styles.border_muted,
)))
};
frame.render_widget(Paragraph::new(head).wrap(Wrap { trim: false }), zones[0]);
// A zone with no rule in it has no height, so drawing it there draws nothing
frame.render_widget(rule(zones[1]), zones[1]);
render_guide_document(frame, zones[2], app, review);
frame.render_widget(rule(zones[3]), zones[3]);
if foot_height > 0 {
frame.render_widget(Paragraph::new(foot).wrap(Wrap { trim: false }), zones[4]);
}
}
/// Rows a block of lines occupies once wrapped to `width`.
fn wrapped_height(lines: &[Line<'static>], width: u16) -> u16 {
lines
.iter()
.map(|line| {
Paragraph::new(line.clone()).wrap(Wrap { trim: false }).line_count(width) as u16
})
.sum()
}
/// The document: the change's intent, then a block per chapter with its own prose and files.
///
/// Scrolls to keep the selection in view and holds no scroll state to do it. The offset is a
/// function of the position and the pane height, recomputed every frame, so there is nothing to
/// fall out of step with the cursor and nothing for a wheel to fight.
fn render_guide_document(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
if area.width == 0 || area.height == 0 {
return;
}
// The bar's lane is reserved whether or not it is drawn: appearing and disappearing as content
// crosses the viewport would reflow every line of prose beside it while the reader scrolled.
let text = Rect { width: area.width.saturating_sub(1), ..area };
if text.width == 0 {
return;
}
let width = usize::from(text.width);
let (lines, anchors, focus) = guide_document(app, review, width);
// Wrapped here rather than by the widget, so a rendered row and a document line mean the same
// thing — which is what lets the scroll offset count what the reader can see and a click land
// on the row under the pointer. One pass, recording where each line landed: measuring every
// height and then wrapping again did the same work twice on every frame.
let mut rows: Vec<Line<'static>> = Vec::with_capacity(lines.len() + lines.len() / 4);
let mut starts: Vec<usize> = Vec::with_capacity(lines.len() + 1);
for line in &lines {
starts.push(rows.len());
rows.extend(crate::widgets::wrap_line(line, width));
}
starts.push(rows.len());
let height = usize::from(area.height);
let total = rows.len();
let last = total.saturating_sub(height.min(total));
// Scroll only as far as it takes to keep the selection in view. Centering it instead would
// push the change's own intent off the top the moment a review opened, which is the one thing
// on this surface that has to be read first. A block taller than the pane gives way to the
// line the position is actually on.
let through = starts[focus.through + 1] + GUIDE_SELECTION_MARGIN;
let following = through.saturating_sub(height).min(starts[focus.at]).min(last);
let workspace = &app.guided_review_workspace;
// A cursor that has moved since the wheel was used takes the guide back: a pinned offset that
// outlived the reason it was pinned is a pane stuck somewhere nobody is looking.
let cursor = workspace.position.fingerprint();
if workspace.guide_scroll_anchor.get() != cursor {
workspace.guide_scroll.set(None);
workspace.guide_scroll_anchor.set(cursor);
}
let offset = match workspace.guide_scroll.get() {
Some(pinned) => {
let clamped = pinned.min(last);
workspace.guide_scroll.set(Some(clamped));
clamped
}
None => following,
};
workspace.guide_drawn_offset.set(offset);
workspace.guide_room.set(last);
{
let mut regions = app.hit.borrow_mut();
for anchor in &anchors {
let Some(visible) = starts[anchor.line].checked_sub(offset).filter(|row| *row < height)
else {
continue;
};
let row_height = starts[anchor.line + 1]
.saturating_sub(starts[anchor.line])
.max(1)
.min(height - visible);
regions.push(
Rect::new(text.x, text.y + visible as u16, text.width, row_height as u16),
anchor.target.clone(),
);
}
}
rows.drain(..offset.min(rows.len()));
rows.truncate(height);
frame.render_widget(Paragraph::new(rows), text);
crate::widgets::steered_scrollbar(
frame,
&mut app.hit.borrow_mut(),
Rect { x: area.x + area.width.saturating_sub(1), width: 1, ..area },
crate::mouse::ScrollRegionId::ReviewGuide,
offset,
total,
height,
&app.theme_styles,
);
}
/// A document row a click can land on.
struct GuideAnchor {
/// Index into the unwrapped document lines.
line: usize,
/// What clicking it means.
target: crate::mouse::MouseTarget,
}
/// The guide document's lines, the rows a pointer can act on, and what the pane follows.
///
/// It follows the most specific thing the position names, with the block around it. Following the
/// chapter's title alone let a chapter with a few paragraphs of prose walk its files off the bottom
/// of the pane while `Space` stepped through them.
fn guide_document(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
width: usize,
) -> (Vec<Line<'static>>, Vec<GuideAnchor>, GuideFocus) {
let mut doc = GuideDocument {
lines: brief::intent_lines(app, review, width),
anchors: Vec::new(),
focus: GuideFocus { at: 0, through: 0 },
};
let owners = brief::FileOwners::of(review);
for (index, chapter) in review.chapters.iter().enumerate() {
chapter_document(&mut doc, app, review, &owners, (index, chapter), width);
}
(doc.lines, doc.anchors, doc.focus)
}
/// The guide document as it is built: its lines, what its rows open, and where the reading is.
struct GuideDocument {
lines: Vec<Line<'static>>,
anchors: Vec<GuideAnchor>,
focus: GuideFocus,
}
/// One chapter's part of the guide: its number and kind, its title, then either the one line that
/// accounts for it or its rationale and its files.
fn chapter_document(
doc: &mut GuideDocument,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
owners: &brief::FileOwners<'_>,
(index, chapter): (usize, &luxe_core::guided_review::ReviewChapter),
width: usize,
) {
let styles = &app.theme_styles;
let lines = &mut doc.lines;
let current = app.guided_review_workspace.position.chapter_id.as_ref() == Some(&chapter.id);
let roll = app.review.budget.chapter(&chapter.id);
let accounted = roll.needs_review == 0;
lines.push(Line::from(vec![
Span::styled(format!("{:02} / {:02} ", index + 1, review.chapters.len()), styles.dim),
Span::styled(chapter_kind_label(chapter.kind).to_uppercase(), styles.dim),
Span::styled(
if app.guided_review_workspace.is_chapter_walked(&chapter.id) {
" reviewed"
} else {
""
},
styles.success,
),
]));
if current {
doc.focus = GuideFocus { at: lines.len(), through: lines.len() };
}
doc.anchors.push(GuideAnchor {
line: lines.len(),
target: crate::mouse::MouseTarget::ReviewGuideChapter(chapter.id.clone()),
});
lines.push(Line::from(vec![
Span::styled(if current { "\u{203a} " } else { " " }, styles.accent),
Span::styled(
chapter.title.clone(),
if accounted {
styles.muted
} else if current {
styles.accent.add_modifier(ratatui::style::Modifier::BOLD)
} else {
styles.accent
},
),
]));
// An accounted-for chapter recedes to one line and says what accounts for it. It is still
// reachable — `]` steps into it like any other — it just does not spend the page.
if accounted {
lines.push(Line::from(Span::styled(
format!(" {}", chapter_accounted_label(app, review, chapter)),
styles.dim,
)));
lines.push(Line::default());
return;
}
lines.extend(brief::prose_lines(&chapter.rationale, app, width, " "));
if let Some(impact) = chapter.impact.as_deref() {
lines.extend(brief::prose_lines(impact, app, width, " \u{2192} "));
}
lines.push(Line::default());
chapter_file_rows(doc, app, &owners.chapter_files(chapter), current, width);
doc.lines.push(Line::default());
}
/// A chapter's files, windowed to [`MAX_CHAPTER_FILE_ROWS`] around the one being read, which
/// opens to its hunks.
fn chapter_file_rows(
doc: &mut GuideDocument,
app: &App,
files: &[&luxe_core::guided_review::ReviewFile],
current: bool,
width: usize,
) {
let styles = &app.theme_styles;
let lines = &mut doc.lines;
let selected_file = app.guided_review_workspace.position.file_id.as_ref();
let selected_index =
current.then(|| files.iter().position(|file| Some(&file.id) == selected_file)).flatten();
let (start, end) = file_window(files.len(), selected_index, MAX_CHAPTER_FILE_ROWS);
if start > 0 {
lines.push(Line::from(Span::styled(format!(" \u{2026} {start} above"), styles.dim)));
}
for (position, file) in files.iter().enumerate().take(end).skip(start) {
let open = current && selected_index == Some(position);
doc.anchors.push(GuideAnchor {
line: lines.len(),
target: crate::mouse::MouseTarget::ReviewGuideFile(file.id.clone()),
});
let file_line = lines.len();
lines.push(brief::file_line(app, file, open, width));
if !open {
continue;
}
// Only the file being read opens to its hunks. That is what makes stepping legible:
// the mark moves down a list you can see, on every press.
let (rows, active) = hunk_rows(app, file, width);
doc.focus = GuideFocus {
at: active.map_or(file_line, |active| file_line + 1 + active),
through: file_line + rows.len(),
};
lines.extend(rows);
}
if end < files.len() {
lines.push(Line::from(Span::styled(
format!(" \u{2026} {} more", files.len() - end),
styles.dim,
)));
}
}
/// One row per hunk in the file being read, with the active one marked, and which row that is.
fn hunk_rows(
app: &App,
file: &luxe_core::guided_review::ReviewFile,
width: usize,
) -> (Vec<Line<'static>>, Option<usize>) {
let styles = &app.theme_styles;
let active = app.guided_review_workspace.position.hunk_id.as_ref();
let shown: Vec<&luxe_core::guided_review::ReviewHunk> = file
.hunks
.iter()
.filter(|hunk| !app.guided_review_workspace.is_hunk_hidden(file, hunk))
.collect();
let at = shown.iter().position(|hunk| active == Some(&hunk.id));
let rows = shown
.into_iter()
.map(|hunk| {
let current = active == Some(&hunk.id);
let label = hunk
.symbol
.as_ref()
.and_then(|symbol| symbol.name.clone())
.or_else(|| hunk.heading.clone())
.unwrap_or_else(|| format!("line {}", hunk.new_range.start));
Line::from(vec![
Span::styled(if current { " \u{2503} " } else { " " }, styles.accent),
Span::styled(
crate::guided_review::diff::clip_terminal_cells_ellipsis(
&label,
width.saturating_sub(8),
),
if current { styles.text.patch(styles.selected_bg) } else { styles.muted },
),
])
})
.collect();
(rows, at)
}
/// What accounts for a chapter nothing in which needs the reviewer.
fn chapter_accounted_label(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
chapter: &luxe_core::guided_review::ReviewChapter,
) -> String {
use luxe_core::guided_review::{ItemVerdict, ReviewItemRef};
let mut reason: Option<luxe_core::guided_review::Accounted> = None;
for item in &chapter.items {
let verdict = match item {
ReviewItemRef::Hunk(hunk_id) => app.review.budget.hunk_verdict(hunk_id),
ReviewItemRef::File(_) => app.review.budget.verdict(item),
};
let ItemVerdict::Accounted(accounted) = verdict else {
return "nothing here needs you".into();
};
match &reason {
Some(seen) if *seen != accounted => return "nothing here needs you".into(),
_ => reason = Some(accounted),
}
}
let _ = review;
reason.map_or_else(
|| "nothing here needs you".into(),
|accounted| format!("{} \u{2014} nothing here needs you", accounted.label()),
)
}

View File

@@ -0,0 +1,240 @@
//! Review metadata — the review's heading and the metadata rows under it, wide, medium and narrow.
use super::super::{brief, review_label};
use super::guide::TITLE_ROWS;
use super::summary::{
chapter_progress_summary, checks_label, feedback_summary, hidden_noise_summary,
review_activity_status, review_outcome_label, review_stats_summary, review_summary,
stale_revision_label,
};
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
/// The review title, falling back to a stable label when the source carries none.
pub(super) fn review_title(review: &luxe_core::guided_review::GuidedReview) -> &str {
let title = review.context.title.trim();
if title.is_empty() {
"Guided Review"
} else {
review.context.title.as_str()
}
}
/// A one-line metadata summary (source · workload · judgements · counts) for the compact
/// medium/narrow headers that have no room for the full guide pane.
pub(super) fn review_metadata_summary(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> String {
// Ordered by what must survive clipping on a narrow tier: identity and workload, then the
// judgements (outcome, verification, staleness), and only then the counts. The order was
// already documented this way and already wrong — the feedback roll-up sat third, so a longer
// one pushed the recorded outcome off the end of the row.
let mut parts = vec![review_label(review), review_summary(app)];
if let Some(outcome) = review_outcome_label(app.review.session()) {
parts.push(format!("Outcome: {outcome}"));
}
if let Some(stale) = stale_revision_label(app, review) {
parts.push(stale);
}
if let Some((_, checks)) = checks_label(review) {
parts.push(checks);
}
parts
.push(feedback_summary(app.review.session(), crate::app::github_post_is_pull_request(app)));
if let Some(chapters) = chapter_progress_summary(app, review) {
parts.push(chapters);
}
parts.push(review_stats_summary(review));
parts.join(" · ")
}
/// The rail's own heading, cut from the same ramp as the dock's.
///
/// This rail and the Context Dock are the same column at the same screen position —
/// `LEFT_RAIL_WIDTH == CONTEXT_DOCK_WIDTH` so the divider never jumps moving chat↔review — so the
/// heading over it has to be the same object. `Hero`, because REVIEW anchors this surface the way
/// PROJECT anchors the dock. `statusline.style = "flat"` flattens it with everything else.
fn review_heading_spans(app: &App) -> Vec<Span<'static>> {
let styles = &app.theme_styles;
if app.config.statusline.style() == luxe_core::config::StatuslineStyle::Flat {
return vec![Span::styled(
"REVIEW",
styles.accent.add_modifier(ratatui::style::Modifier::BOLD),
)];
}
let canvas = styles.background.bg.unwrap_or(styles.slab.canvas);
crate::widgets::badge("REVIEW", crate::theme::styles::Depth::Hero, canvas, styles)
}
/// `REVIEW` on the left and `Step 3 of 7` on the right: where you are, in the place the peek pane
/// puts its own `2 of 5`, rather than at the foot beside a ribbon of cells, which would spend a row
/// saying a number twice.
fn review_heading_line(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
width: u16,
) -> Line<'static> {
let mut spans = review_heading_spans(app);
if let Some((at, total)) = app.guided_review_workspace.walkthrough_step(review) {
let step = format!("Step {at} of {total}");
let used: usize = spans.iter().map(|span| span.content.width()).sum();
if used + step.width() < usize::from(width) {
spans.push(Span::raw(" ".repeat(usize::from(width) - used - step.width())));
spans.push(Span::styled(step, app.theme_styles.muted));
}
}
Line::from(spans)
}
/// The guide pane's head: what is being read, and nothing about what it asks for.
///
/// Identity and scale only. The counts a reviewer glances down for — workload, chapters walked,
/// comments outstanding — are in the foot, so the two questions have one place each instead of a
/// column of numbers at the top that has to be re-read to find the one that changed.
pub(super) fn review_metadata_lines(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
width: u16,
) -> Vec<Line<'static>> {
let mut lines = vec![
Line::default(), // 1-cell top pad
review_heading_line(app, review, width),
// Two lines and then an ellipsis. A review's title is usually the session's first message,
// which is a paragraph as often as it is a name — left to wrap it took four lines off the
// top of the guide and still ended mid-word, which reads as a rendering fault rather than
// as a long title.
Line::from(Span::styled(
clip_terminal_cells_ellipsis(
review_title(review),
usize::from(width).saturating_mul(TITLE_ROWS),
),
app.theme_styles.text,
)),
Line::from(Span::styled(
format!("{} · {}", review_label(review), review_stats_summary(review)),
app.theme_styles.muted,
)),
];
if let Some(pr) = review.context.pull_request.as_ref() {
lines.extend(brief::pull_request_facts(app, pr, usize::from(width)));
}
lines.extend(guide_state_lines(app));
if let Some(status) = review_activity_status(app) {
// Spun, with the live tool beside it: after a submission a silent review gives no sign the
// agent is doing anything, which is when a reviewer starts pressing keys.
let mut spans = vec![
Span::styled(
format!("{} ", crate::statusline::spinner(app.guided_review_workspace.frame)),
app.theme_styles.accent,
),
Span::styled(status, app.theme_styles.accent),
];
if let Some(tool) = app.status.active_tool.as_deref() {
spans.push(Span::styled(format!(" {tool}"), app.theme_styles.muted));
}
// Through the status model rather than off `turn_started`, so a turn blocked on a prompt
// reports the same figure here as it does above the composer.
if let Some(elapsed) = app.status.elapsed(app.frame_now()) {
spans.push(Span::styled(
format!(" {}", crate::statusline::format_elapsed_compact(elapsed)),
app.theme_styles.dim,
));
}
lines.push(Line::from(spans));
}
if let Some(stale) = stale_revision_label(app, review) {
lines.push(Line::from(Span::styled(stale, app.theme_styles.warning)));
}
// What the review will not say unless it is told to. Silent whenever there is nothing wrong,
// which is most of the time.
lines.extend(brief::notice_lines(app, review));
lines.push(Line::default());
lines
}
/// How the visible chapters were produced, when that is worth saying. A review opens on
/// deterministic sections and upgrades in place, so silence here means the model wrote them.
///
/// There is no waiting case. The guide pass takes tens of seconds on a local model and every
/// heading, sentence and per-file note on this surface arrives with it, so opening on a structural
/// placeholder would rewrite itself under the reader. The surface opens only once the guide has
/// landed, and the waiting is announced in the tray above the composer, which is where the reader
/// is while it happens and which does not need a whole screen to say one line.
fn guide_state_lines(app: &App) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let Some(provenance) = app.review.provenance.as_ref() else {
return Vec::new();
};
provenance
.label()
.map(|label| vec![Line::from(Span::styled(label, styles.muted))])
.unwrap_or_default()
}
/// The medium tier's stacked context block, shared with the layout so its reserved height matches
/// what it renders.
pub(in crate::view::guided_review) fn medium_context_lines(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Vec<Line<'static>> {
let chapter_index = app
.guided_review_workspace
.position
.chapter_id
.as_ref()
.and_then(|id| review.chapters.iter().position(|chapter| &chapter.id == id))
.unwrap_or_default();
let chapter = review.chapters.get(chapter_index);
let file = app
.guided_review_workspace
.position
.file_id
.as_ref()
.and_then(|id| review.files.iter().find(|file| &file.id == id));
let mut lines = vec![
Line::default(), // top pad
Line::from(Span::styled(
review_title(review).to_string(),
app.theme_styles.accent.add_modifier(ratatui::style::Modifier::BOLD),
)),
Line::from(Span::styled(review_metadata_summary(app, review), app.theme_styles.muted)),
Line::from(Span::styled(
format!("{:02} / {:02}", chapter_index + 1, review.chapters.len().max(1)),
app.theme_styles.muted,
)),
];
if let Some(chapter) = chapter {
lines.push(Line::from(Span::styled(chapter.title.clone(), app.theme_styles.text)));
lines.push(Line::from(Span::styled(chapter.rationale.clone(), app.theme_styles.muted)));
}
if let Some(file) = file {
let path = file
.new_path
.as_deref()
.or(file.old_path.as_deref())
.map_or_else(|| "(unknown path)".into(), |path| path.display().to_string());
lines.push(Line::from(Span::styled(
format!(
"› {path} +{} −{}",
file.additions.unwrap_or_default(),
file.deletions.unwrap_or_default()
),
app.theme_styles.muted,
)));
}
if let Some(summary) = hidden_noise_summary(app, review) {
let detail = if app.guided_review_workspace.noise_details_visible {
let (hunks, lines) = app.guided_review_workspace.hidden_counts(&review.files);
format!(
"{hunks}/{lines} folded: format/generated/lockfile/mechanical; semantic/comments kept · d close"
)
} else {
summary
};
lines.push(Line::from(Span::styled(detail, app.theme_styles.muted)));
}
lines
}

View File

@@ -0,0 +1,382 @@
//! Review summaries — the short strings about the source, its checks, progress, staleness, the
//! agent's work and the feedback tally.
use super::plural;
use crate::app::App;
use crate::guided_review::GuidedReviewLoadState;
/// The `Checks …` label for a review carrying real gate results, or `None`.
///
/// Only genuine review-gate results reach here. Promoting every shell command to a check and every
/// non-zero exit to a failure would turn a `grep` that matched nothing red and report a healthy
/// session as broken. The harness cannot know what an exit code meant, so it does not guess: an
/// interactive review has no gate results and says nothing, and what verification actually happened
/// is described in the Brief by the narrator, which can see the whole turn.
pub(super) fn checks_label(
review: &luxe_core::guided_review::GuidedReview,
) -> Option<(ChecksTone, String)> {
use luxe_core::guided_review::ReviewCheckStatus;
let checks = &review.checks.checks;
if checks.is_empty() {
return None;
}
Some(if checks.iter().any(|check| matches!(check.status, ReviewCheckStatus::Failed)) {
(ChecksTone::Failed, "Checks failed".to_string())
} else if checks.iter().any(|check| matches!(check.status, ReviewCheckStatus::Pending)) {
(ChecksTone::Unsettled, "Checks pending".to_string())
} else if checks.iter().any(|check| matches!(check.status, ReviewCheckStatus::Unavailable)) {
// A run that predates the final edit is the only thing that lands here today.
(ChecksTone::Unsettled, "Verified before the last edit".to_string())
} else {
(ChecksTone::Passed, format!("Checks {}", crate::glyphs::Mark::Yes))
})
}
/// How the checks line should read, decided with the status rather than re-derived from the words.
///
/// Matching the rendered label to pick a color would turn the passing line amber the moment its
/// tick became a themed glyph.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ChecksTone {
Passed,
Failed,
Unsettled,
}
/// The `{n} files · +a −d · {n} hunks` change-size summary for the review.
///
/// The hunk count joined it when the overview's own "Scale" section went: that section restated
/// this line and added the one figure it was missing.
pub(super) fn review_stats_summary(review: &luxe_core::guided_review::GuidedReview) -> String {
let mut stats = format!(
"{} {}",
review.stats.files,
if review.stats.files == 1 { "file" } else { "files" }
);
if let (Some(additions), Some(deletions)) = (review.stats.additions, review.stats.deletions) {
stats.push_str(&format!(" · +{additions} −{deletions}"));
}
if review.stats.hunks > 0 {
stats.push_str(&format!(
" · {} {}",
review.stats.hunks,
if review.stats.hunks == 1 { "hunk" } else { "hunks" }
));
}
stats
}
/// The in-flight status for the sidebar, or `None` when the review is settled.
///
/// Owned as a `String` so an active remediation can name the comments it is addressing: after
/// submitting, a silent review gives no sign the agent is working at all.
pub(super) fn review_activity_status(app: &App) -> Option<String> {
if let Some(working) = agent_working_label(app) {
return Some(working);
}
if app.review_edit_pending(|purpose| *purpose == crate::app::ReviewEditPurpose::Send) {
Some("Saving feedback snapshot".into())
} else if app.review_edit_pending(|_| true) {
Some("Saving review".into())
} else {
// Kept short enough to fit the 40-cell rail on one line (no mid-phrase wrap).
match app.guided_review_workspace.load_state {
GuidedReviewLoadState::Loading { .. } => Some("Refreshing · revision retained".into()),
GuidedReviewLoadState::Failed { .. } => {
Some("Refresh failed · revision retained".into())
}
GuidedReviewLoadState::Idle | GuidedReviewLoadState::Ready => None,
}
}
}
/// Whether the working tree has moved on from the revision the reviewer is reading.
///
/// A pinned review is a feature, not a bug — but reading a diff that no longer matches the files
/// without being told is how a reviewer signs off on code that has since changed underneath them.
pub(super) fn stale_revision_label(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Option<String> {
// Checked first, and for any target, because the path comparison below cannot see it: a fix
// nearly always edits a file the review already holds, which leaves the set of paths as it was
if let Some(addressed) = app
.review
.session()
.and_then(|session| fixes_returned_label(session, &review.source.content_digest))
{
return Some(addressed);
}
if review.target != luxe_core::guided_review::ReviewTarget::WorkingTree {
return None;
}
let changes = &app.workspace.as_ref()?.changes;
// A bounded list cannot be compared honestly, and neither can raw counts: Git collapses an
// untracked directory into one dock entry while the review expands it into its files, so
// `19 != 8` was permanently true and the warning permanently on. Paths compare; counts do not.
if changes.truncated {
return None;
}
let reviewed: Vec<String> = review
.files
.iter()
.filter_map(|file| file.new_path.as_deref().or(file.old_path.as_deref()))
.map(|path| path.display().to_string())
.collect();
let entries: Vec<String> =
changes.files.iter().map(|entry| entry.path.display().to_string()).collect();
let covers = |entry: &str, path: &str| {
entry == path || (entry.ends_with('/') && path.starts_with(entry))
};
let moved = !reviewed.iter().all(|path| entries.iter().any(|entry| covers(entry, path)))
|| !entries.iter().all(|entry| reviewed.iter().any(|path| covers(entry, path)));
moved.then_some("Workspace changed · ctrl+r refresh".to_owned())
}
/// `Fixes for 2 comments are in · Ctrl+R refresh` once fixes asked for from this revision have
/// come back: the diff on screen is from before them, and verifying a fix against it would sign
/// off on code that is no longer there. A refresh captures a new revision, which no submission
/// names yet.
pub(super) fn fixes_returned_label(
session: &luxe_core::guided_review::ReviewSession,
revision: &luxe_core::guided_review::ReviewRevisionId,
) -> Option<String> {
use luxe_core::guided_review::{ReviewFeedbackMode, SubmissionDispatch};
let fixed: usize = session
.submissions
.iter()
.filter(|submission| {
&submission.revision_id == revision
&& submission.mode == ReviewFeedbackMode::RequestFixes
&& submission.dispatch == SubmissionDispatch::Completed
})
.map(|submission| submission.findings.len())
.sum();
match fixed {
0 => None,
1 => Some("The fix is in · ctrl+r refresh".to_owned()),
n => Some(format!("Fixes for {n} comments are in · ctrl+r refresh")),
}
}
/// `Agent working on 2 comments`, or `Agent answering your question`, while a dispatched
/// submission is still being worked.
fn agent_working_label(app: &App) -> Option<String> {
use luxe_core::guided_review::{ReviewFeedbackMode, SubmissionDispatch};
let session = app.review.session()?;
let dispatched: Vec<_> = session
.submissions
.iter()
.filter(|submission| submission.dispatch == SubmissionDispatch::Dispatched)
.collect();
let comments: usize = dispatched.iter().map(|submission| submission.findings.len()).sum();
let asking =
dispatched.iter().all(|submission| submission.mode == ReviewFeedbackMode::Question);
match (comments, asking) {
(0, _) => None,
(1, true) => Some("Agent answering your question".to_owned()),
(n, true) => Some(format!("Agent answering {n} questions")),
(1, false) => Some("Agent working on your comment".to_owned()),
(n, false) => Some(format!("Agent working on {n} comments")),
}
}
/// What the review asks of the reviewer: `14 to judge` / `all accounted for`.
///
/// Deliberately not a completion ratio. `Reviewed 0/92` framed review as an inspection with a target
/// nobody can hit on an agent-scale change, and made reading the core sections closely and judging
/// the rest look like failure.
pub(super) fn review_summary(app: &App) -> String {
let budget = &app.review.budget;
if budget.total() == 0 {
return "Nothing to review".into();
}
if budget.needs_review == 0 {
return "All accounted for".into();
}
// The accounted-for tail rides here rather than in a block of its own: what each exclusion is
// *for* is printed on the hunk header and the file row it accounts for, so the only thing left
// to say at review scale is how much of the change it covers.
let mut summary = format!("{} to review", budget.needs_review);
if budget.accounted > 0 {
summary.push_str(&format!(" · {} accounted for", budget.accounted));
}
summary
}
/// `Chapters 2/7` — the only progress the review keeps.
pub(super) fn chapter_progress_summary(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Option<String> {
let (walked, total) = app.guided_review_workspace.chapters_walked(review);
(total > 0).then(|| format!("Chapters {walked}/{total}"))
}
/// Whether `finding` went in a send the agent has not finished: queued, or its turn running.
///
/// Sent is not the same thing. Once its turn is over a comment is back with the reader, to verify
/// or to read, whatever its state says.
pub(in crate::view::guided_review) fn with_the_agent(
session: &luxe_core::guided_review::ReviewSession,
finding: &luxe_core::guided_review::FindingId,
) -> bool {
use luxe_core::guided_review::SubmissionDispatch;
session.submissions.iter().any(|submission| {
matches!(submission.dispatch, SubmissionDispatch::Queued | SubmissionDispatch::Dispatched)
&& submission.findings.iter().any(|sent| &sent.finding_id == finding)
})
}
pub(in crate::view::guided_review) fn submission_dispatch_label(
dispatch: luxe_core::guided_review::SubmissionDispatch,
) -> &'static str {
match dispatch {
luxe_core::guided_review::SubmissionDispatch::Queued => "queued",
luxe_core::guided_review::SubmissionDispatch::Dispatched => "dispatched",
luxe_core::guided_review::SubmissionDispatch::FailedRetryable => "retry available",
luxe_core::guided_review::SubmissionDispatch::Completed => "completed",
}
}
pub(super) fn review_outcome_label(
session: Option<&luxe_core::guided_review::ReviewSession>,
) -> Option<&'static str> {
match session.and_then(|session| session.outcome) {
Some(luxe_core::guided_review::ReviewOutcome::Accepted) => Some("accepted"),
Some(luxe_core::guided_review::ReviewOutcome::ChangesRequested) => {
Some("changes requested")
}
Some(luxe_core::guided_review::ReviewOutcome::Commented) => Some("commented"),
None => None,
}
}
/// The `Feedback N · M unsent` roll-up shown beside the review, or an empty state.
///
/// *Feedback*, not *findings*: a question and a comment are the same artifact here — text anchored
/// to a place, with a severity saying what it asks for — and "finding" is inspection language on a
/// surface that spent a whole pass leaving the inspection frame behind. The unit is a comment, the
/// collective is feedback. The durable type stays `ReviewFinding` and the binding stays
/// `tui.review.findings`, because both are written down where a rename breaks something: a session
/// file on disk, and a keymap someone has already edited.
pub(super) fn feedback_summary(
session: Option<&luxe_core::guided_review::ReviewSession>,
pull_request: bool,
) -> String {
feedback_tally(session, pull_request)
.map_or_else(|| "No feedback yet".into(), |tally| format!("Feedback {tally}"))
}
/// `3 · 2 unposted`: how many comments, and the one thing the most urgent of them is waiting on.
/// `None` with nothing written.
pub(super) fn feedback_tally(
session: Option<&luxe_core::guided_review::ReviewSession>,
pull_request: bool,
) -> Option<String> {
use luxe_core::guided_review::FindingState;
let session = session.filter(|session| !session.findings.is_empty())?;
let total = session.findings.len();
let count = |predicate: fn(&&luxe_core::guided_review::ReviewFinding) -> bool| {
session.findings.iter().filter(predicate).count()
};
let unsent = session
.findings
.iter()
.filter(|finding| finding.state == FindingState::Draft && finding.posted.is_none())
// A question on a pull request stays with the agent, so it is not waiting to be posted
.filter(|finding| {
!pull_request || finding.severity != luxe_core::guided_review::FindingSeverity::Question
})
.count();
let posted = count(|finding| finding.posted.is_some());
let sent = |finding: &&luxe_core::guided_review::ReviewFinding| {
matches!(finding.state, FindingState::Open | FindingState::NeedsVerification)
&& finding.posted.is_none()
};
let (waiting, back): (Vec<_>, Vec<_>) = session
.findings
.iter()
.filter(sent)
.partition(|finding| with_the_agent(session, &finding.id));
let to_verify =
back.iter().filter(|finding| finding.state == FindingState::NeedsVerification).count();
// Open and back from the agent: it answered, said it could not, or Luxe said it said nothing
let to_read = back
.iter()
.filter(|finding| finding.state == FindingState::Open)
.filter(|finding| {
finding.thread.last().is_some_and(|message| {
message.author != luxe_core::guided_review::FindingMessageAuthor::Reviewer
})
})
.count();
// Unsent leads: a count of what you have written that does not say none of it has left is the
// wrong half of the fact. The keys that send it are the footer's, not repeated here.
let tail = if unsent > 0 && pull_request {
format!(" \u{b7} {unsent} unposted")
} else if unsent > 0 {
format!(" \u{b7} {unsent} unsent")
} else if posted > 0 {
format!(" \u{b7} {posted} on GitHub")
} else if !waiting.is_empty() {
format!(" \u{b7} {} with the agent", waiting.len())
} else if to_verify > 0 {
format!(" \u{b7} {to_verify} to verify")
} else if to_read > 0 {
format!(" \u{b7} {to_read} to read")
} else {
String::new()
};
Some(format!("{total}{tail}"))
}
/// The stacked tiers' one-line version, which carries its own affordance because it has no room
/// for a separate hint row.
pub(super) fn hidden_noise_summary(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Option<String> {
let (hunks, lines) = app.guided_review_workspace.hidden_counts(&review.files);
(hunks > 0).then(|| format!("{} · f opens them", collapsed_banner(hunks, lines)))
}
/// The collapsed count: `12 mechanical changes collapsed · 148 lines`.
///
/// Nothing is withheld — each one is a row in the diff that says what it stands for, and `f` opens
/// every one of them at once.
pub(super) fn collapsed_banner(hunks: usize, lines: usize) -> String {
format!(
"{} collapsed · {}",
plural(hunks, "mechanical change", "mechanical changes"),
plural(lines, "line", "lines"),
)
}
/// Folded hunks grouped by *what accounts for them*, most numerous first.
pub(super) fn folded_reasons(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) -> Vec<(&'static str, usize)> {
use luxe_core::guided_review::NoiseKind;
let mut counts: std::collections::BTreeMap<&'static str, usize> =
std::collections::BTreeMap::new();
for (_, hunk) in review
.files
.iter()
.flat_map(|file| file.hunks.iter().map(move |hunk| (file, hunk)))
.filter(|(file, hunk)| app.guided_review_workspace.is_hunk_hidden(file, hunk))
{
let label = match hunk.noise {
NoiseKind::FormattingOnly => "whitespace-only, tokens identical",
NoiseKind::Generated => "generated file",
NoiseKind::Lockfile => "lockfile",
NoiseKind::Mechanical => "mechanical rename or move",
NoiseKind::CommentOnly | NoiseKind::Semantic | NoiseKind::Unknown => continue,
};
*counts.entry(label).or_default() += 1;
}
let mut reasons: Vec<(&'static str, usize)> = counts.into_iter().collect();
reasons.sort_by(|left, right| right.1.cmp(&left.1).then(left.0.cmp(right.0)));
reasons
}

View File

@@ -0,0 +1,175 @@
use super::summary::{collapsed_banner, feedback_summary, fixes_returned_label};
/// Fixes asked for from the revision on screen, once their turn has ended, say the diff is from
/// before them. A question's answer changes no code, a turn still working has not come back, and
/// a refreshed revision is one no submission names.
#[test]
fn fixes_that_came_back_say_the_diff_is_from_before_them() {
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{
ReviewFeedbackMode, ReviewRevisionId, SubmissionDispatch, SubmissionId,
};
let app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
let mut session = app.review.session.clone().expect("session");
let revision = session.source.content_digest.clone();
let ids: Vec<_> = session.findings.iter().take(2).map(|finding| finding.id.clone()).collect();
let files = app.guided_review.as_ref().expect("review").files.clone();
session
.queue_submission(SubmissionId::new(), ReviewFeedbackMode::RequestFixes, &ids, &files, 7)
.expect("queued");
let mut with = |dispatch, mode| {
let submission = session.submissions.last_mut().expect("submission");
submission.dispatch = dispatch;
submission.mode = mode;
fixes_returned_label(&session, &revision)
};
assert_eq!(with(SubmissionDispatch::Dispatched, ReviewFeedbackMode::RequestFixes), None);
assert_eq!(with(SubmissionDispatch::Completed, ReviewFeedbackMode::Question), None);
let label = with(SubmissionDispatch::Completed, ReviewFeedbackMode::RequestFixes);
assert_eq!(label.as_deref(), Some("Fixes for 2 comments are in · ctrl+r refresh"));
let refreshed = ReviewRevisionId::from_canonical_bytes(b"after the fixes");
assert_eq!(fixes_returned_label(&session, &refreshed), None);
}
/// Once a pull request's review has gone to GitHub the foot says so, with the verdict, in the
/// place that offered to post it. The toast saying so is gone in seconds, and a foot still
/// offering to post left the reader unsure whether anything had gone at all.
#[test]
fn the_guide_foot_says_a_posted_review_went_out() {
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{FindingState, PostedComment, ReviewOutcome};
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture");
app.guided_review_workspace.github_post = None;
let review = app.guided_review.clone().expect("review");
app.guided_review_workspace.walked_chapters =
review.chapters.iter().map(|chapter| chapter.id.clone()).collect();
let foot = |app: &crate::app::App| {
super::foot::guide_foot_lines(app, &review, 60)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n")
};
let before = foot(&app);
assert!(before.contains("to post your review"), "{before}");
let session = app.review.session_mut().expect("session");
session.outcome = Some(ReviewOutcome::Accepted);
for finding in &mut session.findings {
finding.state = FindingState::Draft;
finding.posted =
Some(PostedComment { review_id: 9, url: "https://github.com/a/b/pull/1".into() });
}
let after = foot(&app);
assert!(after.contains("Posted to GitHub · approved"), "{after}");
assert!(after.contains("opens it"), "and where to read it: {after}");
assert!(!after.contains("to post your review"), "no longer offered: {after}");
assert!(!after.contains("Outcome:"), "the posted line says the verdict: {after}");
// A comment written after the post is what the key offers next
let session = app.review.session_mut().expect("session");
session.findings[0].posted = None;
session.findings[0].severity = luxe_core::guided_review::FindingSeverity::Suggestion;
let more = foot(&app);
assert!(more.contains("to post your new comment"), "{more}");
}
/// The guide foot says what the feedback wants next: unsent first, then posted, then with the
/// agent, then back with the reader to verify or to read. A posted comment is neither unsent
/// nor waiting, a question on a pull request stays with the agent rather than waiting to be
/// posted, and a comment is with the agent only while its send is queued or running.
#[test]
fn the_guide_foot_counts_what_the_feedback_wants_next() {
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{
FindingMessage, FindingMessageAuthor, FindingSeverity, FindingState, PostedComment,
ReviewFeedbackMode, SubmissionDispatch, SubmissionId,
};
let app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
// R1 open · R2 to verify · R3 draft · R4 verified · R5 stale
let base = app.review.session.clone().expect("session");
let summary = |edit: &dyn Fn(&mut luxe_core::guided_review::ReviewSession), pr: bool| {
let mut session = base.clone();
edit(&mut session);
feedback_summary(Some(&session), pr)
};
let posted =
|| Some(PostedComment { review_id: 1, url: "https://github.com/a/b/pull/1".into() });
let settle = |session: &mut luxe_core::guided_review::ReviewSession| {
for finding in &mut session.findings {
finding.state = FindingState::Resolved;
}
};
assert_eq!(summary(&|_| {}, false), "Feedback 5 · 1 unsent");
assert_eq!(summary(&|_| {}, true), "Feedback 5 · 1 unposted");
assert_eq!(
summary(&|session| session.findings[2].severity = FindingSeverity::Question, true),
"Feedback 5 · 1 to verify",
"a question on a pull request is not waiting to be posted"
);
assert_eq!(
summary(&|session| session.findings[2].posted = posted(), false),
"Feedback 5 · 1 on GitHub",
"a posted draft is not unsent"
);
let drafted = |session: &mut luxe_core::guided_review::ReviewSession| {
session.findings[2].state = FindingState::Resolved;
};
assert_eq!(summary(&drafted, false), "Feedback 5 · 1 to verify", "sent is not with the agent");
let sending = |session: &mut luxe_core::guided_review::ReviewSession,
dispatch: SubmissionDispatch| {
drafted(session);
let ids = [session.findings[0].id.clone(), session.findings[1].id.clone()];
let submission = SubmissionId::new();
session
.queue_submission(submission.clone(), ReviewFeedbackMode::RequestFixes, &ids, &[], 0)
.expect("queued");
session.submissions.last_mut().expect("the send").dispatch = dispatch;
};
for dispatch in [SubmissionDispatch::Queued, SubmissionDispatch::Dispatched] {
assert_eq!(
summary(&|session| sending(session, dispatch), false),
"Feedback 5 · 2 with the agent",
"{dispatch:?}"
);
}
assert_eq!(
summary(&|session| sending(session, SubmissionDispatch::Completed), false),
"Feedback 5 · 1 to verify",
"a finished send is back with the reader"
);
let replied = |session: &mut luxe_core::guided_review::ReviewSession| {
drafted(session);
session.findings[1].state = FindingState::Resolved;
session.findings[0].thread.push(FindingMessage {
author: FindingMessageAuthor::System,
body: "No word from the agent on this comment: it wrote no report.".into(),
created_at_ms: 1,
});
};
assert_eq!(summary(&replied, false), "Feedback 5 · 1 to read");
assert_eq!(
summary(
&|session| {
settle(session);
session.findings[0].state = FindingState::Open;
session.findings[0].posted = posted();
},
false
),
"Feedback 5 · 1 on GitHub",
"a posted comment is not with the agent"
);
assert_eq!(summary(&settle, true), "Feedback 5");
assert_eq!(feedback_summary(None, false), "No feedback yet");
}
#[test]
fn collapsed_banner_pluralizes_changes_and_lines() {
assert_eq!(collapsed_banner(1, 1), "1 mechanical change collapsed · 1 line");
assert_eq!(collapsed_banner(3, 12), "3 mechanical changes collapsed · 12 lines");
assert_eq!(collapsed_banner(1, 4), "1 mechanical change collapsed · 4 lines");
}

View File

@@ -0,0 +1,363 @@
//! Guided Review diff rendering — unified/split hunks, gutters, finding markers,
//! and syntax-highlighted source spans.
mod annotations;
mod source;
mod split;
mod unified;
use crate::app::App;
use crate::guided_review::{visible_groups, VisibleGroup};
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Paragraph, Wrap};
use ratatui::Frame;
#[cfg(test)]
pub(super) use annotations::comment_lines;
pub(super) use annotations::{display_author, is_feedback, thread_is_feedback};
pub(super) use unified::render_first_file_diff;
/// Renders the diff content pane: a left/top pad, a sticky `file › hunk` breadcrumb, then the
/// diff itself. The breadcrumb reinforces which file/hunk is shown as the reviewer moves, and the
/// left pad lifts the diff off the sidebar divider.
pub(super) fn render_content(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
narrate: bool,
) {
// 1-cell top + left padding for breathing room off the divider and the screen top.
let area = Rect {
x: area.x.saturating_add(1),
y: area.y.saturating_add(1),
width: area.width.saturating_sub(1),
height: area.height.saturating_sub(1),
};
if area.width == 0 || area.height == 0 {
return;
}
// The narration comes first and full width: the reviewer is here to understand the change, and
// the diff below is the evidence for what the prose just said.
// Only the wide tier narrates here: the stacked tiers already carry the section prose in their
// own context block, and saying it twice would cost the diff rows for nothing.
let narration = narrate
.then(|| super::narration::narration_lines(app, review, area.width.saturating_sub(1)))
.flatten();
let narration_height = narration.as_ref().map_or(0, |lines| {
// Never let the story crowd out the code it describes.
(lines.len() as u16 + 1).min(area.height / 2)
});
let area = if let (Some(lines), true) = (narration, narration_height > 0) {
let split = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(narration_height), Constraint::Min(1)])
.split(area);
frame.render_widget(Paragraph::new(lines), split[0]);
// A thin rule marks where the story ends and its evidence begins.
frame.render_widget(
Paragraph::new(Line::from(Span::styled(
"─".repeat(usize::from(split[0].width)),
app.theme_styles.border_muted,
))),
Rect { y: split[0].bottom().saturating_sub(1), height: 1, ..split[0] },
);
split[1]
} else {
area
};
// A blank spacer, then the diff. No breadcrumb: the narration above and the guide's foot
// already say the path, the symbol and the step, and none of them is worth two rows to repeat.
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(1), Constraint::Min(1)])
.split(area);
// Reserve the last column for the scrollbar so a long file says where you are in it; without
// one the pane gave no sense of position or of how much was left.
let body = rows[1];
let (diff_area, scrollbar_area) = if body.width > 2 {
(
Rect { width: body.width.saturating_sub(1), ..body },
Some(Rect { x: body.right().saturating_sub(1), width: 1, ..body }),
)
} else {
(body, None)
};
render_first_file_diff(frame, diff_area, app, review);
if let Some(scrollbar_area) = scrollbar_area {
render_diff_scrollbar(frame, scrollbar_area, app, review);
}
}
/// A proportional scrollbar for the selected file's visible rows.
fn render_diff_scrollbar(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
let total = visible_row_total(app, review);
crate::widgets::steered_scrollbar(
frame,
&mut app.hit.borrow_mut(),
area,
crate::mouse::ScrollRegionId::ReviewDiff,
app.guided_review_workspace.position.line_offset.min(total.saturating_sub(1)),
total,
usize::from(area.height),
&app.theme_styles,
);
}
/// The file the diff pane is showing: the selection, else the first item worth landing on.
pub(super) fn shown_file<'a>(
app: &App,
review: &'a luxe_core::guided_review::GuidedReview,
) -> Option<&'a luxe_core::guided_review::ReviewFile> {
app.guided_review_workspace
.position
.file_id
.as_ref()
.and_then(|selected| review.files.iter().find(|file| &file.id == selected))
.or_else(|| {
review
.files
.iter()
.find(|file| (file.is_text() && !file.hunks.is_empty()) || file.non_text.is_some())
})
}
/// Total visible rows in the selected file, matching the renderer's row space.
fn visible_row_total(app: &App, review: &luxe_core::guided_review::GuidedReview) -> usize {
shown_file(app, review)
.map(|file| {
visible_groups(file, &app.guided_review_workspace.fold)
.iter()
.map(VisibleGroup::rows)
.sum()
})
.unwrap_or_default()
}
/// Appends the end-of-reading marker under the rows when the pane has room for it, so the last
/// screen of a file is not indistinguishable from a scroll that stopped working.
///
/// Args: `(lines, app, review, (groups, shown), height)` — the visible groups and how many rows
/// from the offset the pane drew.
fn append_end_of_reading(
lines: &mut Vec<Line<'static>>,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
(groups, shown): (&[VisibleGroup<'_>], usize),
height: u16,
) {
let total_rows: usize = groups.iter().map(VisibleGroup::rows).sum();
let at_file_end =
app.guided_review_workspace.position.line_offset.saturating_add(shown) >= total_rows;
if (lines.len() as u16) < height {
if let Some(marker) = end_of_reading_marker(app, review, at_file_end) {
lines.push(Line::default());
lines.push(Line::from(Span::styled(marker, app.theme_styles.muted)));
}
}
}
/// The marker under the file's last row: where the reading stops, and what carries it on.
///
/// The pane draws one file at a time, so "these rows ran out" and "there is nothing more to read"
/// look identical from the bottom of a scroll. Naming which one it is, and the key past it, is what
/// lets scrolling clamp at the edge without reading as a stuck scrollbar.
///
/// At a chapter's end it also reports whether the chapter counted as reviewed, because that is the
/// one place the distinction shows: stepping here with `Space` records the chapter, scrolling here
/// does not, and nothing else on screen says which of the two just happened.
fn end_of_reading_marker(
app: &App,
review: &luxe_core::guided_review::GuidedReview,
at_file_end: bool,
) -> Option<String> {
let workspace = &app.guided_review_workspace;
if !at_file_end {
return None;
}
if !workspace.at_scope_end(review) {
return Some("— end of file —".into());
}
let index = review
.chapters
.iter()
.position(|chapter| workspace.position.chapter_id.as_ref() == Some(&chapter.id))?;
let reviewed = workspace.is_chapter_walked(&review.chapters[index].id);
let ending = if reviewed { "chapter reviewed" } else { "end of chapter" };
// The end of the reading is where the reader asks what comes next
let finish = super::chord(app, luxe_core::keymap::UiAction::ReviewFinish, "alt+enter");
Some(match review.chapters.get(index + 1) {
Some(next) => format!("— {ending} · ] {} —", next.title),
None if reviewed => format!("— last chapter reviewed · space or {finish} finishes —"),
None => format!("— end of the last chapter · space or {finish} finishes —"),
})
}
pub(super) fn render_non_text_diff(
frame: &mut Frame,
area: Rect,
app: &App,
file: &luxe_core::guided_review::ReviewFile,
) {
let mut lines = Vec::new();
let Some(change) = file.non_text.as_ref() else {
lines.push(Line::from(Span::styled("Non-text change", app.theme_styles.warning)));
frame.render_widget(Paragraph::new(lines), area);
return;
};
let kind = match change.kind {
luxe_core::guided_review::NonTextChangeKind::Binary => "Binary change",
luxe_core::guided_review::NonTextChangeKind::Submodule => "Submodule change",
luxe_core::guided_review::NonTextChangeKind::ModeOnly => "File mode change",
luxe_core::guided_review::NonTextChangeKind::Rename => "Rename-only change",
luxe_core::guided_review::NonTextChangeKind::Copy => "Copy-only change",
};
lines.push(Line::from(Span::styled(kind, app.theme_styles.warning)));
lines.push(Line::from(Span::styled(&change.summary, app.theme_styles.text)));
lines.push(Line::from(Span::styled("space reviewed", app.theme_styles.muted)));
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), area);
}
#[cfg(test)]
mod chrome_tests {
/// The workspace decides whether a column fits; this file lays the column out. They measure
/// the pane's fixed costs separately — the model may not reach into the view for a constant —
/// so the two numbers are held equal here rather than hoped to be.
#[test]
fn the_split_gate_measures_what_the_renderer_lays_out() {
assert_eq!(
crate::guided_review::SPLIT_PANE_CHROME,
crate::view::diff_lines::SPLIT_DIVIDER_CELLS + super::source::ACTIVE_BAR_WIDTH,
);
assert_eq!(
crate::guided_review::UNIFIED_ROW_CHROME,
super::source::ACTIVE_BAR_WIDTH + super::unified::UNIFIED_NUMBER_CHROME,
);
}
}
#[cfg(test)]
mod reply_preview_tests {
/// The card previews a reply's opening paragraph as it reads, not its markup.
#[test]
fn a_reply_previews_its_first_paragraph_as_text() {
let registry = luxe_core::theme::ThemeRegistry::new();
let resolved = registry.resolve("luxe").expect("luxe resolves");
let styles = crate::theme::styles::ThemeStyles::from_resolved(&resolved, "luxe");
let reply =
"**It's an off-by-one**, in `untrusted`.\nSecond line.\n\n```\ncode\n```\nMore.";
assert_eq!(
super::annotations::first_paragraph(reply, &styles),
"It's an off-by-one, in untrusted. Second line."
);
}
}
#[cfg(test)]
mod split_feedback_tests {
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::FindingId;
/// A split review with a comment on the row at unified `offset`, saying `body`.
fn commented(offset: usize, body: &str) -> crate::app::App {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewSplit).expect("fixture");
let files = app.guided_review.as_ref().expect("review").files.clone();
app.guided_review_workspace.position.line_offset = offset;
app.guided_review_workspace.position.hunk_id = None;
app.guided_review_workspace.begin_finding_draft(&files);
let draft = app.guided_review_workspace.finding_draft.as_mut().expect("draft");
draft.set_body(body);
let finding = draft.to_review_finding(FindingId::new()).expect("finding");
app.review.session_mut().expect("session").add_finding(finding).expect("added");
app.guided_review_workspace.discard_finding_draft();
app.guided_review_workspace.position.line_offset = 0;
app
}
/// Whether `body` is drawn in the card right under the first row drawing `line`, in the diff:
/// the card's top border, then its text.
fn carded_under(drawn: &[String], line: &str, body: &str) -> bool {
let y = drawn.iter().position(|row| row.contains(line)).expect("the line is drawn");
drawn.get(y + 2).is_some_and(|row| row.contains(body))
}
/// The drawn rows of the review surface.
fn rows(app: &mut crate::app::App, width: u16, height: u16) -> Vec<String> {
use ratatui::{backend::TestBackend, Terminal};
app.update(crate::app::Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("drawn");
let buffer = terminal.backend().buffer();
(0..height).map(|y| (0..width).map(|x| buffer[(x, y)].symbol()).collect()).collect()
}
/// Comment cards under a split hunk header take rows, and the clicks below them still land on
/// the row drawn there.
///
/// The break this catches: a header with cards recorded a height of one, so every click
/// region below it sat a card's worth of rows too high.
#[test]
fn split_header_feedback_does_not_shift_later_clicks() {
let mut app = commented(0, "About this whole hunk.");
let drawn = rows(&mut app, 200, 40);
assert!(carded_under(&drawn, "@@ -4,3", "About this whole hunk."), "{drawn:#?}");
let y = drawn.iter().position(|row| row.contains("pub struct Notification {")).unwrap();
let hit = app.hit.borrow();
let at = drawn[y].find("pub struct").unwrap();
let x = unicode_width::UnicodeWidthStr::width(&drawn[y][..at]) as u16;
assert_eq!(
hit.at(x, y as u16).cloned(),
Some(crate::mouse::MouseTarget::ReviewDiffRow(1)),
"the click on the first context row is that row"
);
}
/// A context line sits on both sides of its split row, and its comment is still drawn once.
#[test]
fn a_context_lines_comment_is_drawn_once() {
let mut app = commented(1, "Said once, not twice.");
let drawn = rows(&mut app, 200, 40);
let cards = drawn.iter().filter(|row| row.contains("│ Said once, not twice.")).count();
assert_eq!(cards, 1, "{drawn:#?}");
}
/// Wrapping a split diff keeps the comments under their lines.
#[test]
fn wrapping_a_split_diff_keeps_its_feedback() {
let mut app = commented(1, "Wrapped, and still here.");
app.guided_review_workspace.word_wrap = true;
let drawn = rows(&mut app, 200, 40);
assert!(
carded_under(&drawn, "pub struct Notification {", "Wrapped, and still here."),
"{drawn:#?}"
);
}
/// A comment on a deletion shows in the split row it shares with the addition beside it.
///
/// The break this catches: a pair looked up comments on its new side only, and an addition has
/// no old line, so the deletion's comment was never drawn.
#[test]
fn paired_deletion_keeps_old_side_feedback() {
let mut app = commented(2, "The removed field mattered.");
let drawn = rows(&mut app, 200, 40);
let said = carded_under(&drawn, "pub category: String", "The removed field mattered.");
assert!(said, "{drawn:#?}");
}
/// With the cursor on an addition paired with a deletion, the split pane draws that pair.
#[test]
fn a_selected_addition_reaches_the_split_screen() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewSplit).expect("fixture");
app.guided_review_workspace.position.line_offset = 3;
let drawn = rows(&mut app, 200, 40);
let shown = drawn.iter().any(|row| row.contains("pub category: NotificationCategory"));
assert!(shown, "{drawn:#?}");
}
}

View File

@@ -0,0 +1,352 @@
//! Review annotations — the comment and thread cards drawn under the lines they are anchored to.
use super::super::chord;
use crate::app::App;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// Rows one comment may spend on its body before it is clipped.
const MAX_COMMENT_BODY_ROWS: usize = 3;
/// Whether a line anchor points at this exact source line.
pub(in crate::view::guided_review) fn line_anchor_matches(
anchor: &luxe_core::guided_review::FindingAnchor,
file_id: &luxe_core::guided_review::FileId,
line: &luxe_core::guided_review::ReviewLine,
) -> bool {
use luxe_core::guided_review::{DiffSide, FindingAnchor};
let FindingAnchor::Line { file_id: anchor_file, side, line: anchor_line, .. } = anchor else {
return false;
};
anchor_file == file_id
&& match side {
DiffSide::Old => line.old_line == Some(*anchor_line),
DiffSide::New => line.new_line == Some(*anchor_line),
}
}
/// The comments whose anchor `matches`.
pub(super) fn findings_at(
app: &App,
matches: impl Fn(&luxe_core::guided_review::FindingAnchor) -> bool,
) -> Vec<luxe_core::guided_review::ReviewFinding> {
let Some(session) = app.review.session() else {
return Vec::new();
};
session.findings.iter().filter(|finding| matches(&finding.anchor)).cloned().collect()
}
/// One comment as rows under the line it is anchored to.
///
/// The whole point of rendering it here: under the code it is about, reading your own words needs
/// neither a drawer over the far corner nor an overlay on top of that.
pub(in crate::view::guided_review) fn comment_lines(
app: &App,
findings: &[luxe_core::guided_review::ReviewFinding],
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
for finding in findings {
// Only a question is worth naming. Everything else a reviewer writes is a comment, and a
// row that labeled every one of them "issue" spent a word saying what the surface is.
let question = finding.severity == luxe_core::guided_review::FindingSeverity::Question;
let tone = if question { styles.info } else { styles.error };
let severity = if question { "question" } else { "" };
let (state, state_style) = comment_state_label(app, finding, question);
let mut title = Vec::new();
if !severity.is_empty() {
title.push(Span::styled(format!("{severity} "), tone));
}
title.push(Span::styled(state, state_style));
let inner = card_inner_width(width);
let mut body = comment_body_rows(app, finding, inner);
body.extend(comment_reply_rows(app, finding, inner));
let fill = if question { styles.card_info_bg } else { styles.card_error_bg };
lines.extend(card_lines(tone, fill, title, body, width));
}
lines
}
/// What a comment is and what happens to it next, and the ink to say it in.
///
/// The second half is what a comment sitting in a drawer never told anyone.
fn comment_state_label(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
question: bool,
) -> (String, ratatui::style::Style) {
use luxe_core::guided_review::FindingState;
let styles = &app.theme_styles;
let pull_request = crate::app::github_post_is_pull_request(app);
// Bound for GitHub rather than the agent: someone else's pull request, and not a question
let for_github = pull_request && !question;
let answered = finding.github_thread.as_ref().filter(|thread| thread.resolved);
match finding.state {
_ if answered.is_some() => ("resolved on GitHub".to_owned(), styles.success),
FindingState::Draft | FindingState::Open if finding.posted.is_some() => {
("on GitHub \u{00b7} o opens it".to_owned(), styles.dim)
}
FindingState::Draft if for_github => (
format!(
"{} to post",
chord(app, luxe_core::keymap::UiAction::ReviewFinish, "alt+enter")
),
styles.warning,
),
FindingState::Draft => ("unsent".to_owned(), styles.warning),
// Spun here, on the card the reader just wrote, rather than only in the dock across
// the screen
FindingState::Open if being_worked(app, &finding.id) => {
let spinner = crate::statusline::spinner(app.guided_review_workspace.frame);
let doing = if question { "answering" } else { "working on it" };
(format!("{spinner} the agent is {doing}\u{2026}"), styles.accent)
}
// The answer is in, under it; following up, or asking for the fix, is the window's
FindingState::Open
if question
&& finding.thread.last().is_some_and(|message| {
message.author == luxe_core::guided_review::FindingMessageAuthor::Agent
}) =>
{
(
format!(
"answered \u{00b7} {} follows up",
chord(app, luxe_core::keymap::UiAction::ReviewFindings, "alt+c")
),
styles.success,
)
}
// The fix turn ended with no word on this one, so the agent is not still at it
FindingState::Open
if finding.thread.last().is_some_and(|message| {
message.author == luxe_core::guided_review::FindingMessageAuthor::System
}) =>
{
(
format!(
"no word from the agent \u{00b7} {} says why",
chord(app, luxe_core::keymap::UiAction::ReviewFindings, "alt+c")
),
styles.warning,
)
}
// Not fixed, or a question back for the reader: the agent has had its say
FindingState::Open
if !app.review.session().is_some_and(|session| {
super::super::context::with_the_agent(session, &finding.id)
}) && finding.thread.last().is_some_and(|message| {
message.author == luxe_core::guided_review::FindingMessageAuthor::Agent
}) =>
{
(
format!(
"the agent replied \u{00b7} {} reads it",
chord(app, luxe_core::keymap::UiAction::ReviewFindings, "alt+c")
),
styles.info,
)
}
FindingState::Open => ("sent \u{00b7} waiting on the agent".to_owned(), styles.dim),
FindingState::NeedsVerification => {
("to verify \u{00b7} alt+c shows what the agent changed".to_owned(), styles.info)
}
FindingState::Resolved => ("verified".to_owned(), styles.success),
FindingState::Stale => ("the code moved \u{00b7} alt+r re-anchors".to_owned(), styles.dim),
}
}
/// The comment's own words, wrapped to the card and capped.
fn comment_body_rows(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
inner: usize,
) -> Vec<Line<'static>> {
crate::widgets::wrap_line(
&Line::from(Span::styled(finding.body.clone(), app.theme_styles.text)),
inner,
)
.into_iter()
.take(MAX_COMMENT_BODY_ROWS)
.collect()
}
/// The last word that was not the reader's, under the comment.
fn comment_reply_rows(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
inner: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut rows = Vec::new();
// The last word that was not the reader's: the answer to a question belongs beside the
// question, not behind two overlays, and so does Luxe saying the agent left none
if let Some(reply) =
finding.thread.iter().rev().find(|message| {
message.author != luxe_core::guided_review::FindingMessageAuthor::Reviewer
})
{
let said = first_paragraph(&reply.body, styles);
let who = match reply.author {
luxe_core::guided_review::FindingMessageAuthor::System => "luxe",
_ => "agent",
};
rows.extend(
crate::widgets::wrap_line(
&Line::from(Span::styled(format!("{who}: {said}"), styles.muted)),
inner,
)
.into_iter()
.take(MAX_COMMENT_BODY_ROWS),
);
}
rows
}
/// Whether a submission carrying `finding` is with the agent right now.
fn being_worked(app: &App, finding: &luxe_core::guided_review::FindingId) -> bool {
use luxe_core::guided_review::SubmissionDispatch;
app.review.session().is_some_and(|session| {
session.submissions.iter().any(|submission| {
submission.dispatch == SubmissionDispatch::Dispatched
&& submission.findings.iter().any(|sent| &sent.finding_id == finding)
})
})
}
/// The opening paragraph of a reply, as it reads rendered: the card has three rows for it, and
/// markup shown raw spends them on asterisks and fences. The feedback window has the rest.
pub(super) fn first_paragraph(reply: &str, styles: &crate::theme::styles::ThemeStyles) -> String {
let text =
|line: &Line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>();
crate::markdown::render_markdown(reply, styles)
.iter()
.map(text)
.skip_while(|line| line.trim().is_empty())
.take_while(|line| !line.trim().is_empty())
.map(|line| line.trim().to_string())
.collect::<Vec<_>>()
.join(" ")
}
/// Whether a thread is already feedback: on your own pull request, an unresolved thread becomes a
/// finding, and drawing it a second time as earlier conversation would say everything twice.
pub(in crate::view::guided_review) fn thread_is_feedback(
app: &App,
thread: &luxe_core::guided_review::EarlierThread,
) -> bool {
is_feedback(app, &thread.id)
}
/// Whether the thread or conversation comment GitHub calls `id` became a finding.
pub(in crate::view::guided_review) fn is_feedback(app: &App, id: &str) -> bool {
!id.is_empty()
&& app.review.session().is_some_and(|session| {
session
.findings
.iter()
.any(|finding| finding.github_thread.as_ref().is_some_and(|origin| origin.id == id))
})
}
/// The earlier review threads that sit under `line` of the file `file_id`, on either side.
pub(in crate::view::guided_review) fn threads_at<'a>(
app: &'a App,
file_id: &luxe_core::guided_review::FileId,
line: &luxe_core::guided_review::ReviewLine,
) -> Vec<&'a luxe_core::guided_review::EarlierThread> {
use luxe_core::guided_review::DiffSide;
let Some(conversation) =
app.guided_review.as_ref().and_then(|review| review.conversation.as_ref())
else {
return Vec::new();
};
conversation
.threads()
.iter()
.filter(|thread| !thread_is_feedback(app, thread))
.filter(|thread| {
line.new_line.is_some_and(|number| thread.sits_at(file_id, DiffSide::New, number))
|| line
.old_line
.is_some_and(|number| thread.sits_at(file_id, DiffSide::Old, number))
})
.collect()
}
/// A reviewer's thread as rows under the line it is about.
///
/// A lighter rule than a comment of your own, because it is someone else's and nothing about it is
/// waiting on you: who opened it, whether it was resolved, what they said, and the latest reply.
/// The rest of a long thread is one `o` away on GitHub.
pub(in crate::view::guided_review) fn thread_lines(
app: &App,
threads: &[&luxe_core::guided_review::EarlierThread],
width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
for thread in threads {
let tone = if thread.resolved { styles.dim } else { styles.info };
let fill = if thread.resolved { styles.user_msg_bg } else { styles.card_info_bg };
let Some(opening) = thread.comments.first() else { continue };
let state = if thread.resolved { "resolved" } else { "unresolved" };
let replies = thread.total_comments.saturating_sub(1);
let mut title = vec![
Span::styled(display_author(&opening.author), styles.accent_secondary),
Span::styled(" \u{b7} ", styles.dim),
Span::styled(state, tone),
];
if replies > 0 {
let noun = if replies == 1 { "reply" } else { "replies" };
title.push(Span::styled(format!(" \u{b7} {replies} {noun}"), styles.dim));
}
let inner = card_inner_width(width);
let mut body = Vec::new();
let mut say = |text: String, style: Style, rows: usize| {
body.extend(
crate::widgets::wrap_line(&Line::from(Span::styled(text, style)), inner)
.into_iter()
.take(rows),
);
};
say(opening.body.clone(), styles.text, MAX_COMMENT_BODY_ROWS);
if let Some(latest) = thread.comments.iter().skip(1).last() {
say(format!("{}: {}", display_author(&latest.author), latest.body), styles.muted, 2);
}
let unshown = thread.total_comments.saturating_sub(thread.comments.len());
if unshown > 0 {
say(format!("{unshown} more on GitHub \u{b7} o"), styles.dim, 1);
}
lines.extend(card_lines(tone, fill, title, body, width));
}
lines
}
/// Cells between the diff's margin and a card's left edge.
const CARD_INDENT: usize = 2;
fn card_inner_width(width: usize) -> usize {
crate::widgets::card_inner_width(width, CARD_INDENT)
}
fn card_lines(
tone: Style,
fill: Style,
title: Vec<Span<'static>>,
body: Vec<Line<'static>>,
width: usize,
) -> Vec<Line<'static>> {
crate::widgets::card(tone, fill, title, body, width, CARD_INDENT)
}
/// A login the way GitHub writes one, `@mara`; a deleted account has none.
///
/// The `@` is what says it is a GitHub account and not a name the review made up, which a bare
/// `mara` beside a file path did not.
pub(in crate::view::guided_review) fn display_author(login: &str) -> String {
match login.strip_prefix("app/").unwrap_or(login) {
"" => "a deleted account".to_owned(),
name => format!("@{name}"),
}
}

View File

@@ -0,0 +1,130 @@
//! Review source rows — highlighting, intraline emphasis, hunk headers, line backgrounds and the
//! active bar.
use crate::app::App;
use crate::guided_review::diff::UnifiedDiffRow;
use crate::view::diff_lines::IntralineEmphasis;
use crate::view::emphasis;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// The full (unclipped) styled source spans for a diff line: syntax-highlighted for context, or the
/// line color with its changed spans marked for a replaced add/deletion. Owned spans so they can be
/// soft-wrapped independently of the borrowed source.
pub(super) fn full_source_spans(
line: &luxe_core::guided_review::ReviewLine,
changed: &[std::ops::Range<usize>],
style: Style,
file: &luxe_core::guided_review::ReviewFile,
app: &App,
) -> Vec<Span<'static>> {
let source = crate::tabstop::display_text(&line.text);
match line.kind {
luxe_core::guided_review::ReviewLineKind::Context => {
highlighted_source_spans(&source, file.language.as_deref(), app)
}
_ => emphasis::spans(&source, changed, style, emphasis_style(app, style, line)),
}
}
/// How a changed span is marked on `line`: a deeper wash of the row's own hue, and bold.
///
/// The wash stands down on a search hit. That row already wears the search highlight to say "this is
/// what you asked for", the match and the change are often the same token, and two backgrounds
/// competing inside one row leave neither legible. The mark still says what changed.
pub(super) fn emphasis_style(
app: &App,
base: Style,
line: &luxe_core::guided_review::ReviewLine,
) -> Style {
let added = matches!(line.kind, luxe_core::guided_review::ReviewLineKind::Addition);
let style = app.theme_styles.diff_emphasis(base, added);
if app.guided_review_workspace.line_matches_search(&crate::tabstop::display_text(&line.text)) {
Style { bg: None, ..style }
} else {
style
}
}
/// The intra-line marks for one rendered window, mapped from the review's own row space.
pub(super) fn intraline_emphasis(rows: &[UnifiedDiffRow<'_>]) -> IntralineEmphasis {
let sources: Vec<Option<&luxe_core::guided_review::ReviewLine>> = rows
.iter()
.map(|row| match row {
UnifiedDiffRow::Source(line) => Some(*line),
_ => None,
})
.collect();
crate::view::diff_lines::intraline_emphasis(&sources)
}
/// Cells at the margin reserved for the bar down the hunk being read.
pub(super) const ACTIVE_BAR_WIDTH: usize = 2;
/// The bar that marks the hunk under the cursor, or the blank that holds its column.
///
/// Spent on every row, selected or not: a marker that only appears under the cursor slides the
/// code sideways as the cursor arrives, which is the thing it exists to make legible.
pub(super) fn active_bar_span(app: &App, active: bool) -> Span<'static> {
if active {
Span::styled("\u{2503} ", app.theme_styles.accent)
} else {
Span::raw(" ")
}
}
pub(super) fn highlighted_source_spans(
text: &str,
language: Option<&str>,
app: &App,
) -> Vec<Span<'static>> {
crate::view::diff_lines::highlighted_source_spans(text, language, &app.theme_styles)
}
/// The `@@ … @@ heading` row that opens a hunk, in either layout.
///
/// When something already vouches for the hunk the header says *what*, in the reviewer's own words
/// — `covered by \`cargo test\``, `formatting only`. Naming it is the difference between a reviewer
/// who can disagree with the harness and one who cannot see that it decided anything.
pub(super) fn hunk_header_line(
app: &App,
hunk_id: &luxe_core::guided_review::HunkId,
old_range: luxe_core::guided_review::LineRange,
new_range: luxe_core::guided_review::LineRange,
heading: Option<&str>,
active: bool,
) -> Line<'static> {
use luxe_core::guided_review::ItemVerdict;
let selected = app.guided_review_workspace.position.hunk_id.as_ref() == Some(hunk_id);
let style = if selected {
app.theme_styles.accent.patch(app.theme_styles.selected_bg)
} else {
app.theme_styles.accent
};
let marker = if selected { "› " } else { " " };
let mut spans = vec![
active_bar_span(app, active),
Span::styled(
format!(
"{marker}@@ -{},{} +{},{} @@ {}",
old_range.start,
old_range.count,
new_range.start,
new_range.count,
heading.unwrap_or_default()
),
style,
),
];
if let ItemVerdict::Accounted(accounted) = app.review.budget.hunk_verdict(hunk_id) {
spans.push(Span::styled(format!(" {}", accounted.label()), app.theme_styles.dim));
}
Line::from(spans)
}
pub(super) fn diff_line_background(
kind: luxe_core::guided_review::ReviewLineKind,
app: &App,
) -> Option<Style> {
crate::view::diff_lines::diff_line_background(kind, &app.theme_styles)
}

View File

@@ -0,0 +1,254 @@
//! Side-by-side review diff — old and new columns over the same rows, each pair's source and the
//! feedback either side of it carries.
use super::annotations::{
comment_lines, findings_at, line_anchor_matches, thread_lines, threads_at,
};
use super::append_end_of_reading;
use super::source::{active_bar_span, hunk_header_line, ACTIVE_BAR_WIDTH};
use super::unified::folded_run_line;
use crate::app::App;
use crate::guided_review::diff::{gutter_width, visible_split_rows, SplitDiffCell, SplitRow};
use crate::guided_review::visible_groups;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;
/// One old/new pair's source, as one line or, wrapped, as many as it takes, behind the active-hunk
/// bar. Pairing is exact here, so the changed spans are too — no run-matching heuristic.
fn append_split_pair(
lines: &mut Vec<Line<'static>>,
app: &App,
layout: &crate::view::diff_lines::SplitLayout<'_>,
(old, new): (SplitDiffCell<'_>, SplitDiffCell<'_>),
(bar_span, word_wrap): (&Span<'static>, bool),
) {
let changed = match (old, new) {
// over the drawn text, like every other intra-line pass: the ranges are byte offsets
// into the string the renderer slices
(SplitDiffCell::Source(old), SplitDiffCell::Source(new)) if old.kind != new.kind => {
luxe_core::intraline::intraline_change(
&crate::tabstop::display_text(&old.text),
&crate::tabstop::display_text(&new.text),
)
}
_ => luxe_core::intraline::IntralineChange::default(),
};
let (old_style, new_style) = (split_cell_style(app, old), split_cell_style(app, new));
if word_wrap {
let wrapped = layout
.wrapped_pair((old, &changed.removed, &old_style), (new, &changed.added, &new_style));
lines.extend(wrapped.into_iter().map(|line| {
let mut spans = vec![bar_span.clone()];
spans.extend(line.spans);
Line::from(spans)
}));
return;
}
use crate::view::diff_lines::SplitSide;
let mut spans = vec![bar_span.clone()];
spans.extend(layout.cell_spans(SplitSide::Old, old, &changed.removed, &old_style));
spans.push(layout.divider());
spans.extend(layout.cell_spans(SplitSide::New, new, &changed.added, &new_style));
lines.push(Line::from(spans));
}
/// The comments and earlier threads anchored to either side of a pair, each once.
///
/// Both sides, because a pair can carry a deletion's comment on its old line and an addition's on
/// its new one; looking only at the new side lost the first whenever the second had no old line.
/// A context line sits on both sides, so what it carries is kept once.
fn pair_annotations(
app: &App,
file: &luxe_core::guided_review::ReviewFile,
(old, new): (SplitDiffCell<'_>, SplitDiffCell<'_>),
width: usize,
) -> Vec<Line<'static>> {
let mut findings: Vec<luxe_core::guided_review::ReviewFinding> = Vec::new();
let mut threads: Vec<&luxe_core::guided_review::EarlierThread> = Vec::new();
// old first, as the unified pane and the left column read
for cell in [old, new] {
let SplitDiffCell::Source(line) = cell else { continue };
for finding in findings_at(app, |anchor| line_anchor_matches(anchor, &file.id, line)) {
if !findings.iter().any(|kept| kept.id == finding.id) {
findings.push(finding);
}
}
for thread in threads_at(app, &file.id, line) {
if !threads.iter().any(|kept| std::ptr::eq(*kept, thread)) {
threads.push(thread);
}
}
}
let mut lines = comment_lines(app, &findings, width);
lines.extend(thread_lines(app, &threads, width));
lines
}
/// Renders the selected file side by side: old on the left, new on the right.
///
/// Shares the unified row space (`position.line_offset`), so scrolling, hunk selection, click
/// mapping, search and the findings gutter behave exactly as they do unified. The previous split
/// renderer paged one hunk against a private offset and could not show a file.
pub(super) fn render_split_file_diff(
frame: &mut Frame,
area: Rect,
app: &App,
file: &luxe_core::guided_review::ReviewFile,
review: &luxe_core::guided_review::GuidedReview,
) {
let number_width = gutter_width(&file.hunks);
// The active-hunk bar sits outside both columns, at the margin, so the rule between them does
// not move as the cursor does.
let bar = ACTIVE_BAR_WIDTH as u16;
let mut layout = crate::view::diff_lines::split_layout(
&app.theme_styles,
area.width.saturating_sub(bar),
number_width,
0,
file.language.as_deref(),
);
// Wrapping supersedes horizontal scrolling, and the workspace already zeroes the offset when
// it turns on; passing it regardless keeps the two paths reading from one source of truth.
layout.column = app.guided_review_workspace.diff_column_offset;
let groups = visible_groups(file, &app.guided_review_workspace.fold);
let rows = visible_split_rows(
&groups,
app.guided_review_workspace.position.line_offset,
usize::from(area.height),
);
let active_rows = app
.guided_review_workspace
.position
.hunk_id
.as_ref()
.and_then(|hunk_id| crate::guided_review::hunk_row_span(&groups, hunk_id));
let word_wrap = app.guided_review_workspace.word_wrap;
let mut lines: Vec<Line> = Vec::with_capacity(rows.len());
let mut row_indices: Vec<usize> = Vec::with_capacity(rows.len());
// Visual height per logical row: what it drew, wrapped lines and comment cards included.
let mut heights: Vec<u16> = Vec::with_capacity(rows.len());
let drawn = SplitRowContext { app, file, layout: &layout, word_wrap, width: area.width };
for row in &rows {
row_indices.push(row.unified_index());
let on_active_hunk =
active_rows.as_ref().is_some_and(|span| span.contains(&row.unified_index()));
heights.push(append_split_row(&mut lines, &drawn, row, on_active_hunk));
}
publish_split_rows(app, area, &row_indices, &heights, &rows, file);
append_end_of_reading(&mut lines, app, review, (&groups, rows.len()), area.height);
frame.render_widget(Paragraph::new(lines), area);
}
/// What every split row is drawn against.
struct SplitRowContext<'a> {
app: &'a App,
file: &'a luxe_core::guided_review::ReviewFile,
layout: &'a crate::view::diff_lines::SplitLayout<'a>,
word_wrap: bool,
width: u16,
}
/// Appends one logical split row — a folded run, a hunk header with its cards, or a pair with the
/// feedback either side of it — and returns how many visual lines it drew.
fn append_split_row(
lines: &mut Vec<Line<'static>>,
ctx: &SplitRowContext<'_>,
row: &SplitRow<'_>,
on_active_hunk: bool,
) -> u16 {
let (app, file) = (ctx.app, ctx.file);
let bar_span = active_bar_span(app, on_active_hunk);
match row {
SplitRow::Folded { run, unified_index } => {
let selected = app.guided_review_workspace.position.line_offset == *unified_index
&& app.guided_review_workspace.position.hunk_id.is_none();
lines.push(folded_run_line(app, *run, selected, true));
1
}
SplitRow::Header { hunk_id, old_range, new_range, heading, .. } => {
let before = lines.len();
lines.push(split_header_line(
app,
hunk_id,
*old_range,
*new_range,
*heading,
on_active_hunk,
));
lines.extend(comment_lines(
app,
&findings_at(app, |anchor| {
matches!(anchor, luxe_core::guided_review::FindingAnchor::Hunk { hunk_id: at, .. } if at == *hunk_id)
}),
usize::from(ctx.width),
));
// a header carrying comment cards is that many rows tall, or every click below
// it lands a row short
(lines.len() - before) as u16
}
SplitRow::Pair { old, new, .. } => {
let before = lines.len();
append_split_pair(lines, app, ctx.layout, (*old, *new), (&bar_span, ctx.word_wrap));
lines.extend(pair_annotations(app, file, (*old, *new), usize::from(ctx.width)));
(lines.len() - before).max(1) as u16
}
}
}
/// Same click contract as unified: a row maps to its unified index, so a click anchors a comment
/// at the line the reviewer pointed at — including a wrapped row, across every visual line it
/// occupies.
fn publish_split_rows(
app: &App,
area: Rect,
row_indices: &[usize],
heights: &[u16],
rows: &[SplitRow<'_>],
file: &luxe_core::guided_review::ReviewFile,
) {
let mut regions = app.hit.borrow_mut();
let mut y = area.y;
for ((unified, height), row) in row_indices.iter().zip(heights).zip(rows) {
if y >= area.bottom() {
break;
}
let region_height = (*height).min(area.bottom().saturating_sub(y));
let target = if matches!(row, SplitRow::Folded { .. }) {
crate::mouse::MouseTarget::ReviewFoldedRun(file.id.clone())
} else {
crate::mouse::MouseTarget::ReviewDiffRow(*unified)
};
regions.push(Rect::new(area.x, y, area.width, region_height), target);
y = y.saturating_add(*height);
}
}
/// What the review knows about one side of a split row that the shared layout does not: whether a
/// search hit is claiming the row's background.
fn split_cell_style(app: &App, cell: SplitDiffCell<'_>) -> crate::view::diff_lines::SplitCellStyle {
let SplitDiffCell::Source(line) = cell else {
return crate::view::diff_lines::SplitCellStyle::default();
};
let searched =
app.guided_review_workspace.line_matches_search(&crate::tabstop::display_text(&line.text));
crate::view::diff_lines::SplitCellStyle {
marker: String::new(),
background: searched.then_some(app.theme_styles.selected_bg),
plain_wash: searched,
}
}
/// A hunk header spanning both columns, carrying the same selection and finding markers as unified.
fn split_header_line(
app: &App,
hunk_id: &luxe_core::guided_review::HunkId,
old_range: luxe_core::guided_review::LineRange,
new_range: luxe_core::guided_review::LineRange,
heading: Option<&str>,
active: bool,
) -> Line<'static> {
hunk_header_line(app, hunk_id, old_range, new_range, heading, active)
}

View File

@@ -0,0 +1,317 @@
//! Unified review diff — the selected file's rows one above the other, with folds, the active bar
//! and the feedback under each line.
use super::annotations::{
comment_lines, findings_at, line_anchor_matches, thread_lines, threads_at,
};
use super::source::{
active_bar_span, diff_line_background, emphasis_style, full_source_spans,
highlighted_source_spans, hunk_header_line, intraline_emphasis, ACTIVE_BAR_WIDTH,
};
use super::split::render_split_file_diff;
use super::{append_end_of_reading, render_non_text_diff, shown_file};
use crate::app::App;
use crate::guided_review::diff::{clip_terminal_cells, gutter_width, visible_rows, UnifiedDiffRow};
use crate::guided_review::visible_groups;
use crate::view::diff_lines::{changed_spans, clip_styled_spans, rendered_marker, tint_row};
use crate::view::emphasis;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;
/// Cells a unified row spends between its numbers and its source: a space after each number, and
/// the diff sign.
pub(super) const UNIFIED_NUMBER_CHROME: usize = 3;
pub(in crate::view::guided_review) fn render_first_file_diff(
frame: &mut Frame,
area: Rect,
app: &App,
review: &luxe_core::guided_review::GuidedReview,
) {
let Some(file) = shown_file(app, review) else {
return;
};
if !file.is_text() {
render_non_text_diff(frame, area, app, file);
return;
}
if app.guided_review_workspace.split_layout_active_for(file) {
render_split_file_diff(frame, area, app, file, review);
return;
}
let width = gutter_width(&file.hunks);
// One cell at the margin for the bar down the hunk being read, so `Space` is a shape moving
// rather than a redraw of the same frame with different code in it.
let source_width = usize::from(area.width)
.saturating_sub(width.saturating_mul(2) + ACTIVE_BAR_WIDTH + UNIFIED_NUMBER_CHROME);
let groups = visible_groups(file, &app.guided_review_workspace.fold);
let rows = visible_rows(
&groups,
app.guided_review_workspace.position.line_offset,
usize::from(area.height),
);
let emphasized = intraline_emphasis(&rows);
let line_offset = app.guided_review_workspace.position.line_offset;
// The rows the hunk under the cursor owns, so its bar runs the whole height of it even when
// the window starts below its header.
let active_rows = app
.guided_review_workspace
.position
.hunk_id
.as_ref()
.and_then(|hunk_id| crate::guided_review::hunk_row_span(&groups, hunk_id));
let mut lines: Vec<Line> = Vec::new();
// (first visual Y, visual height, absolute row index) so click regions map to the right source
// row despite blank inter-hunk spacers and wrapped continuation lines.
let mut row_ys: Vec<(u16, u16, usize)> = Vec::new();
let context = UnifiedContext {
app,
file,
width,
source_width,
area_width: area.width,
emphasized: &emphasized,
};
for (index, row) in rows.iter().enumerate() {
// Separate stacked blocks with a blank row so each reads as a distinct one.
if matches!(row, UnifiedDiffRow::HunkHeader { .. } | UnifiedDiffRow::Folded(_))
&& !lines.is_empty()
{
lines.push(Line::default());
}
let first_y = lines.len() as u16;
let on_active_hunk =
active_rows.as_ref().is_some_and(|span| span.contains(&(line_offset + index)));
match *row {
UnifiedDiffRow::Folded(run) => {
let selected = app.guided_review_workspace.position.line_offset
== line_offset + index
&& app.guided_review_workspace.position.hunk_id.is_none();
lines.push(folded_run_line(app, run, selected, false));
}
UnifiedDiffRow::HunkHeader { hunk_id, old_range, new_range, heading } => {
let header = (hunk_id, old_range, new_range, heading);
lines.extend(hunk_header_rows(app, header, on_active_hunk, area.width));
}
UnifiedDiffRow::Source(line) => {
lines.extend(unified_source_rows(&context, line, index, on_active_hunk));
append_unified_annotations(&mut lines, app, file, line, usize::from(area.width));
}
}
let visual_height = (lines.len() as u16).saturating_sub(first_y).max(1);
row_ys.push((first_y, visual_height, line_offset + index));
}
publish_diff_rows(app, area, &row_ys, &rows, file);
append_end_of_reading(&mut lines, app, review, (&groups, rows.len()), area.height);
frame.render_widget(Paragraph::new(lines), area);
}
/// A hunk's header row, with the comment cards anchored to the whole hunk under it.
fn hunk_header_rows(
app: &App,
(hunk_id, old_range, new_range, heading): (
&luxe_core::guided_review::HunkId,
luxe_core::guided_review::LineRange,
luxe_core::guided_review::LineRange,
Option<&str>,
),
on_active_hunk: bool,
width: u16,
) -> Vec<Line<'static>> {
let mut lines =
vec![hunk_header_line(app, hunk_id, old_range, new_range, heading, on_active_hunk)];
use luxe_core::guided_review::FindingAnchor;
let on_hunk = |anchor: &FindingAnchor| match anchor {
FindingAnchor::Hunk { hunk_id: at, .. } => at == hunk_id,
_ => false,
};
lines.extend(comment_lines(app, &findings_at(app, on_hunk), usize::from(width)));
lines
}
/// What every unified source row is drawn against.
struct UnifiedContext<'a> {
app: &'a App,
file: &'a luxe_core::guided_review::ReviewFile,
/// Digits each line number takes
width: usize,
source_width: usize,
area_width: u16,
emphasized: &'a crate::view::diff_lines::IntralineEmphasis,
}
/// One source line as its visual rows: the active bar, both numbers and the sign, then the source
/// wrapped under that gutter or clipped at the diff's column offset.
fn unified_source_rows(
ctx: &UnifiedContext<'_>,
line: &luxe_core::guided_review::ReviewLine,
index: usize,
on_active_hunk: bool,
) -> Vec<Line<'static>> {
let (app, file, width) = (ctx.app, ctx.file, ctx.width);
let mut lines: Vec<Line<'static>> = Vec::new();
let old = line.old_line.map_or_else(|| " ".repeat(width), |number| format!("{number:>width$}"));
let new = line.new_line.map_or_else(|| " ".repeat(width), |number| format!("{number:>width$}"));
let style = match line.kind {
luxe_core::guided_review::ReviewLineKind::Addition => app.theme_styles.success,
luxe_core::guided_review::ReviewLineKind::Deletion => app.theme_styles.error,
_ => app.theme_styles.text,
};
// The fixed gutter (active bar + old/new numbers + diff marker) prefixing the
// first visual line; wrapped continuations align their source under it.
let gutter = || {
vec![
active_bar_span(app, on_active_hunk),
Span::styled(format!("{old} {new} "), app.theme_styles.muted),
Span::styled(rendered_marker(line.kind), style),
]
};
let source = crate::tabstop::display_text(&line.text);
// Tint add/removed rows with a full-width bar; a search match wins so the located
// line stays obvious over the add/del tint.
let row_bg = if app.guided_review_workspace.line_matches_search(&source) {
Some(app.theme_styles.selected_bg)
} else {
diff_line_background(line.kind, app)
};
let finish = |mut spans: Vec<Span<'static>>| match row_bg {
Some(background) => Line::from(tint_row(spans, background, ctx.area_width)),
None => {
spans.shrink_to_fit();
Line::from(spans)
}
};
if app.guided_review_workspace.word_wrap {
// Soft-wrap the full source under the gutter with an aligned continuation glyph,
// instead of horizontal scrolling (`w` toggles this).
let full = full_source_spans(line, changed_spans(ctx.emphasized, index), style, file, app);
let continuation_pad = ACTIVE_BAR_WIDTH + width * 2 + 2;
for (segment_index, segment) in
crate::widgets::wrap_cells(full, ctx.source_width).into_iter().enumerate()
{
let mut spans = if segment_index == 0 {
gutter()
} else {
vec![Span::styled(
format!(
"{}{}",
" ".repeat(continuation_pad),
crate::glyphs::Mark::Continuation
),
app.theme_styles.dim,
)]
};
spans.extend(segment);
lines.push(finish(spans));
}
// Guarantee at least one visual line (e.g. an empty added line).
if lines.is_empty() {
lines.push(finish(gutter()));
}
return lines;
}
let column_offset = app.guided_review_workspace.diff_column_offset;
let source_spans = match line.kind {
luxe_core::guided_review::ReviewLineKind::Context => {
let clipped = clip_terminal_cells(&source, column_offset, ctx.source_width);
highlighted_source_spans(&clipped, file.language.as_deref(), app)
}
// Mark only the spans that changed; everything either side keeps the line's
// own color.
_ => crate::view::diff_lines::owned_spans(clip_styled_spans(
&emphasis::parts(
&source,
changed_spans(ctx.emphasized, index),
style,
emphasis_style(app, style, line),
),
column_offset,
ctx.source_width,
)),
};
let mut spans = gutter();
spans.extend(source_spans);
lines.push(match row_bg {
Some(background) => Line::from(tint_row(spans, background, ctx.area_width)),
None => Line::from(spans),
});
lines
}
/// The comments and earlier threads anchored to a source line, under it.
///
/// The comment sits under the line it is about, the way every review tool shows one: a bare `R1` in
/// a gutter, with the words in a drawer over the far corner, makes "where did my comment go" a
/// question at all.
fn append_unified_annotations(
lines: &mut Vec<Line<'static>>,
app: &App,
file: &luxe_core::guided_review::ReviewFile,
line: &luxe_core::guided_review::ReviewLine,
width: usize,
) {
lines.extend(comment_lines(
app,
&findings_at(app, |anchor| line_anchor_matches(anchor, &file.id, line)),
width,
));
lines.extend(thread_lines(app, &threads_at(app, &file.id, line), width));
}
/// Publish a click region per rendered source/header row → its absolute index (spanning its
/// wrapped visual lines), so a click moves the cursor/anchor there. A collapsed run is the one
/// row whose click means "open this" rather than "put the cursor here".
fn publish_diff_rows(
app: &App,
area: Rect,
row_ys: &[(u16, u16, usize)],
rows: &[UnifiedDiffRow<'_>],
file: &luxe_core::guided_review::ReviewFile,
) {
let mut regions = app.hit.borrow_mut();
for ((y, height, absolute), row) in row_ys.iter().zip(rows) {
let row_y = area.y.saturating_add(*y);
if row_y >= area.bottom() {
continue;
}
let region_height = (*height).min(area.bottom().saturating_sub(row_y));
let target = if matches!(row, UnifiedDiffRow::Folded(_)) {
crate::mouse::MouseTarget::ReviewFoldedRun(file.id.clone())
} else {
crate::mouse::MouseTarget::ReviewDiffRow(*absolute)
};
regions.push(Rect::new(area.x, row_y, area.width, region_height), target);
}
}
/// The row that stands in for a run of collapsed mechanical hunks.
///
/// It is a row, not an absence: whatever the classifier decided, the reviewer can see that
/// something is there, what kind of thing it is, how much of it there is, and how to open it.
pub(super) fn folded_run_line(
app: &App,
run: crate::guided_review::FoldedRun,
selected: bool,
full_width: bool,
) -> Line<'static> {
let style = if selected {
app.theme_styles.muted.patch(app.theme_styles.selected_bg)
} else {
app.theme_styles.muted
};
let marker =
format!("{}{} ", if selected { "› " } else { " " }, crate::glyphs::Mark::FoldClosed);
let mut spans = vec![
Span::styled(marker, style),
Span::styled(run.summary(), style),
Span::styled(" · enter opens", app.theme_styles.dim),
];
if full_width {
spans.push(Span::styled(String::new(), style));
}
Line::from(spans)
}

View File

@@ -0,0 +1,364 @@
//! The feedback window — every comment in a list, and the one under the cursor read in full.
//!
//! One window for two jobs. `Alt+C` opens it to work through feedback: go to a comment, reply,
//! verify, edit. `u` there turns it to choosing what goes to the agent, each row with a checkbox. A
//! comment is often long and often markdown, especially one an agent or a reviewer on GitHub
//! wrote, so the list keeps to a line a comment and the pane beside it draws the whole thing.
use super::overlays::{anchor_summary, finding_state_glyph, finding_state_label, overlay_block};
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use crate::mouse::MouseTarget;
use luxe_core::guided_review::{FindingMessageAuthor, FindingSeverity, ReviewFinding};
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
/// What the window is open for.
pub(super) enum FeedbackMode<'a> {
/// Working through feedback
Manage,
/// Choosing what goes to the agent
Send(&'a crate::guided_review::SendPreview),
}
/// What the send window says above the list; the manage window has no header.
fn header_lines(
mode: &FeedbackMode<'_>,
findings: &[&ReviewFinding],
styles: &crate::theme::styles::ThemeStyles,
) -> Vec<Line<'static>> {
match mode {
FeedbackMode::Manage => Vec::new(),
FeedbackMode::Send(send) => {
let included =
findings.iter().filter(|finding| !send.excluded.contains(&finding.id)).count();
vec![
Line::from(Span::styled(
match send.outcome {
Some(_) => "Finish the review by sending these comments to the agent",
None => "Send these comments to the agent",
},
styles.accent,
)),
Line::from(Span::styled(
format!("{included} of {} included", findings.len()),
styles.muted,
)),
Line::from(""),
]
}
}
}
/// Draws the reading pane and its scrollbar, and returns how far past its height the text runs.
fn render_preview(
frame: &mut Frame,
app: &App,
preview: Vec<Line<'static>>,
preview_rows: u16,
preview_area: Rect,
) -> u16 {
let styles = &app.theme_styles;
let room = preview_rows.saturating_sub(preview_area.height);
app.guided_review_workspace.feedback_room.set(room);
let scroll = app.guided_review_workspace.feedback_scroll.min(room);
let text_area = Rect { width: preview_area.width.saturating_sub(1), ..preview_area };
frame.render_widget(
Paragraph::new(preview).wrap(Wrap { trim: false }).scroll((scroll, 0)),
text_area,
);
crate::widgets::steered_scrollbar(
frame,
&mut app.hit.borrow_mut(),
preview_area,
crate::mouse::ScrollRegionId::ReviewFeedback,
usize::from(scroll),
usize::from(preview_rows),
usize::from(preview_area.height),
styles,
);
room
}
/// Draws the window.
pub(super) fn render_feedback_window(
frame: &mut Frame,
area: Rect,
app: &App,
mode: FeedbackMode<'_>,
) {
let styles = &app.theme_styles;
let (findings, selected) = rows(app, &mode);
if findings.is_empty() {
render_empty(frame, area, app);
return;
}
let width = area.width.saturating_sub(6).clamp(60, 150).min(area.width);
let list_width = (width * 2 / 5).clamp(28, 52);
// What the reading pane's text wraps at: the frame and its pad, the list, the divider, and the
// scrollbar's column. Counted wider, the last rows of a long comment could never be reached
let preview_width = width.saturating_sub(3 + list_width + 3 + 1).max(1);
let finding = findings.get(selected).copied();
let preview = finding.map_or_else(Vec::new, |finding| preview_lines(app, finding));
let preview_rows = crate::widgets::text_field::wrapped_rows(&preview, preview_width);
let header = header_lines(&mode, &findings, styles);
let header_rows = u16::try_from(header.len()).unwrap_or(0);
let list_rows = u16::try_from(findings.len()).unwrap_or(u16::MAX);
let height =
(header_rows + list_rows.max(preview_rows).max(8) + 2 + crate::widgets::FOOTER_ROWS)
.min(area.height.saturating_sub(2))
.min(area.height);
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
let (title, glyph) = match &mode {
FeedbackMode::Manage => ("Feedback", Icon::Findings.glyph()),
FeedbackMode::Send(_) => ("Send to agent", Icon::Finish.glyph()),
};
let block = overlay_block(app, glyph, title);
let inner = crate::widgets::footed_body(&block, popup);
frame.render_widget(Clear, popup);
let [header_area, body] = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Length(header_rows),
ratatui::layout::Constraint::Min(1),
])
.areas(inner);
frame.render_widget(Paragraph::new(header), header_area);
let [list_area, divider, preview_area] = ratatui::layout::Layout::horizontal([
ratatui::layout::Constraint::Length(list_width),
ratatui::layout::Constraint::Length(3),
ratatui::layout::Constraint::Min(1),
])
.areas(body);
// The list scrolls to keep the cursor in it
let offset = selected.saturating_sub(usize::from(list_area.height.saturating_sub(1)));
let row_width = usize::from(list_area.width);
let mut regions = app.hit.borrow_mut();
let lines: Vec<Line<'static>> = findings
.iter()
.enumerate()
.skip(offset)
.take(usize::from(list_area.height))
.map(|(index, finding)| {
if matches!(mode, FeedbackMode::Manage) {
let y = list_area.y + u16::try_from(index - offset).unwrap_or(0);
regions.push(
Rect::new(list_area.x, y, list_area.width, 1),
MouseTarget::ReviewFindingRow(finding.id.clone()),
);
}
list_row(app, &mode, finding, index == selected, row_width)
})
.collect();
drop(regions);
// `trim: false`: the rows arrive laid out, and trimming ate the frame off unselected ones
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), list_area);
let rule: Vec<Line<'static>> =
(0..divider.height).map(|_| Line::from(Span::styled(" │ ", styles.border_muted))).collect();
frame.render_widget(Paragraph::new(rule), divider);
let room = render_preview(frame, app, preview, preview_rows, preview_area);
let scrolls = if room > 0 { " · pgup/pgdn scroll" } else { "" };
let hint = match mode {
FeedbackMode::Manage => {
// The preview it opens lists what goes, so the hint needs no count to disagree with
// the guide's, which leaves out what the agent already has
let sends = if crate::app::window_sends(app).is_some() { " · u send" } else { "" };
format!(" {}{sends}{scrolls} · esc close ", manage_keys(app))
}
FeedbackMode::Send(_) => {
format!(" enter send · space include · ↑/↓ choose{scrolls} · esc cancel ")
}
};
crate::widgets::render_footed(frame, block, popup, &hint, None, styles);
}
/// The comments the window lists, and which of them is under the cursor.
fn rows<'a>(app: &'a App, mode: &FeedbackMode<'_>) -> (Vec<&'a ReviewFinding>, usize) {
let Some(session) = app.review.session() else {
return (Vec::new(), 0);
};
match mode {
FeedbackMode::Manage => {
let findings = crate::guided_review::ordered_findings(&session.findings);
let selected = app
.guided_review_workspace
.selected_finding_id
.as_ref()
.and_then(|id| findings.iter().position(|finding| &finding.id == id))
.unwrap_or(0);
(findings, selected)
}
FeedbackMode::Send(send) => {
let ids = crate::app::input::unsent_finding_ids(app);
let findings: Vec<&ReviewFinding> =
session.findings.iter().filter(|finding| ids.contains(&finding.id)).collect();
let selected = send.selected.min(findings.len().saturating_sub(1));
(findings, selected)
}
}
}
/// One comment in the list: its mark, its label, its title, and where it stands.
fn list_row(
app: &App,
mode: &FeedbackMode<'_>,
finding: &ReviewFinding,
selected: bool,
width: usize,
) -> Line<'static> {
let styles = &app.theme_styles;
let (mark, state, dim) = match mode {
FeedbackMode::Manage => (finding_state_glyph(finding), finding_state_label(finding), false),
FeedbackMode::Send(send) => {
let excluded = send.excluded.contains(&finding.id);
let mark = if excluded { "○" } else { crate::glyphs::Mark::Yes.glyph() };
let kind = if finding.severity == FindingSeverity::Question { "question" } else { "" };
(mark, kind, excluded)
}
};
let state = if state.is_empty() { String::new() } else { format!(" {state} ") };
let title_width = width.saturating_sub(3 + state.width() + crate::widgets::SELECTION_FRAME);
let text = if dim { styles.dim } else { styles.text };
crate::widgets::selection_row(
vec![
Span::styled(if selected { "›" } else { " " }, styles.accent),
Span::styled(mark, if dim { styles.dim } else { styles.accent }),
Span::styled(" ", text),
Span::styled(clip_terminal_cells_ellipsis(&plain(&finding.title), title_width), text),
Span::styled(state, styles.muted),
],
width,
selected,
styles,
)
}
/// A title as the reader sees it drawn: a comment's first line keeps its markdown, and `**`
/// around a word reads as noise in a list.
pub(super) fn plain(title: &str) -> String {
title.replace("**", "").replace("__", "").replace('`', "")
}
/// The comment in full: what kind it is and where it stands, where it is, what it says, and what
/// has been said about it since.
fn preview_lines(app: &App, finding: &ReviewFinding) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let kind = match finding.severity {
FindingSeverity::Question => "Question",
_ if finding.github_thread.is_some() => "Reviewer comment",
_ => "Comment",
};
let head = Span::styled(format!("{kind} · {}", finding_state_label(finding)), styles.accent);
let mut lines = vec![Line::from(head)];
let mut place = anchor_summary(app, &finding.anchor);
if let Some(thread) = finding.github_thread.as_ref() {
let author = if thread.author.is_empty() { "a deleted account" } else { &thread.author };
place = format!("{place} · from {author} on GitHub");
}
lines.push(Line::from(Span::styled(place, styles.muted)));
lines.push(Line::from(""));
lines.extend(crate::markdown::render_markdown(&finding.body, styles));
if let Some(fix) = finding.proposed_fix.as_deref().filter(|fix| !fix.trim().is_empty()) {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled("Proposed fix", styles.muted)));
lines.extend(crate::markdown::render_markdown(fix, styles));
}
for message in &finding.thread {
lines.push(Line::from(""));
let who = match message.author {
FindingMessageAuthor::Reviewer => "You",
FindingMessageAuthor::Agent => "The agent",
FindingMessageAuthor::System => "Luxe",
};
lines.push(Line::from(Span::styled(who, styles.muted)));
lines.extend(crate::markdown::render_markdown(&message.body, styles));
}
lines
}
/// What the keys do to the comment under the cursor, which depends on where it stands.
fn manage_keys(app: &App) -> &'static str {
use luxe_core::guided_review::FindingState;
let selected = app.review.session().and_then(|session| {
app.guided_review_workspace
.selected_finding_id
.as_ref()
.and_then(|id| session.findings.iter().find(|finding| &finding.id == id))
});
if crate::app::input::retryable_submission_for_selected_finding(app).is_some() {
return "enter go to it · r retry sending";
}
if crate::app::input::queued_submission_for_selected_finding(app).is_some() {
return "enter go to it · r send now · x cancel sending";
}
let question = selected
.filter(|finding| finding.severity == luxe_core::guided_review::FindingSeverity::Question);
match (question, selected.map(|finding| (finding.state, finding.posted.is_some()))) {
(Some(finding), _) => {
let resolved = finding.state == FindingState::Resolved;
match (crate::app::reply_asks_for_fix(app, finding), resolved) {
(true, false) => "enter go to it · c ask for a fix · a follow up · r resolve",
(true, true) => "enter go to it · c ask for a fix · a follow up · r reopen",
(false, false) => "enter go to it · a follow up · r resolve",
(false, true) => "enter go to it · a follow up · r reopen",
}
}
_ => manage_comment_keys(selected.map(|finding| (finding.state, finding.posted.is_some()))),
}
}
/// The keys for a comment, rather than a question, by where it stands.
fn manage_comment_keys(
selected: Option<(luxe_core::guided_review::FindingState, bool)>,
) -> &'static str {
use luxe_core::guided_review::FindingState;
match selected {
Some((FindingState::Draft, true)) => "enter go to it · o open on GitHub",
Some((FindingState::Draft, false)) => "enter go to it · e edit · x delete",
Some((FindingState::Stale, _)) => "enter go to it · alt+r re-anchor and verify",
Some((FindingState::Resolved, _)) => "enter go to it · r reopen · c reply",
Some((FindingState::Open, _)) => "enter go to it · r resolve · c reply",
Some((FindingState::NeedsVerification, _)) => {
"enter go to it · v what changed · r verify · c reply"
}
None => "↑/↓ choose",
}
}
/// No feedback yet: say how to leave some.
fn render_empty(frame: &mut Frame, area: Rect, app: &App) {
let styles = &app.theme_styles;
let lines = vec![
Line::from(Span::styled("No feedback yet", styles.text)),
Line::from(""),
Line::from(Span::styled("Put the cursor on a line, hunk or chapter:", styles.muted)),
Line::from(Span::styled("c comments on it · a asks the agent about it", styles.muted)),
Line::from(Span::styled("Either one stays anchored to this revision.", styles.muted)),
];
let width = area.width.saturating_sub(4).clamp(32, 56).min(area.width);
let height = (7 + crate::widgets::FOOTER_ROWS).min(area.height);
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
let block = overlay_block(app, Icon::Findings.glyph(), "Feedback");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(frame, block, popup, "esc close", None, styles);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,239 @@
use crate::app::{App, Msg};
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{FindingId, FindingSeverity, ReviewFinding};
use ratatui::{backend::TestBackend, buffer::Buffer, Terminal};
fn draw(app: &mut App, width: u16, height: u16) -> Buffer {
app.update(Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
terminal.backend().buffer().clone()
}
fn row(buffer: &Buffer, y: u16) -> String {
(0..buffer.area.width).map(|x| buffer[(x, y)].symbol()).collect()
}
/// The row the window's top border is on, and its footer rule's.
fn frame_rows(buffer: &Buffer, title: &str) -> (u16, u16) {
let top = (0..buffer.area.height)
.find(|y| {
let row = row(buffer, *y);
row.contains(title) && row.contains(['╭', '┌'])
})
.expect("top");
// The footer's rule, the row above its keys: where what the window says ends
let keys = (top + 2..buffer.area.height)
.find(|y| row(buffer, *y).contains("esc ") && row(buffer, y - 1).contains("────"))
.expect("the footer");
(top, keys - 1)
}
fn feedback(app: &mut App) -> &mut Vec<ReviewFinding> {
&mut app.review.session_mut().expect("session").findings
}
fn open(scenario: FixtureScenario) -> App {
let mut app = seeded_app("nord", scenario).expect("fixture app");
app.guided_review_workspace.findings_visible = true;
app
}
/// Centered both ways, the list two fifths of the window, the divider right after it, and as
/// tall as the longer of the list and the comment with a floor of eight rows.
#[test]
fn the_window_is_centered_and_split_two_fifths_to_three() {
let mut app = open(FixtureScenario::GuidedReviewFindings);
let buffer = draw(&mut app, 100, 40);
let (top, bottom) = frame_rows(&buffer, "Feedback");
assert_eq!(bottom - top + 1, 8 + 2, "{}", row(&buffer, top));
let corners = row(&buffer, top);
let left = corners.chars().position(|c| matches!(c, '╭' | '┌')).expect("left");
let right = corners.chars().position(|c| matches!(c, '╮' | '┐')).expect("right");
// 94 wide: three columns either side of a 100-column terminal
assert_eq!((left, right), (3, 96), "{corners}");
// Frame, pad, a 37-column list, then the divider's middle column
assert_eq!(buffer[(3 + 2 + 37 + 1, top + 1)].symbol(), "│");
// The review's inner area sits under a row of chrome and over the footer
let above = usize::from(top);
let below = usize::from(buffer.area.height - 1 - bottom);
assert!(above.abs_diff(below) <= 3, "{above} vs {below}");
let mut app = open(FixtureScenario::GuidedReviewReady);
let buffer = draw(&mut app, 100, 40);
let (top, bottom) = frame_rows(&buffer, "Feedback");
assert_eq!(bottom - top + 1, 7, "the empty window is its message and a frame");
let corners = row(&buffer, top);
let left = corners.chars().position(|c| matches!(c, '╭' | '┌')).expect("left");
assert_eq!(left, (100 - 56) / 2, "{corners}");
assert!(usize::from(top).abs_diff(usize::from(40 - 1 - bottom)) <= 3);
}
/// The cursor row is marked, a list longer than the window scrolls to keep it on screen, and
/// each drawn row is the click target for its own comment.
#[test]
fn the_list_follows_the_cursor_and_clicks_land_on_their_rows() {
let mut app = open(FixtureScenario::GuidedReviewFindings);
let template = feedback(&mut app)[0].clone();
for n in 0..30 {
let mut extra = template.clone();
extra.id = FindingId::new();
extra.label = format!("R{}", n + 10);
extra.title = format!("Extra comment {n}");
feedback(&mut app).push(extra);
}
let findings = crate::guided_review::ordered_findings(feedback(&mut app));
let last = findings.last().expect("last").id.clone();
// The first whole, with the gap before its state so `0` is not the start of `09`; the last
// by its start, since a long title is cut to fit its row
let first_title = format!("{} ", findings[0].title);
let last_title = findings.last().unwrap().title.chars().take(12).collect::<String>();
app.guided_review_workspace.selected_finding_id = Some(last.clone());
let buffer = draw(&mut app, 120, 24);
let text = (0..24).map(|y| row(&buffer, y)).collect::<Vec<_>>().join("\n");
// Inside the window: the guide behind it keeps a cursor of its own
let inside = |row: String| row.split_once('│').map(|(_, rest)| rest.to_owned());
let marked: Vec<String> =
(0..24).filter_map(|y| inside(row(&buffer, y))).filter(|row| row.contains('›')).collect();
assert_eq!(marked.len(), 1, "{text}");
assert!(marked[0].contains(&last_title), "{text}");
// In the list's columns, since the guide behind the window lists the feedback too
let list = |y: u16| (0..50).map(|x| buffer[(x, y)].symbol()).collect::<Vec<_>>();
let listed = (0..24).map(|y| list(y).concat()).collect::<Vec<_>>().join("\n");
assert!(!listed.contains(&first_title), "scrolled past the first: {listed}");
let (x, y) = (0..24)
.find_map(|y| {
let cells = list(y);
(0..cells.len() - last_title.len())
.find(|&x| cells[x..x + last_title.len()].concat() == last_title)
.map(|x| (u16::try_from(x).unwrap(), y))
})
.expect("drawn in the list");
let (_, rule) = frame_rows(&buffer, "Feedback");
assert_eq!(y, rule - 1, "the last row of the window's list, over the footer");
let hit = app.hit.borrow().at(x, y).cloned();
assert_eq!(hit, Some(crate::mouse::MouseTarget::ReviewFindingRow(last)));
}
/// A long comment scrolls to its last line, which lands on the pane's last row rather than
/// short of it or past it, and its text never runs into the scrollbar's column.
#[test]
fn a_long_comment_scrolls_exactly_to_its_end() {
let mut app = open(FixtureScenario::GuidedReviewFindings);
// The pane's text is 50 columns wide here: 94 less the frame and pad (3), the list (37),
// the divider (3) and the scrollbar (1). Each line is one column wider, so it wraps once
// exactly at the true width, and a pane counted even a column wider scrolls short.
let line = |n: usize| format!("{n:02} {}abcdef", "abcde ".repeat(7));
assert_eq!(line(0).len(), 51);
let body = (0..40).map(line).collect::<Vec<_>>().join("\n\n");
feedback(&mut app)[0].body = format!("{body}\n\nTHE END");
let first = feedback(&mut app)[0].id.clone();
app.guided_review_workspace.selected_finding_id = Some(first);
let buffer = draw(&mut app, 100, 40);
assert!((0..40).any(|y| row(&buffer, y).contains("pgup/pgdn scroll")));
app.guided_review_workspace.scroll_feedback(10_000);
let buffer = draw(&mut app, 100, 40);
let (_, bottom) = frame_rows(&buffer, "Feedback");
assert!(row(&buffer, bottom - 1).contains("THE END"), "{}", row(&buffer, bottom - 1));
// The pane's last column is the scrollbar's, never a letter: the right border is at 96
let lane = 96 - 1;
for y in bottom.saturating_sub(20)..bottom {
let cell = buffer[(lane, y)].symbol();
assert!(cell.chars().all(|c| !c.is_alphanumeric()), "{cell:?} at row {y}");
}
// A short one says nothing about scrolling
let mut app = open(FixtureScenario::GuidedReviewFindings);
let buffer = draw(&mut app, 100, 40);
assert!(!(0..40).any(|y| row(&buffer, y).contains("pgup/pgdn")));
}
/// The reading pane names what the comment is — a question, a reviewer's, or yours — with its
/// label when it has one, and shows a proposed fix only when there is one.
#[test]
fn the_reading_pane_says_what_the_comment_is() {
let mut app = open(FixtureScenario::GuidedReviewFindings);
let first = feedback(&mut app)[0].id.clone();
app.guided_review_workspace.selected_finding_id = Some(first);
let text = |app: &mut App| {
let buffer = draw(app, 120, 40);
(0..40).map(|y| row(&buffer, y)).collect::<Vec<_>>().join("\n")
};
let label = feedback(&mut app)[0].label.clone();
let shown = text(&mut app);
assert!(shown.contains("Comment · open"), "{shown}");
assert!(!shown.contains(&format!("{label} ")), "no label is drawn: {shown}");
feedback(&mut app)[0].severity = FindingSeverity::Question;
assert!(text(&mut app).contains("Question · open"));
feedback(&mut app)[0].severity = FindingSeverity::Issue;
feedback(&mut app)[0].github_thread = Some(luxe_core::guided_review::GitHubThread {
id: "PRRT_1".into(),
url: String::new(),
author: "mara".into(),
can_reply: true,
can_resolve: true,
reply_url: None,
resolved: false,
conversation: false,
});
let shown = text(&mut app);
assert!(shown.contains("Reviewer comment") && shown.contains("from mara on GitHub"));
feedback(&mut app)[0].proposed_fix = Some(" ".into());
assert!(!text(&mut app).contains("Proposed fix"));
feedback(&mut app)[0].proposed_fix = Some("Bound the retry.".into());
let shown = text(&mut app);
assert!(shown.contains("Proposed fix") && shown.contains("Bound the retry."));
}
/// Sending shows the same window with checkboxes: a question says so, an excluded row dims,
/// a long title is cut before the row's end, and the header counts what goes.
#[test]
fn sending_lists_each_comment_with_a_checkbox() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
let unsent = crate::app::input::unsent_finding_ids(&app);
let long = "A title long enough that it cannot fit beside its mark and label ".repeat(2);
for finding in feedback(&mut app).iter_mut() {
if finding.id == unsent[0] {
finding.severity = FindingSeverity::Question;
finding.title = long.trim().to_owned();
}
}
app.update(Msg::GuidedReviewOpenSendPreview);
let buffer = draw(&mut app, 120, 40);
let text = (0..40).map(|y| row(&buffer, y)).collect::<Vec<_>>().join("\n");
let question = (0..40)
.map(|y| row(&buffer, y))
.find(|row| row.contains("A title long enough"))
.expect("the question's row");
// Cut to exactly the room there is: the ellipsis meets the state's own gap
assert!(question.contains("… question ▌"), "and the row fills to its edge: {question}");
assert!(text.contains(&format!("{} of {} included", unsent.len(), unsent.len())));
app.update(Msg::GuidedReviewToggleSendPreviewRow);
let buffer = draw(&mut app, 120, 40);
let text = (0..40).map(|y| row(&buffer, y)).collect::<Vec<_>>().join("\n");
assert!(text.contains(&format!("{} of {} included", unsent.len() - 1, unsent.len())));
}
/// Opened with nothing selected, the window selects the first comment, since it draws the
/// cursor there and its keys act on the selection; a title's markdown reads as plain text.
#[test]
fn opening_selects_the_first_comment_and_titles_read_plain() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
app.guided_review_workspace.selected_finding_id = None;
app.guided_review_workspace.findings_visible = false;
feedback(&mut app)[0].title = "Pin **actions/setup-dotnet** to a `SHA`".into();
app.update(Msg::GuidedReviewToggleFindings);
let first = crate::guided_review::ordered_findings(feedback(&mut app))[0].id.clone();
assert_eq!(app.guided_review_workspace.selected_finding_id, Some(first));
let buffer = draw(&mut app, 140, 40);
let text = (0..40).map(|y| row(&buffer, y)).collect::<Vec<_>>().join("\n");
assert!(text.contains("Pin actions/setup-dotnet to a SHA"), "{text}");
assert!(!text.contains("**") && text.contains("enter go to it"), "{text}");
// Closing and opening again keeps where the reader was
let second = crate::guided_review::ordered_findings(feedback(&mut app))[1].id.clone();
app.guided_review_workspace.selected_finding_id = Some(second.clone());
app.update(Msg::GuidedReviewToggleFindings);
app.update(Msg::GuidedReviewToggleFindings);
assert_eq!(app.guided_review_workspace.selected_finding_id, Some(second));
}

View File

@@ -0,0 +1,245 @@
//! Review footer — the shortcut row under the diff: which keys it offers, fitted to the width, and
//! where each one's click lands.
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells;
use crate::guided_review::GuidedReviewLoadState;
use crate::mouse::ReviewFooterAction;
use ratatui::{
layout::Rect,
text::{Line, Span},
};
use unicode_width::UnicodeWidthStr;
/// A footer shortcut: its rendered label, the action a click dispatches, and how readily it yields
/// its cells. Higher `priority` drops first, so adding a hint can never push `Esc return` off the
/// row — the failure mode the previous hand-tuned width tiers had.
#[derive(Clone)]
pub(super) struct FooterSegment {
pub(super) label: String,
action: ReviewFooterAction,
priority: u8,
}
fn segment(label: impl Into<String>, action: ReviewFooterAction, priority: u8) -> FooterSegment {
FooterSegment { label: label.into(), action, priority }
}
/// The footer string, plus the clickable segments when the interactive "ready" footer applies.
pub(super) fn resolve_footer(app: &App, width: u16) -> (String, Option<Vec<FooterSegment>>) {
// The in-diff search prompt replaces the footer while it is open.
if let Some(query) = app.guided_review_workspace.search.as_ref() {
let _ = width;
return (format!("Search: {query}█ · enter/↓ next · ↑ previous · esc close"), None);
}
match &app.guided_review_workspace.load_state {
GuidedReviewLoadState::Loading { .. } => ("esc back to chat".into(), None),
GuidedReviewLoadState::Failed { error, .. }
if app.guided_review.is_some() && width >= 90 =>
{
// Reserve the recovery actions, then spend only the remaining cells on the cause
let detail_width = usize::from(width.saturating_sub(64)).min(40);
let detail = clip_terminal_cells(&error.message, 0, detail_width);
(
format!("Refresh failed: {detail} · r retry · s change source · esc back to chat"),
None,
)
}
GuidedReviewLoadState::Failed { .. } if width < 60 => ("r retry · esc back".into(), None),
GuidedReviewLoadState::Failed { .. } => {
("r retry · s change source · esc back to chat".into(), None)
}
GuidedReviewLoadState::Idle | GuidedReviewLoadState::Ready => {
let mut segments = ready_footer_segments(app, width);
// At a chapter boundary `n` is a dead key by design (movement is scoped so the
// narrative always describes the diff), so name the key that does move.
if let Some((label, action)) = chapter_boundary_hint(app, width) {
segments.insert(0, segment(label, action, 3));
}
let segments = fit_footer_segments(segments, width);
(footer_segments_text(&segments), Some(segments))
}
}
}
/// Joins segment labels the way the footer draws them.
fn footer_segments_text(segments: &[FooterSegment]) -> String {
segments.iter().map(|segment| segment.label.as_str()).collect::<Vec<_>>().join(SEPARATOR)
}
/// Between two footer shortcuts, as between two keys in a panel's hint.
const SEPARATOR: &str = " · ";
/// Total cells `segments` occupy once joined.
pub(super) fn footer_segments_width(segments: &[FooterSegment]) -> usize {
let labels: usize =
segments.iter().map(|segment| UnicodeWidthStr::width(segment.label.as_str())).sum();
labels + SEPARATOR.width() * segments.len().saturating_sub(1)
}
/// Drops the least important shortcuts until the row fits, so the footer degrades by priority
/// instead of being clipped mid-label (which also desynchronizes the click regions).
pub(super) fn fit_footer_segments(
mut segments: Vec<FooterSegment>,
width: u16,
) -> Vec<FooterSegment> {
while segments.len() > 1 && footer_segments_width(&segments) > usize::from(width) {
let drop = segments
.iter()
.enumerate()
.max_by_key(|(index, segment)| (segment.priority, *index))
.map(|(index, _)| index);
match drop {
Some(index) => {
segments.remove(index);
}
None => break,
}
}
segments
}
/// The same footer as spans, keys in the accent the way a panel's hint draws them, so the
/// shortcut under the pointer lights up like the button it is.
pub(super) fn footer_spans(app: &App, segments: &[FooterSegment], width: u16) -> Line<'static> {
let _ = width;
let styles = &app.theme_styles;
let mut spans: Vec<Span<'static>> = Vec::with_capacity(segments.len() * 3);
for (index, segment) in segments.iter().enumerate() {
if index > 0 {
spans.push(Span::styled(SEPARATOR, styles.muted));
}
let hovered = app.pointer.hover.as_ref()
== Some(&crate::mouse::MouseTarget::ReviewFooter(segment.action));
match hovered {
true => spans.push(Span::styled(segment.label.clone(), styles.selected_bg)),
false => spans.extend(hint_spans(&segment.label, styles)),
}
}
Line::from(spans)
}
/// A footer that is not the ready one — a failed refresh, a search — drawn with the same key
/// styling. Its segments are split on the separator, and a segment is only a key and its words
/// when it starts with one, so a sentence among them stays a sentence.
pub(super) fn footer_hint_line(
text: &str,
styles: &crate::theme::styles::ThemeStyles,
) -> Line<'static> {
let mut spans = Vec::new();
for (index, piece) in text.split(SEPARATOR).enumerate() {
if index > 0 {
spans.push(Span::styled(SEPARATOR, styles.muted));
}
spans.extend(hint_spans(piece, styles));
}
Line::from(spans)
}
/// One shortcut, `Alt+C feedback`: the key in the accent and the words in the body text. A piece
/// that does not open with a key reads as text.
fn hint_spans(label: &str, styles: &crate::theme::styles::ThemeStyles) -> Vec<Span<'static>> {
match label.split_once(' ') {
Some((key, words)) if is_key(key) => vec![
Span::styled(key.to_owned(), styles.accent),
Span::styled(format!(" {words}"), styles.text),
],
_ => vec![Span::styled(label.to_owned(), styles.text)],
}
}
/// Whether a label's first word names a key: a chord, a named key, or one character.
pub(super) fn is_key(word: &str) -> bool {
const NAMED: [&str; 6] = ["space", "enter", "esc", "tab", "pgup", "pgdn"];
word.contains('+') || NAMED.contains(&word) || word.contains('/') || word.chars().count() == 1
}
/// The interactive "ready" footer as ordered segments; [`fit_footer_segments`] trims it to the
/// width by priority.
pub(super) fn ready_footer_segments(app: &App, width: u16) -> Vec<FooterSegment> {
use ReviewFooterAction as A;
// What a reader needs to *work*, and nothing else: past about half a dozen nobody reads any of
// them, and the ones that matter stop being findable. The layout, the guide, churn and the
// rest are all still bound and all named by `? help`, the surface built to list them; the
// churn keys are also in the guide's foot, beside the churn they open. Esc is the one key
// nobody has to be told.
//
// Finishing is where everything that happens *after* reading lives — committing, opening a
// pull request, posting — and nothing else on screen says it exists. The feedback window
// earns its cells once there is feedback in it.
let finish =
format!("{} finish", chord(app, luxe_core::keymap::UiAction::ReviewFinish, "alt+enter"));
let feedback =
format!("{} feedback", chord(app, luxe_core::keymap::UiAction::ReviewFindings, "alt+c"));
let has_feedback = app.review.session().is_some_and(|session| !session.findings.is_empty());
let _ = width;
let mut segments = vec![
segment("space next", A::HunkNext, 2),
segment("c comment", A::AddComment, 3),
segment("a ask agent", A::AskQuestion, 5),
segment(feedback, A::Feedback, 4),
segment(finish, A::Finish, 2),
segment("? help", A::ToggleHelp, 1),
];
if !has_feedback {
segments.retain(|cell| cell.action != A::Feedback);
}
segments
}
/// The first key bound to `action`, as the footer names keys, or `fallback` when nothing is bound.
pub(in crate::view) fn chord(
app: &App,
action: luxe_core::keymap::UiAction,
fallback: &str,
) -> String {
app.keymap
.chords_for(action)
.and_then(|chords| chords.first())
.map_or_else(|| fallback.to_owned(), ToString::to_string)
}
/// The chapter-boundary hint, when the diff cursor sits on the first or last item the current
/// chapter owns. Scoped movement makes `n`/`N` a deliberate dead key there, so the footer names
/// the key that does move. Forward wins when a one-item chapter is both ends at once.
fn chapter_boundary_hint(app: &App, width: u16) -> Option<(String, ReviewFooterAction)> {
let workspace = &app.guided_review_workspace;
if width < 90 {
return None;
}
let review = app.guided_review.as_ref()?;
let index = review
.chapters
.iter()
.position(|chapter| workspace.position.chapter_id.as_ref() == Some(&chapter.id))?;
let long = width >= 120;
if index + 1 < review.chapters.len() && workspace.at_scope_end(review) {
return Some((
if long { "] next chapter".into() } else { "] chapter".into() },
ReviewFooterAction::ChapterNext,
));
}
if index > 0 && workspace.at_scope_start(review) {
return Some((
if long { "[ previous chapter".into() } else { "[ chapter".into() },
ReviewFooterAction::ChapterPrev,
));
}
None
}
/// Publishes a click region for each footer segment, matching the left-aligned Paragraph layout.
pub(super) fn publish_footer_regions(app: &App, area: Rect, segments: &[FooterSegment]) {
let separator_width = SEPARATOR.width() as u16;
let label_width = |label: &str| UnicodeWidthStr::width(label) as u16;
let mut x = area.x;
let mut regions = app.hit.borrow_mut();
for segment in segments {
let cells = label_width(&segment.label);
regions.push(
Rect::new(x, area.y, cells, 1),
crate::mouse::MouseTarget::ReviewFooter(segment.action),
);
x = x.saturating_add(cells).saturating_add(separator_width);
}
}

View File

@@ -0,0 +1,379 @@
//! The post preview — exactly what a pull request's review will say on GitHub, before it does.
//!
//! Two panes, the way the command palette reads: what will be posted on the left — the review
//! itself, then each comment that sits on a line — and the whole text of the one under the cursor
//! on the right, drawn as the markdown GitHub will render. A one-line title is never posted: what
//! GitHub shows is the comment, so that is what the preview shows. A terminal too narrow for both
//! stacks the text under the list.
mod items;
mod preview;
use super::overlays::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::theme::styles::ThemeStyles;
use items::{items, list_lines, Item};
use luxe_core::github::ReviewEvent;
use luxe_core::guided_review::PostPlanError;
use preview::pane_lines;
use ratatui::layout::Rect;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
/// The widest the dialog grows: past this a comment's lines get too long to read comfortably.
const MAX_WIDTH: u16 = 116;
/// The narrowest the list may be and still name where a comment lands.
const LIST_MIN: u16 = 24;
/// The narrowest the text pane may be and still read as prose.
const PANE_MIN: u16 = 34;
/// The most rows the dialog's body takes, however long a comment runs; the pane scrolls past it.
const MAX_BODY_ROWS: usize = 24;
pub(super) fn render_github_post(
frame: &mut Frame,
area: Rect,
app: &App,
post: &crate::guided_review::GithubPost,
) {
let styles = &app.theme_styles;
let width = area.width.saturating_sub(4).clamp(50, MAX_WIDTH).min(area.width);
let mut head = post_preview_head(app, post, width);
let Some(prepared) = post.prepared.as_ref() else {
head.push(Line::from(""));
match post.error.as_deref() {
Some(error) => {
head.push(Line::from(Span::styled(error.to_owned(), styles.error)));
}
None => head.push(Line::from(Span::styled(
format!(
"{} Reading the pull request…",
crate::statusline::spinner(app.guided_review_workspace.frame)
),
styles.muted,
))),
}
return draw(frame, area, app, width, head, None, post);
};
let posted = posted_count(app);
let notes = post_preview_notes(app, post, prepared, posted);
if !notes.is_empty() {
head.push(Line::from(""));
head.extend(notes);
}
match crate::app::github_post_plan(app) {
Some(Ok(plan)) => {
let items = items(app, &plan);
draw(frame, area, app, width, head, Some(&items), post);
}
Some(Err(error)) => {
head.push(Line::from(""));
head.push(Line::from(Span::styled(refusal(error, posted, prepared), styles.warning)));
draw(frame, area, app, width, head, None, post);
}
None => draw(frame, area, app, width, head, None, post),
}
}
/// The dialog's head: what it posts to, and the verdict between rules of its own.
fn post_preview_head(
app: &App,
post: &crate::guided_review::GithubPost,
width: u16,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let title = app
.guided_review
.as_ref()
.and_then(|review| review.context.pull_request.as_ref())
.map_or_else(
|| "Post this review to GitHub".to_owned(),
|pr| format!("Post this review to {}#{}", pr.repository, pr.number),
);
// The verdict is the one choice the dialog asks for, so it sits between rules of its own
let inner = width.saturating_sub(3);
let mut head = vec![Line::from(Span::styled(title, styles.accent)), rule(inner, styles)];
head.push(verdict_row(post, styles));
head.push(rule(inner, styles));
head
}
/// Comments of this review already on GitHub, which posting again leaves alone.
fn posted_count(app: &App) -> usize {
app.review.session().map_or(0, |session| {
session.findings.iter().filter(|finding| finding.posted.is_some()).count()
})
}
/// What the reader should know before posting: whose pull request it is, a push since they read
/// it, what is already up, an error, and the post in flight.
fn post_preview_notes(
app: &App,
post: &crate::guided_review::GithubPost,
prepared: &crate::guided_review::PreparedPost,
posted: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut notes = Vec::new();
if prepared.own_pull_request {
notes.push(Line::from(Span::styled("Your pull request · comment only", styles.muted)));
}
if prepared.head_moved {
notes.push(Line::from(Span::styled(
format!(
"Pushed since you read it · comments stay on {}, marked outdated",
pinned_head(app)
),
styles.warning,
)));
}
if posted > 0 {
notes.push(Line::from(Span::styled(
match posted {
1 => "1 comment already on GitHub · not posted again".to_owned(),
count => format!("{count} comments already on GitHub · not posted again"),
},
styles.dim,
)));
}
if let Some(error) = post.error.as_deref() {
notes.push(Line::from(Span::styled(error.to_owned(), styles.error)));
}
if post.posting {
notes.push(Line::from(Span::styled(
format!(
"{} Posting to GitHub…",
crate::statusline::spinner(app.guided_review_workspace.frame)
),
styles.muted,
)));
}
notes
}
/// A rule across the dialog's inside, the one divider it uses between its parts.
/// A rule across the dialog's head, a cell clear of the frame on both sides: the panel's left pad
/// gives it one, and this the other. The footer's rule is the frame's and runs edge to edge.
fn rule(inner: u16, styles: &ThemeStyles) -> Line<'static> {
Line::from(Span::styled("─".repeat(usize::from(inner.saturating_sub(1))), styles.border_muted))
}
/// The verdicts on offer as tabs, each with GitHub's icon for it: the chosen one cut the way every
/// open tab is, the ones GitHub will not take dimmed.
fn verdict_row(post: &crate::guided_review::GithubPost, styles: &ThemeStyles) -> Line<'static> {
use crate::glyphs::{icon_label, Icon};
let on_offer = post.verdicts();
let surface = styles
.selected_bg
.bg
.unwrap_or_else(|| styles.slab.at(crate::theme::styles::Depth::Raised));
let bold = Style::new().add_modifier(ratatui::style::Modifier::BOLD);
let mut spans = Vec::new();
for verdict in [ReviewEvent::Comment, ReviewEvent::Approve, ReviewEvent::RequestChanges] {
let label = match verdict {
ReviewEvent::Comment => icon_label(Icon::ReviewComment.glyph(), "Comment"),
ReviewEvent::Approve => icon_label(Icon::ReviewApprove.glyph(), "Approve"),
ReviewEvent::RequestChanges => {
icon_label(Icon::ReviewRequestChanges.glyph(), "Request changes")
}
};
if verdict == post.verdict {
spans.extend(crate::widgets::slab(
[Span::styled(label, styles.accent)],
surface,
styles.slab.canvas,
bold,
));
} else {
let style = if on_offer.contains(&verdict) { styles.muted } else { styles.dim };
spans.push(Span::styled(format!(" {label} "), style));
}
}
Line::from(spans)
}
/// Why nothing can be posted yet, in the words that say what to do about it.
fn refusal(
error: PostPlanError,
posted: usize,
prepared: &crate::guided_review::PreparedPost,
) -> String {
match error {
PostPlanError::Nothing if posted > 0 => {
"Already on GitHub · nothing new to post".to_owned()
}
PostPlanError::Nothing if prepared.own_pull_request => {
"Nothing to post · no comments yet".to_owned()
}
PostPlanError::NeedsBody => {
format!("{} c writes it.", crate::app::github_post_refusal(PostPlanError::NeedsBody))
}
error => crate::app::github_post_refusal(error),
}
}
/// How the body splits once the head is laid out: in half, the palette's rule. Args:
/// `(list_width, pane_width)`, or `None` for one column.
fn split(inner: u16) -> Option<(u16, u16)> {
let split = crate::picker::Split::of(inner);
(split.list >= LIST_MIN && split.pane >= PANE_MIN).then_some((split.list, split.pane))
}
fn draw(
frame: &mut Frame,
area: Rect,
app: &App,
width: u16,
head: Vec<Line<'static>>,
items: Option<&[Item]>,
post: &crate::guided_review::GithubPost,
) {
let styles = &app.theme_styles;
// Borders and the block's left pad
let inner = width.saturating_sub(3);
let head: Vec<Line<'static>> =
head.iter().flat_map(|line| crate::widgets::wrap_line(line, inner.into())).collect();
let selected = items.map_or(0, |items| post.selected.min(items.len().saturating_sub(1)));
let layout = items.map(|items| (items, split(inner)));
// Sized for the longest text any item has, so the dialog holds still as the cursor moves
let body_rows = match layout {
None => 0,
Some((items, Some((_, pane)))) => items
.iter()
.map(|item| pane_lines(app, item, pane.into()).len())
.max()
.unwrap_or(0)
.max(list_lines(app, items, 0, pane.into()).len())
.min(MAX_BODY_ROWS),
Some((items, None)) => {
let text = items
.iter()
.map(|item| pane_lines(app, item, inner.into()).len())
.max()
.unwrap_or(0);
(list_lines(app, items, 0, inner.into()).len() + 1 + text).min(MAX_BODY_ROWS)
}
};
let gap = usize::from(body_rows > 0);
let rows = head.len() + gap + body_rows + 2 + usize::from(crate::widgets::FOOTER_ROWS);
let rows = u16::try_from(rows).unwrap_or(u16::MAX);
let Some(popup) = crate::widgets::fit_review_preview(frame, area, (width, rows, 8), app) else {
return;
};
let block = overlay_block(app, Icon::GitHub.glyph(), "Post to GitHub");
frame.render_widget(Clear, popup);
let summary = crate::app::review_draft_summary(app).is_some();
let room = usize::from(width.saturating_sub(4));
let keys = hint(post, items.map_or(0, <[Item]>::len), summary, room);
let content = crate::widgets::render_footed(frame, block, popup, &keys, None, styles);
let head_rows = u16::try_from(head.len()).unwrap_or(u16::MAX).min(content.height);
frame.render_widget(Paragraph::new(head), Rect { height: head_rows, ..content });
let top = content.y + head_rows + u16::try_from(gap).unwrap_or(0);
let body = Rect { y: top, height: content.bottom().saturating_sub(top), ..content };
let Some((items, split)) = layout else { return };
if body.height == 0 {
return;
}
let item = &items[selected];
match split {
Some((list, pane)) => {
let rows = list_lines(app, items, selected, list.into());
let at = rows.iter().position(|(item, _)| *item == Some(selected)).unwrap_or(0);
let skip = at.saturating_sub(usize::from(body.height).saturating_sub(1));
let rows: Vec<Line<'static>> =
rows.into_iter().skip(skip).map(|(_, row)| row).collect();
frame.render_widget(Paragraph::new(rows), Rect { width: list, ..body });
let text = scrolled(pane_lines(app, item, pane.into()), post.scroll, body.height);
crate::picker::render_pane(frame, body, list, pane, &text, styles);
}
None => {
let rows: Vec<Line<'static>> = list_lines(app, items, selected, body.width.into())
.into_iter()
.map(|(_, row)| row)
.collect();
let list_rows = u16::try_from(rows.len()).unwrap_or(u16::MAX).min(body.height);
frame.render_widget(Paragraph::new(rows), Rect { height: list_rows, ..body });
let text_top = body.y + list_rows + 1;
let text_area =
Rect { y: text_top, height: body.bottom().saturating_sub(text_top), ..body };
let text =
scrolled(pane_lines(app, item, body.width.into()), post.scroll, text_area.height);
frame.render_widget(Paragraph::new(text), text_area);
}
}
}
/// `lines` from `scroll` on, clamped so the last row can reach the bottom but not leave it.
fn scrolled(lines: Vec<Line<'static>>, scroll: u16, height: u16) -> Vec<Line<'static>> {
let most = lines.len().saturating_sub(usize::from(height));
lines.into_iter().skip(usize::from(scroll).min(most)).collect()
}
/// The keys, naming only what this state of the dialog will do, in the `room` the frame has.
///
/// Posting and leaving always fit; the rest drop out least-needed first, so a narrow terminal
/// loses the worktree key before it loses the one that moves between comments.
fn hint(
post: &crate::guided_review::GithubPost,
items: usize,
summary: bool,
room: usize,
) -> String {
if post.posting {
return " posting… ".to_owned();
}
if post.prepared.is_none() {
let keys =
if post.error.is_some() { " enter retry · esc cancel " } else { " esc cancel " };
return keys.to_owned();
}
// In reading order, each with the rank it is dropped at: highest goes first
let drafting = post.drafting.is_some();
let keys = [
("enter post", 0),
("↑/↓ comment", if items > 1 { 2 } else { u8::MAX }),
("tab verdict", if post.verdicts().len() > 1 { 1 } else { u8::MAX }),
("drafting the summary…", if drafting { 1 } else { u8::MAX }),
("d draft summary", if drafting { u8::MAX } else { 2 }),
(if summary { "e edit summary" } else { "c summary" }, 3),
("w fix in a worktree", 4),
("esc cancel", 0),
];
let render = |limit: u8| {
let shown: Vec<&str> =
keys.iter().filter(|(_, rank)| *rank <= limit).map(|(key, _)| *key).collect();
format!(" {} ", shown.join(" · "))
};
(0..=4).rev().map(render).find(|text| text.width() <= room).unwrap_or_else(|| render(0))
}
fn pinned_head(app: &App) -> String {
match app.guided_review.as_ref().map(|review| &review.source.base) {
Some(luxe_core::guided_review::ReviewBase::PullRequest { head_oid, .. }) => {
head_oid.chars().take(7).collect()
}
_ => String::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The pane's last row can reach the bottom, and a scroll past it stops there.
#[test]
fn scrolling_stops_at_the_last_row() {
let lines: Vec<Line<'static>> = (0..10).map(|n| Line::from(n.to_string())).collect();
assert_eq!(scrolled(lines.clone(), 0, 4)[0].to_string(), "0");
assert_eq!(scrolled(lines.clone(), 3, 4)[0].to_string(), "3");
assert_eq!(scrolled(lines.clone(), 99, 4)[0].to_string(), "6", "clamped to the end");
assert_eq!(scrolled(lines, 5, 20)[0].to_string(), "0", "nothing to scroll when it fits");
}
}

View File

@@ -0,0 +1,144 @@
//! Post items — what the post will carry, where each item lands on GitHub, and the list of them.
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use luxe_core::guided_review::{BodyReason, DiffSide, FindingId, Placement, PostPlan};
use ratatui::text::{Line, Span};
/// One thing the review will post: the review's own text, or a comment on a line.
pub(super) struct Item {
/// What the pane heads it with: `Summary`, or where on the diff it lands
pub(super) place: String,
/// Where a line comment sits, `None` for the summary
pub(super) on: Option<OnLines>,
/// The text GitHub will show, as markdown; empty for a review with no words of its own
pub(super) body: String,
}
/// The lines a comment sits on.
pub(super) struct OnLines {
pub(super) path: String,
pub(super) side: DiffSide,
pub(super) start: u32,
pub(super) end: u32,
}
impl OnLines {
fn of(place: &Placement) -> Option<Self> {
match place {
Placement::Line { path, line, side } => {
Some(Self { path: path.clone(), side: *side, start: *line, end: *line })
}
Placement::Lines { path, start, end, side } => {
Some(Self { path: path.clone(), side: *side, start: *start, end: *end })
}
Placement::Body(_) => None,
}
}
/// What the list calls it under its file's name: `line 13`, `lines 12–14 (before)`.
fn short(&self) -> String {
let before = if self.side == DiffSide::Old { " (before)" } else { "" };
if self.start == self.end {
format!("line {}{before}", self.end)
} else {
format!("lines {}–{}{before}", self.start, self.end)
}
}
}
/// The review, then each comment on a line, grouped by file the way GitHub lists them: files in
/// the order their first comment was written, and down each file by line.
///
/// A comment placed in the review's body is part of the review's text on GitHub, under a heading
/// that says where it was written, so it is read there rather than listed a second time.
pub(super) fn items(app: &App, plan: &PostPlan) -> Vec<Item> {
let body_of = |id: &FindingId| {
app.review
.session()
.and_then(|session| session.findings.iter().find(|finding| &finding.id == id))
.map_or_else(String::new, |finding| finding.body.trim().to_owned())
};
let mut lines: Vec<Item> = plan
.placed
.iter()
.filter_map(|placed| {
let on = OnLines::of(&placed.place)?;
Some(Item {
place: place(&placed.place),
on: Some(on),
body: body_of(&placed.finding_id),
})
})
.collect();
let mut files: Vec<String> = Vec::new();
for item in &lines {
let path = &item.on.as_ref().expect("a line comment").path;
if !files.contains(path) {
files.push(path.clone());
}
}
lines.sort_by_key(|item| {
let on = item.on.as_ref().expect("a line comment");
(files.iter().position(|file| file == &on.path), on.start)
});
let summary =
Item { place: "Summary".to_owned(), on: None, body: plan.review.body.trim().to_owned() };
std::iter::once(summary).chain(lines).collect()
}
/// Where a comment lands, as a reader of GitHub's page would look for it.
fn place(place: &Placement) -> String {
let before = |side: &DiffSide| if *side == DiffSide::Old { " (before)" } else { "" };
match place {
Placement::Line { path, line, side } => format!("{path}:{line}{}", before(side)),
Placement::Lines { path, start, end, side } => {
format!("{path}:{start}–{end}{}", before(side))
}
Placement::Body(BodyReason::WholeReview) => "on the review".to_owned(),
Placement::Body(BodyReason::Chapter(title)) => format!("under “{title}”"),
Placement::Body(BodyReason::OffDiff { path, lines }) => {
format!("{path}:{lines}, outside GitHub's diff")
}
}
}
/// The list's rows: the summary, then each file's name over the comments on it. Each row carries
/// the item it selects, or `None` for a file's name, which selects nothing.
pub(super) fn list_lines(
app: &App,
items: &[Item],
selected: usize,
width: usize,
) -> Vec<(Option<usize>, Line<'static>)> {
let styles = &app.theme_styles;
let room = width.saturating_sub(crate::widgets::SELECTION_FRAME);
let mut rows = Vec::new();
let mut file: Option<&str> = None;
for (index, item) in items.iter().enumerate() {
let label = match &item.on {
None => item.place.clone(),
Some(on) => {
if file != Some(on.path.as_str()) {
file = Some(on.path.as_str());
let name = clip_terminal_cells_ellipsis(&on.path, room);
// In the column a selected row's label starts in
let name = format!("{}{name}", " ".repeat(crate::widgets::SELECTION_INSET));
rows.push((None, Line::from(Span::styled(name, styles.muted))));
}
format!(" {}", on.short())
}
};
let label = clip_terminal_cells_ellipsis(&label, room);
rows.push((
Some(index),
crate::widgets::selection_row(
vec![Span::styled(label, styles.text)],
width,
index == selected,
styles,
),
));
}
rows
}

View File

@@ -0,0 +1,135 @@
//! Post preview — the selected item as GitHub will show it: its Markdown and the code it is on.
use super::items::{Item, OnLines};
use crate::app::App;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use luxe_core::guided_review::DiffSide;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// Diff lines above a line comment, its own included, the way GitHub shows a comment's context.
const EXCERPT_LINES: usize = 4;
/// The most lines of a comment on a run of lines the excerpt shows, ending at the run's last.
const EXCERPT_MOST: usize = 8;
/// The selected item's text as rows of `width`: where it goes, the diff it sits under when it sits
/// on lines, then the words.
pub(super) fn pane_lines(app: &App, item: &Item, width: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines =
vec![Line::from(Span::styled(item.place.clone(), styles.accent)), Line::from("")];
if let Some(on) = &item.on {
let excerpt = excerpt(app, on, width);
if !excerpt.is_empty() {
lines.extend(excerpt);
lines.push(Line::from(""));
}
}
let post = app.guided_review_workspace.github_post.as_ref();
let summary = item.on.is_none();
let drafting = post.and_then(|post| post.drafting_since).filter(|_| summary);
if let Some(since) = drafting {
lines.push(drafting_line(app, since));
if !item.body.is_empty() {
lines.push(Line::from(""));
}
}
if item.body.is_empty() {
if drafting.is_none() {
lines.push(Line::from(Span::styled("No summary · c write one", styles.dim)));
}
} else {
lines.extend(crate::markdown::render_markdown(&item.body, styles));
}
let mut lines: Vec<Line<'static>> =
lines.iter().flat_map(|line| crate::widgets::wrap_line(line, width)).collect();
if let Some(note) = post.and_then(|post| post.draft_note.as_deref()).filter(|_| summary) {
lines.push(Line::from(""));
lines.extend(crate::github_detail::draft_note_lines(note, width, styles));
}
lines
}
/// The wait for a drafted summary, drawn where the summary will land: who is writing it, and a
/// count, because a minute of a still line reads as a hang.
fn drafting_line(app: &App, since: std::time::Instant) -> Line<'static> {
let styles = &app.theme_styles;
let model = match app.status.model.trim() {
"" => "The agent",
model => model,
};
Line::from(vec![
Span::styled(
format!("{} drafting ", crate::statusline::spinner(app.guided_review_workspace.frame)),
styles.accent,
),
Span::styled(
format!(
"\u{b7} {model} is drafting the review summary \u{b7} {}",
crate::statusline::format_elapsed_compact(
app.frame_now().saturating_duration_since(since)
)
),
styles.muted,
),
])
}
/// The diff a line comment sits under, as GitHub shows it: up to [`EXCERPT_LINES`] lines ending at
/// the comment's last, numbered and colored the way the review draws them, with its own lines
/// marked. Empty when the lines are not in the review, which leaves the heading to say where.
fn excerpt(app: &App, on: &OnLines, width: usize) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let number = |line: &luxe_core::guided_review::ReviewLine| match on.side {
DiffSide::Old => line.old_line,
DiffSide::New => line.new_line,
};
let Some(hunk_lines) = app.guided_review.as_ref().and_then(|review| {
let file = review.files.iter().find(|file| {
let path = match on.side {
DiffSide::Old => file.old_path.as_deref(),
DiffSide::New => file.new_path.as_deref(),
};
path.is_some_and(|path| luxe_core::paths::display(path) == on.path)
})?;
file.hunks.iter().find_map(|hunk| {
let end = hunk.lines.iter().position(|line| number(line) == Some(on.end))?;
let start = hunk.lines.iter().position(|line| number(line) == Some(on.start));
let from = start
.unwrap_or(end)
.min(end.saturating_sub(EXCERPT_LINES - 1))
.max((end + 1).saturating_sub(EXCERPT_MOST));
Some(&hunk.lines[from..=end])
})
}) else {
return Vec::new();
};
let digits = hunk_lines
.iter()
.filter_map(|line| line.new_line.or(line.old_line))
.max()
.map_or(1, |most| most.to_string().len());
hunk_lines
.iter()
.map(|line| {
use luxe_core::guided_review::ReviewLineKind;
let (sign, fill) = match line.kind {
ReviewLineKind::Addition => ("+", styles.diff_add_bg),
ReviewLineKind::Deletion => ("-", styles.diff_del_bg),
_ => (" ", Style::default()),
};
let commented = number(line).is_some_and(|n| (on.start..=on.end).contains(&n));
let shown = line.new_line.or(line.old_line).map_or_else(String::new, |n| n.to_string());
let lead = format!("{shown:>digits$} {sign} ");
let room = width.saturating_sub(1 + lead.chars().count());
let text = clip_terminal_cells_ellipsis(&line.text.replace('\t', " "), room);
let pad = room.saturating_sub(unicode_width::UnicodeWidthStr::width(text.as_str()));
Line::from(vec![
Span::styled(if commented { "▎" } else { " " }, styles.accent),
Span::styled(lead, styles.muted.patch(fill)),
Span::styled(format!("{text}{}", " ".repeat(pad)), styles.text.patch(fill)),
])
})
.collect()
}

View File

@@ -0,0 +1,95 @@
//! Review load states — what the surface says before there is a diff to show: too small, loading,
//! empty, or failed.
use crate::app::App;
use crate::guided_review::GuidedReviewLoadState;
use luxe_core::guided_review::ReviewTarget;
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
text::{Line, Span},
widgets::{Paragraph, Wrap},
Frame,
};
pub(super) fn render_minimum_size(frame: &mut Frame, area: Rect, app: &App) {
frame.render_widget(
Paragraph::new(vec![
Line::from(Span::styled("Review needs 40 × 5 cells", app.theme_styles.error)),
Line::from(Span::styled("Resize, or esc back to chat", app.theme_styles.muted)),
])
.alignment(Alignment::Center),
area,
);
}
pub(super) fn render_body(frame: &mut Frame, area: Rect, app: &App) {
let (headline, detail, style) = match &app.guided_review_workspace.load_state {
GuidedReviewLoadState::Idle => (
"Ready to open a review".into(),
"Choose a source to capture an immutable review revision.".into(),
app.theme_styles.text,
),
GuidedReviewLoadState::Loading { target: ReviewTarget::PullRequest { number, .. } } => (
format!("Fetching pull request #{number}"),
"Reading it from GitHub and pinning the exact revision. Your working tree is not touched."
.into(),
app.theme_styles.accent,
),
GuidedReviewLoadState::Loading { target } => {
let detail = if app.guided_review.is_some() {
"Refreshing the source without replacing the pinned revision you are reading."
} else {
"Capturing a complete immutable source before presenting its diff."
};
(
format!("Capturing {}", source_label(target)),
detail.into(),
app.theme_styles.accent,
)
}
GuidedReviewLoadState::Ready if app.guided_review.as_ref().is_some_and(|review| review.files.is_empty()) => (
"No changes to review".into(),
"This captured source contains no reviewable changes. Choose another source or return to the conversation.".into(),
app.theme_styles.success,
),
GuidedReviewLoadState::Ready => (
"Review ready".into(),
"Preparing the selected immutable revision for Guided Review.".into(),
app.theme_styles.success,
),
GuidedReviewLoadState::Failed { error, .. } => (
"Guided Review could not load".into(),
error.message.clone(),
app.theme_styles.error,
),
};
let content = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(40), Constraint::Length(1), Constraint::Length(2)])
.split(area);
frame.render_widget(
Paragraph::new(Line::from(Span::styled(headline, style))).alignment(Alignment::Center),
content[1],
);
frame.render_widget(
Paragraph::new(detail)
.style(app.theme_styles.muted)
.alignment(Alignment::Center)
.wrap(Wrap { trim: true }),
content[2],
);
}
pub(super) fn source_label(target: &ReviewTarget) -> String {
match target {
ReviewTarget::WorkingTree => "working tree".into(),
ReviewTarget::LastTurn { .. } => "last turn".into(),
ReviewTarget::Base { reference } => format!("base {reference}"),
ReviewTarget::Commit { oid } => format!("commit {oid}"),
ReviewTarget::PullRequest { number, repository: None } => format!("pull request #{number}"),
ReviewTarget::PullRequest { number, repository: Some(repository) } => {
format!("pull request {repository}#{number}")
}
ReviewTarget::OwnPullRequest { number } => format!("pull request #{number}"),
}
}

View File

@@ -0,0 +1,201 @@
//! The narration band — this change's own sentence, above the diff that shows it.
//!
//! What the reader is looking at, and what it does: `path · symbol · hunk 2 of 2`, the guide's
//! sentence for *this* hunk, and the graph facts that change a judgement about the file. It changes
//! on every step, which is what makes advancing a visible event rather than a redraw of the same
//! frame with different code in it.
//!
//! The chapter's own prose is deliberately absent: it lives in the guide pane, beside the file list
//! it introduces. Two granularities, one home each — saying the chapter's rationale here as well
//! would spend the diff's rows repeating what is already on screen.
//!
//! Bounded on purpose. `z` folds it away for a reviewer who wants every row of code.
use crate::app::App;
use luxe_core::guided_review::{GuidedReview, ReviewChapter, ReviewItemRef};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
/// Rows this item's sentence may occupy before it is clipped.
const MAX_ITEM_ROWS: u16 = 3;
/// The narration for the current position, or `None` when there is nothing to say.
pub(super) fn narration_lines(
app: &App,
review: &GuidedReview,
width: u16,
) -> Option<Vec<Line<'static>>> {
if !app.guided_review_workspace.narration_visible || width < 40 {
return None;
}
let chapter = current_chapter(app, review)?;
let styles = &app.theme_styles;
let mut lines: Vec<Line<'static>> = Vec::new();
match current_item_note(app, review, chapter) {
Some((heading, note)) => {
lines.push(Line::from(item_heading_spans(heading, styles)));
lines.extend(wrapped(&note, width, styles.text, MAX_ITEM_ROWS));
}
None => {
let heading = item_heading(app, review)?;
lines.push(Line::from(item_heading_spans(heading, styles)));
}
}
lines.extend(current_file_attention_lines(app, review, styles));
(!lines.is_empty()).then_some(lines)
}
/// `path symbol hunk 2 of 3` — what the diff below belongs to.
fn item_heading_spans(
heading: ItemHeading,
styles: &crate::theme::styles::ThemeStyles,
) -> Vec<Span<'static>> {
let mut spans = vec![Span::styled(heading.path, styles.info)];
if let Some(symbol) = heading.symbol {
spans.push(Span::styled(" ", styles.dim));
spans.push(Span::styled(symbol, styles.text.add_modifier(ratatui::style::Modifier::BOLD)));
}
if let Some((at, total)) = heading.hunk {
spans.push(Span::styled(format!(" hunk {at} of {total}"), styles.muted));
}
spans
}
/// What the heading names.
struct ItemHeading {
/// Project-relative path of the file being read.
path: String,
/// The symbol the hunk sits in, when the diff named one.
symbol: Option<String>,
/// `(at, total)` hunks in this file, when the cursor is on one.
hunk: Option<(usize, usize)>,
}
/// The heading for the current position, or `None` when there is no file to name.
fn item_heading(app: &App, review: &GuidedReview) -> Option<ItemHeading> {
let position = &app.guided_review_workspace.position;
let file =
position.file_id.as_ref().and_then(|id| review.files.iter().find(|file| &file.id == id))?;
let path = file
.new_path
.as_deref()
.or(file.old_path.as_deref())
.map(|path| path.display().to_string())?;
let index =
position.hunk_id.as_ref().and_then(|id| file.hunks.iter().position(|hunk| &hunk.id == id));
let symbol = index.and_then(|index| file.hunks.get(index)).and_then(|hunk| {
hunk.symbol.as_ref().and_then(|symbol| symbol.name.clone()).or_else(|| hunk.heading.clone())
});
Some(ItemHeading { path, symbol, hunk: index.map(|index| (index + 1, file.hunks.len())) })
}
/// What the harness noticed about the file on screen, said where the reviewer is already reading.
///
/// The Brief ranks these too, but a list you consult before starting is not where a concern gets
/// resolved — here it sits under the prose that should have explained it, next to the diff that
/// shows it, one `c` away from becoming a comment the agent has to answer.
fn current_file_attention_lines(
app: &App,
review: &GuidedReview,
styles: &crate::theme::styles::ThemeStyles,
) -> Vec<Line<'static>> {
let Some(path) = current_path(app, review) else {
return Vec::new();
};
let mut signals: Vec<&luxe_core::guided_review::AttentionSignal> = app
.review
.flags
.iter()
.filter(|signal| signal.path.as_deref() == Some(path.as_str()))
.collect();
// one line per reason: the flags keep a signal per flagged line, and two credential lines in
// one file are one thing to say
signals.dedup_by(|left, right| left.kind == right.kind && left.detail == right.detail);
signals
.into_iter()
.take(MAX_ATTENTION_ROWS)
.map(|signal| {
// Strip the path the heading right above already carries; what is left continues it.
let detail = signal
.detail
.strip_prefix(&format!("{path}: "))
.or_else(|| signal.detail.strip_prefix(&format!("{path} ")))
.unwrap_or(&signal.detail)
.to_owned();
Line::from(vec![
Span::styled(" · ", styles.warning),
Span::styled(detail, styles.warning),
])
})
.collect()
}
/// Attention rows one section's file may add before the prose stops being prose.
const MAX_ATTENTION_ROWS: usize = 2;
/// The project-relative path of the file being read.
fn current_path(app: &App, review: &GuidedReview) -> Option<String> {
let file = app
.guided_review_workspace
.position
.file_id
.as_ref()
.and_then(|id| review.files.iter().find(|file| &file.id == id))?;
file.new_path.as_deref().or(file.old_path.as_deref()).map(|path| path.display().to_string())
}
/// The chapter the narration describes: the one the cursor is in.
fn current_chapter<'a>(app: &App, review: &'a GuidedReview) -> Option<&'a ReviewChapter> {
let selected = app.guided_review_workspace.position.chapter_id.as_ref()?;
review.chapters.iter().find(|chapter| &chapter.id == selected)
}
/// `(file · symbol, note)` for the selected item, when the guide wrote a sentence for it.
fn current_item_note(
app: &App,
review: &GuidedReview,
chapter: &ReviewChapter,
) -> Option<(ItemHeading, String)> {
let position = &app.guided_review_workspace.position;
let file =
position.file_id.as_ref().and_then(|id| review.files.iter().find(|file| &file.id == id))?;
let note = match position.hunk_id.as_ref() {
Some(hunk_id) => chapter.note_for_hunk(hunk_id),
None => chapter.note_for(&ReviewItemRef::File(file.id.clone())),
}?;
Some((item_heading(app, review)?, note.to_owned()))
}
/// Soft-wraps prose to `width`, clipped to `max_rows` with an ellipsis on the last kept row.
fn wrapped(text: &str, width: u16, style: Style, max_rows: u16) -> Vec<Line<'static>> {
let width = usize::from(width).max(20);
let mut rows: Vec<String> = Vec::new();
let mut current = String::new();
for word in text.split_whitespace() {
let candidate =
if current.is_empty() { word.to_owned() } else { format!("{current} {word}") };
if candidate.width() > width && !current.is_empty() {
rows.push(std::mem::take(&mut current));
current = word.to_owned();
} else {
current = candidate;
}
}
if !current.is_empty() {
rows.push(current);
}
let clipped = rows.len() > usize::from(max_rows);
rows.truncate(usize::from(max_rows));
if clipped {
if let Some(last) = rows.last_mut() {
let budget = width.saturating_sub(1);
while last.width() > budget {
last.pop();
}
last.push('…');
}
}
rows.into_iter().map(|row| Line::from(Span::styled(row, style))).collect()
}

View File

@@ -0,0 +1,35 @@
//! Guided Review overlays — findings drawer, finish/confirm dialogs, finding details,
//! draft composer, outline, help, and the source picker.
//!
//! Two overlay classes (design-tui-polish-and-mouse §A3, D5):
//! - **Modal** (source picker, outline, help, finding details, draft composer, finish review):
//! a centered popup rendered over a **dimmed backdrop** (the caller in `super::render` mutes
//! the surface first) so it reads as focused, not as clipping the text beneath it.
//! - **Drawer** (the findings panel): a non-modal right-edge companion with **no backdrop** —
//! the surface stays bright so the reviewer keeps the diff in view while triaging findings.
mod evidence;
mod finding;
mod finish;
mod help;
use crate::app::App;
pub(super) use evidence::render_finding_fix;
pub(super) use finding::{
anchor_summary, chapter_kind_label, finding_state_glyph, finding_state_label,
render_finding_details, render_finding_draft,
};
#[cfg(test)]
use finish::finish_carries;
pub(super) use finish::{render_commit_preview, render_finish_review};
pub(super) use help::{render_help, render_source_picker};
use ratatui::widgets::{Block, Padding};
/// A review overlay panel: the shared [`crate::widgets::titled_panel`] chrome (rounded accent
/// frame, accent glyph, bold label) plus a 1-col left pad so text isn't flush against the frame.
pub(super) fn overlay_block<'a>(app: &App, glyph: &str, label: &str) -> Block<'a> {
crate::widgets::titled_panel(glyph, label, &app.theme_styles).padding(Padding::left(1))
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,210 @@
//! Finding evidence — the fix dialog, with the source where the finding was and where it is now.
use super::finding::anchor_summary;
use super::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
/// What changed at a comment's anchor since it was submitted, so `NeedsVerification` is checked
/// against evidence rather than trust.
///
/// A model saying "fixed" is a claim. Without this the only way to test it was to refresh the whole
/// review and hunt for the line by hand, which in practice meant pressing `r` and believing it.
pub(in crate::view::guided_review) fn render_finding_fix(frame: &mut Frame, area: Rect, app: &App) {
let Some((finding, submitted)) = app.review.session().and_then(|session| {
let finding = app
.guided_review_workspace
.selected_finding_id
.as_ref()
.and_then(|id| session.findings.iter().find(|finding| &finding.id == id))?;
let submitted = session
.submissions
.iter()
.rev()
.flat_map(|submission| &submission.findings)
.find(|snapshot| snapshot.finding_id == finding.id);
Some((finding, submitted))
}) else {
return;
};
let width = area.width.saturating_sub(4).clamp(48, 96);
let height = area.height.saturating_sub(4).clamp(12, 22);
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
let row_width = usize::from(width.saturating_sub(4));
let mut lines = vec![
Line::from(Span::styled(finding.title.clone(), app.theme_styles.accent)),
Line::from(Span::styled(anchor_summary(app, &finding.anchor), app.theme_styles.muted)),
Line::from(""),
];
match submitted.and_then(|snapshot| snapshot.evidence.source.as_deref()) {
Some(source) => {
lines.push(Line::from(Span::styled("When you commented", app.theme_styles.muted)));
lines.push(Line::from(Span::styled(
format!(" {}", clip_terminal_cells_ellipsis(source.trim(), row_width)),
app.theme_styles.error,
)));
}
None => lines.push(Line::from(Span::styled(
"This comment was not anchored to a source line.",
app.theme_styles.muted,
))),
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled("Now", app.theme_styles.muted)));
let submitted_source = submitted.and_then(|snapshot| snapshot.evidence.source.as_deref());
match current_anchor_lines(app, finding, row_width) {
Some(current) if !current.is_empty() => lines.extend(current),
// The anchor is gone. Remediation usually *moves* code — renames a function, extracts a
// helper — so "refresh and look for it yourself" abandons the reviewer at exactly the
// moment the tool should help. Look for the line they commented on instead.
_ => lines.extend(relocated_lines(app, submitted_source, row_width)),
}
if let Some(agent) = finding
.thread
.iter()
.rev()
.find(|entry| entry.author == luxe_core::guided_review::FindingMessageAuthor::Agent)
{
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"Agent report — a claim, not proof",
app.theme_styles.muted,
)));
for line in agent.body.lines().take(3) {
lines.push(Line::from(Span::styled(
format!(" {}", clip_terminal_cells_ellipsis(line, row_width)),
app.theme_styles.text,
)));
}
}
let block = overlay_block(app, Icon::Evidence.glyph(), "What changed here");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(
frame,
block,
popup,
"r verify and resolve · c reply · esc close",
None,
&app.theme_styles,
);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), body);
}
/// Where the commented-on source went, when its anchor no longer resolves.
fn relocated_lines(
app: &App,
submitted_source: Option<&str>,
row_width: usize,
) -> Vec<Line<'static>> {
let needle = submitted_source.map(str::trim).filter(|text| !text.is_empty());
let found = needle.and_then(|needle| {
let review = app.guided_review.as_ref()?;
review.files.iter().find_map(|file| {
let hunk = file
.hunks
.iter()
.find(|hunk| hunk.lines.iter().any(|line| line.text.trim() == needle))?;
let path = file
.new_path
.as_deref()
.or(file.old_path.as_deref())
.map_or_else(|| "(unknown path)".to_string(), |path| path.display().to_string());
Some((path, hunk.heading.clone()))
})
});
match found {
Some((path, heading)) => {
let location = match heading {
Some(heading) => format!("{path} · {heading}"),
None => path,
};
vec![
Line::from(Span::styled(
" the anchor is gone, but that line now lives at",
app.theme_styles.warning,
)),
Line::from(Span::styled(
format!(" {}", clip_terminal_cells_ellipsis(&location, row_width)),
app.theme_styles.info,
)),
]
}
None if needle.is_some() => vec![Line::from(Span::styled(
" that line is gone from this revision entirely",
app.theme_styles.warning,
))],
None => vec![Line::from(Span::styled(
" this anchor no longer resolves — refresh the review (ctrl+r)",
app.theme_styles.warning,
))],
}
}
/// The anchored hunk as the current revision has it, or `None` when the anchor is gone.
fn current_anchor_lines(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
row_width: usize,
) -> Option<Vec<Line<'static>>> {
use luxe_core::guided_review::{DiffSide, FindingAnchor, ReviewLineKind};
let review = app.guided_review.as_ref()?;
let (file_id, hunk_id, side_line) = match &finding.anchor {
FindingAnchor::Line { file_id, hunk_id, side, line, .. } => {
(file_id, hunk_id, Some((*side, *line)))
}
FindingAnchor::Hunk { file_id, hunk_id } => (file_id, hunk_id, None),
_ => return None,
};
let file = review.files.iter().find(|file| &file.id == file_id)?;
let hunk = file.hunks.iter().find(|hunk| &hunk.id == hunk_id)?;
// Center a short window on the anchored line so the fix is readable without the whole hunk.
let anchor_index = side_line.and_then(|(side, line)| {
hunk.lines.iter().position(|source| match side {
DiffSide::Old => source.old_line == Some(line),
DiffSide::New => source.new_line == Some(line),
})
});
let start = anchor_index.map_or(0, |index| index.saturating_sub(3));
let window = hunk.lines.iter().skip(start).take(8);
Some(
window
.enumerate()
.map(|(offset, line)| {
let marker = match line.kind {
ReviewLineKind::Addition => '+',
ReviewLineKind::Deletion => '-',
_ => ' ',
};
let style = match line.kind {
ReviewLineKind::Addition => app.theme_styles.success,
ReviewLineKind::Deletion => app.theme_styles.error,
_ => app.theme_styles.text,
};
let cursor = if anchor_index == Some(start + offset) { "›" } else { " " };
Line::from(Span::styled(
format!(
"{cursor} {marker}{}",
clip_terminal_cells_ellipsis(
&crate::tabstop::display_text(&line.text),
row_width.saturating_sub(3),
)
),
style,
))
})
.collect(),
)
}

View File

@@ -0,0 +1,377 @@
//! Finding dialogs — a finding's details, and the composer that drafts one.
use super::super::context::submission_dispatch_label;
use super::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
pub(in crate::view::guided_review) fn render_finding_details(
frame: &mut Frame,
area: Rect,
app: &App,
) {
let Some((finding, revision, submission_dispatch)) = selected_finding_snapshot(app) else {
// nothing to draw, so nothing is hidden: with no selection its keys do nothing anyway
app.guided_review_workspace.settle_preview(true);
return;
};
let width = area.width.saturating_sub(4).clamp(36, 72).min(area.width);
let height = area.height.saturating_sub(4).min(18);
let Some(popup) = crate::widgets::fit_review_preview(frame, area, (width, height, 10), app)
else {
return;
};
let mut lines = finding_details_rows(app, finding, revision, submission_dispatch);
if !finding.thread.is_empty() {
lines.extend(finding_thread_rows(app, finding, width));
}
let footer = match finding.state {
luxe_core::guided_review::FindingState::Draft => " e edit · x delete · esc close ",
luxe_core::guided_review::FindingState::Stale => " alt+r re-anchor and verify · esc close ",
luxe_core::guided_review::FindingState::Resolved => " r reopen · esc close ",
luxe_core::guided_review::FindingState::Open => " r resolve · esc close ",
luxe_core::guided_review::FindingState::NeedsVerification => {
" r verify and resolve · esc close "
}
};
let block = overlay_block(app, Icon::Evidence.glyph(), "The exchange");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(frame, block, popup, footer, None, &app.theme_styles);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), body);
}
/// The selected finding, the revision its session pinned, and how the last submission carrying it
/// was dispatched.
fn selected_finding_snapshot(
app: &App,
) -> Option<(
&luxe_core::guided_review::ReviewFinding,
&str,
Option<luxe_core::guided_review::SubmissionDispatch>,
)> {
app.review.session().and_then(|session| {
app.guided_review_workspace
.selected_finding_id
.as_ref()
.and_then(|id| session.findings.iter().find(|finding| &finding.id == id))
.map(|finding| {
let submission_dispatch = session
.submissions
.iter()
.rev()
.find(|submission| {
submission.findings.iter().any(|snapshot| snapshot.finding_id == finding.id)
})
.map(|submission| submission.dispatch);
(finding, session.source.content_digest.as_str(), submission_dispatch)
})
})
}
/// A finding's title, state, anchor, the revision it is against, its words and its suggested fix.
fn finding_details_rows<'a>(
app: &App,
finding: &'a luxe_core::guided_review::ReviewFinding,
revision: &str,
submission_dispatch: Option<luxe_core::guided_review::SubmissionDispatch>,
) -> Vec<Line<'a>> {
let mut lines = vec![
Line::from(Span::styled(&finding.title, app.theme_styles.accent)),
Line::from(Span::styled(
match finding.severity {
luxe_core::guided_review::FindingSeverity::Question => {
format!("question · {}", finding_state_label(finding))
}
_ => finding_state_label(finding).to_owned(),
},
app.theme_styles.muted,
)),
Line::from(Span::styled(anchor_summary(app, &finding.anchor), app.theme_styles.text)),
Line::from(vec![
Span::styled(
submission_dispatch.map_or_else(
|| "Pinned revision: ".to_owned(),
|dispatch| {
format!("Submitted snapshot ({}): ", submission_dispatch_label(dispatch))
},
),
app.theme_styles.muted,
),
Span::styled(clip_terminal_cells(revision, 0, 16), app.theme_styles.text),
]),
Line::from(""),
Line::from(finding.body.as_str()),
];
if let Some(proposed_fix) = finding.proposed_fix.as_deref() {
lines.extend([
Line::from(""),
Line::from(Span::styled("Suggested fix", app.theme_styles.muted)),
Line::from(proposed_fix),
]);
}
lines
}
/// The exchange in order, attributed, each message cut to two lines.
///
/// Showing only the agent's latest note hid the reviewer's own replies — the half that makes this
/// a conversation rather than a verdict.
fn finding_thread_rows(
app: &App,
finding: &luxe_core::guided_review::ReviewFinding,
width: u16,
) -> Vec<Line<'static>> {
let mut lines = vec![
Line::from(""),
Line::from(Span::styled(
"Thread — an agent report is a claim; reviewer verification required",
app.theme_styles.muted,
)),
];
let evidence_width = usize::from(width.saturating_sub(7));
for entry in &finding.thread {
let style = match entry.author {
luxe_core::guided_review::FindingMessageAuthor::Reviewer => app.theme_styles.text,
_ => app.theme_styles.info,
};
lines.push(Line::from(Span::styled(
format!("{}:", entry.author.label()),
app.theme_styles.muted,
)));
let mut body = entry.body.lines();
for line in body.by_ref().take(2) {
lines.push(Line::from(Span::styled(
clip_terminal_cells(line, 0, evidence_width),
style,
)));
}
if body.next().is_some() {
lines.push(Line::from(Span::styled(" …", app.theme_styles.muted)));
}
}
lines
}
pub(in crate::view::guided_review) fn finding_state_glyph(
finding: &luxe_core::guided_review::ReviewFinding,
) -> &'static str {
use luxe_core::guided_review::{FindingSeverity, FindingState};
match finding.state {
FindingState::Resolved => crate::glyphs::Mark::Yes.glyph(),
FindingState::Stale => "~",
FindingState::NeedsVerification => "?",
FindingState::Draft => "○",
FindingState::Open => match finding.severity {
FindingSeverity::Question => "?",
_ => "!",
},
}
}
pub(in crate::view::guided_review) fn finding_state_label(
finding: &luxe_core::guided_review::ReviewFinding,
) -> &'static str {
use luxe_core::guided_review::FindingState;
if finding.github_thread.as_ref().is_some_and(|thread| thread.resolved) {
return "resolved on GitHub";
}
match finding.state {
FindingState::Draft | FindingState::Open if finding.posted.is_some() => "on GitHub",
FindingState::Draft => "draft",
FindingState::Open => "open",
FindingState::NeedsVerification => "to verify",
FindingState::Resolved => "verified",
FindingState::Stale => "stale",
}
}
pub(in crate::view::guided_review) fn render_finding_draft(
frame: &mut Frame,
area: Rect,
app: &App,
draft: &crate::guided_review::FindingDraft,
) {
let anchor = anchor_summary(app, &draft.anchor);
let editing_draft = app.guided_review_workspace.editing_finding_id.is_some();
let (asking, fixing) = finding_draft_intent(app, draft);
// The location, unlabeled. "Anchor:" named the mechanism holding the comment in place, which
// is the reviewer's least pressing question about a box that just opened on the line they were
// already looking at.
let head = vec![
Line::from(Span::styled(anchor, app.theme_styles.muted)),
Line::from(""),
Line::from(Span::styled(
if asking { "Question:" } else { "Comment:" },
app.theme_styles.muted,
)),
];
let mut tail = Vec::new();
if fixing {
tail.push(Line::from(Span::styled(
"Sends the question, its answer and this to the agent as a fix request.",
app.theme_styles.muted,
)));
}
if let Some(error) = draft.error.as_deref() {
tail.push(Line::from(Span::styled(error.to_string(), app.theme_styles.error)));
}
if editing_draft {
tail.push(Line::from(Span::styled(
"Draft edit only — submitted feedback stays immutable.",
app.theme_styles.muted,
)));
}
// Sized after the rows exist, not before: a fixed box left half of itself empty under a short
// comment. The field grows with what is written, up to a point, and scrolls past it.
let width = area.width.min(88);
let inner_width = width.saturating_sub(3).max(1);
let field_rows = crate::widgets::text_field::rows(draft.editor(), inner_width).clamp(3, 12);
let head_rows = crate::widgets::text_field::wrapped_rows(&head, inner_width);
let tail_rows = crate::widgets::text_field::wrapped_rows(&tail, inner_width);
let height =
(head_rows + field_rows + tail_rows + 2 + crate::widgets::FOOTER_ROWS).min(area.height);
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
let (title, hint) = finding_draft_chrome(draft, editing_draft, asking, fixing);
let block = overlay_block(app, Icon::Compose.glyph(), title);
frame.render_widget(Clear, popup);
let inner = crate::widgets::render_footed(frame, block, popup, hint, None, &app.theme_styles);
let [head_area, field_area, tail_area] = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Length(head_rows),
ratatui::layout::Constraint::Min(1),
ratatui::layout::Constraint::Length(tail_rows),
])
.areas(inner);
frame.render_widget(Paragraph::new(head).wrap(Wrap { trim: true }), head_area);
app.guided_review_workspace.field_width.set(field_area.width);
crate::widgets::text_field::render(frame, field_area, draft.editor(), &app.theme_styles);
frame.render_widget(Paragraph::new(tail).wrap(Wrap { trim: true }), tail_area);
}
/// Whether the draft asks the agent a question, and whether, as a comment on a question's thread,
/// it asks for the fix.
fn finding_draft_intent(app: &App, draft: &crate::guided_review::FindingDraft) -> (bool, bool) {
// No severity is on screen, so the title and the field label alone say which verb opened the
// box — and they have to, because a question and a comment do different things to the agent
// and leave at different times.
let asking = draft.severity == luxe_core::guided_review::FindingSeverity::Question;
// A comment on a question's thread asks for the fix, and takes the question and its answer
let fixing = !asking
&& draft.reply_to.as_ref().is_some_and(|id| {
app.review.session().is_some_and(|session| {
session.findings.iter().any(|finding| {
&finding.id == id
&& finding.severity == luxe_core::guided_review::FindingSeverity::Question
})
})
});
(asking, fixing)
}
/// The composer's title and its footer's keys, named for the verb that opened it.
fn finding_draft_chrome(
draft: &crate::guided_review::FindingDraft,
editing_draft: bool,
asking: bool,
fixing: bool,
) -> (&'static str, &'static str) {
// A comment on the review as a whole is what a posted review carries as its summary
let summary = draft.anchor == luxe_core::guided_review::FindingAnchor::Review;
let title = match (editing_draft, asking, summary) {
_ if fixing => "Ask for a fix",
(true, _, _) => "Edit comment",
(false, true, _) => "Ask the agent about this",
(false, false, true) => "Review summary",
(false, false, false) => "Comment on this",
};
// A question leaves the moment it is saved; a comment waits to be sent. That is the one thing
// about the two verbs a reviewer cannot infer from the box in front of them.
let hint = match (asking, fixing) {
(true, _) => "ctrl+enter ask the agent · esc cancel",
(false, true) => "ctrl+enter send now · esc cancel",
(false, false) => "ctrl+enter save · esc cancel",
};
(title, hint)
}
/// A reviewer-facing anchor summary: `src/event.rs:143 (new)` rather than an opaque ID pair.
///
/// Always names the file: "new line 143" is unusable once a review spans more than one path.
pub(in crate::view::guided_review) fn anchor_summary(
app: &App,
anchor: &luxe_core::guided_review::FindingAnchor,
) -> String {
use luxe_core::guided_review::{DiffSide, FindingAnchor};
let path_of = |file_id: &luxe_core::guided_review::FileId| {
app.guided_review
.as_ref()
.and_then(|review| review.files.iter().find(|file| &file.id == file_id))
.and_then(|file| file.new_path.as_deref().or(file.old_path.as_deref()))
.map(|path| path.display().to_string())
};
match anchor {
FindingAnchor::Line { file_id, side, line, .. } => {
let side = match side {
DiffSide::Old => "old",
DiffSide::New => "new",
};
match path_of(file_id) {
Some(path) => format!("{path}:{line} ({side})"),
None => format!("{side} line {line}"),
}
}
FindingAnchor::Hunk { file_id, hunk_id } => {
let heading = app
.guided_review
.as_ref()
.and_then(|review| {
review
.files
.iter()
.flat_map(|file| &file.hunks)
.find(|hunk| &hunk.id == hunk_id)
})
.and_then(|hunk| hunk.heading.clone());
match (path_of(file_id), heading) {
(Some(path), Some(heading)) => format!("{path} · {heading}"),
(Some(path), None) => format!("{path} · selected hunk"),
(None, _) => "selected hunk".into(),
}
}
FindingAnchor::Chapter { chapter_id } => app
.guided_review
.as_ref()
.and_then(|review| review.chapters.iter().find(|chapter| &chapter.id == chapter_id))
.map_or_else(
|| "current chapter".into(),
|chapter| format!("chapter · {}", chapter.title),
),
FindingAnchor::Review => "entire review".into(),
}
}
/// The chapter's presentation priority, so supporting and generated sections are labeled rather
/// than looking like more core work.
pub(in crate::view::guided_review) fn chapter_kind_label(
kind: luxe_core::guided_review::ChapterKind,
) -> &'static str {
use luxe_core::guided_review::ChapterKind;
match kind {
ChapterKind::Core => "core",
ChapterKind::Consequence => "consequence",
ChapterKind::Test => "tests",
ChapterKind::Supporting => "supporting",
ChapterKind::Generated => "generated",
}
}

View File

@@ -0,0 +1,257 @@
//! Finish and commit — the dialog that ends a review, and the preview before its commit.
use super::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use crate::guided_review::FinishReviewChoice;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
pub(in crate::view::guided_review) fn render_finish_review(
frame: &mut Frame,
area: Rect,
app: &App,
selected: FinishReviewChoice,
) {
let width = area.width.saturating_sub(4).clamp(40, 64).min(area.width);
let mut lines = finish_header(app);
lines.extend(finish_choice_rows(app, selected, width));
// As tall as what it says, wrapped where it will be drawn, the two borders and the footer
let rows = Paragraph::new(lines.clone())
.wrap(Wrap { trim: false })
.line_count(width.saturating_sub(3)) as u16;
let height = rows.saturating_add(2 + crate::widgets::FOOTER_ROWS);
let Some(popup) = crate::widgets::fit_whole_review_preview(frame, area, (width, height), app)
else {
return;
};
let surface_style = app.theme_styles.text.patch(app.theme_styles.tool_bg);
let block = overlay_block(app, Icon::Finish.glyph(), "Finish review").style(surface_style);
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(
frame,
block,
popup,
"enter finish · ↑/↓ choose · esc cancel",
None,
&app.theme_styles,
);
// `trim: false`, or the leading frame is stripped from every option except the chosen one and
// the list steps sideways as the cursor moves. The prose above the options starts at the
// margin, so it wraps the same either way.
frame
.render_widget(Paragraph::new(lines).style(surface_style).wrap(Wrap { trim: false }), body);
}
/// What finishing would carry, and the second-press notice when blocking comments remain.
fn finish_header(app: &App) -> Vec<Line<'static>> {
// Name exactly what a submission carries. Severity travels as priority metadata, so nothing a
// reviewer wrote is left behind by the mode they pick.
let unsent = crate::app::input::unsent_finding_ids(app);
let again = app.review.session().map_or(0, |session| {
session
.findings
.iter()
.filter(|finding| {
unsent.contains(&finding.id)
&& finding.state == luxe_core::guided_review::FindingState::Open
})
.count()
});
// The title says what the dialog is for; the first line says what finishing would carry
let mut lines = vec![
Line::from(Span::styled(finish_carries(unsent.len(), again), app.theme_styles.muted)),
Line::from(""),
];
if app.guided_review_workspace.finish_review_accept_confirmed {
lines.extend([
Line::from(Span::styled(
"Blocking comments remain. Press enter again to accept.",
app.theme_styles.accent,
)),
Line::from(""),
]);
}
lines
}
/// The finish dialog's choices, the one under the cursor highlighted, each clipped to one row.
fn finish_choice_rows(app: &App, selected: FinishReviewChoice, width: u16) -> Vec<Line<'static>> {
// Choices clip rather than wrap: a detail that spilled onto a second, unindented line read as
// an extra option, which is a dangerous thing to misread in a dialog that submits work.
//
// width - 2 borders - 1 left pad, the same sum the findings drawer makes: the pad belongs to
// `overlay_block`, and a row sized to the border-to-border width overruns it by exactly one
// cell, wraps, and opens a gap under whichever option the cursor is on.
let row_width = usize::from(width.saturating_sub(3));
let choice_row = |choice: FinishReviewChoice, label: &str, detail: &str| {
let marker = if choice == selected { "›" } else { " " };
let head = format!("{marker} {label}");
let detail = clip_terminal_cells_ellipsis(
&format!(" — {detail}"),
row_width.saturating_sub(head.width() + crate::widgets::SELECTION_FRAME),
);
// The cursor row carries the rail's selection highlight. Tinting it accent alone made the
// chosen option read as the *dimmest* row against its bright neighbors.
crate::widgets::selection_row(
vec![
Span::styled(head, app.theme_styles.text),
Span::styled(detail, app.theme_styles.muted),
],
row_width,
choice == selected,
&app.theme_styles,
)
};
let mut lines = Vec::new();
lines.extend([
choice_row(FinishReviewChoice::Accept, "Accept", "mark it reviewed; the agent isn't told"),
choice_row(
FinishReviewChoice::AcceptAndCommit,
"Accept and commit",
"accept, then commit each chapter",
),
choice_row(
FinishReviewChoice::RequestFixes,
"Request fixes",
"ask the agent to address them",
),
choice_row(
FinishReviewChoice::CommentOnly,
"Comment only",
"send them without requesting edits",
),
]);
if app.guided_review_workspace.finish_offers_answers {
lines.push(choice_row(
FinishReviewChoice::AnswerOnGitHub,
"Answer on GitHub",
"reply to and resolve its threads",
));
}
if app.guided_review_workspace.finish_offers_opening {
lines.push(choice_row(
FinishReviewChoice::OpenPullRequest,
"Open pull request",
"commit, push, and open it on GitHub",
));
}
if app.guided_review_workspace.finish_offers_stack {
lines.push(choice_row(
FinishReviewChoice::OpenStack,
"Open as a stack",
"one pull request per chapter, each on the last",
));
}
lines.push(choice_row(
FinishReviewChoice::Cancel,
"Keep reviewing",
"nothing is sent; comments stay",
));
lines
}
/// What finishing sends: every comment not yet with the agent, and again any it has but has not
/// answered, which the guide's count of unsent leaves out.
pub(super) fn finish_carries(comments: usize, again: usize) -> String {
let noun = if comments == 1 { "comment" } else { "comments" };
match (comments, again) {
(0, _) => "No comments to send — add one with c.".to_owned(),
(_, 0) => format!("Sends {comments} {noun}."),
(_, again) if again == comments => format!("Sends {comments} {noun} again."),
_ => format!("Sends {comments} {noun}, {again} of them again."),
}
}
/// The commit preview: the exact subjects and bodies about to enter the log.
///
/// Chapters are already a hunk-exact partition of the change, so committing them is mechanical —
/// but writing history is irreversible enough that the messages get read first.
pub(in crate::view::guided_review) fn render_commit_preview(
frame: &mut Frame,
area: Rect,
app: &App,
preview: &crate::guided_review::CommitPreview,
) {
use luxe_core::guided_review::{chapter_commits, squashed_commit};
let Some(review) = app.guided_review.as_ref() else {
return;
};
let rendered = if preview.squash {
squashed_commit(review, &[]).map(|commit| vec![commit])
} else {
chapter_commits(review, &[])
};
let width = area.width.saturating_sub(4).clamp(48, 92);
let row_width = usize::from(width.saturating_sub(4));
let mut lines = Vec::new();
match rendered {
Ok(commits) => {
lines.push(Line::from(Span::styled(
match commits.len() {
_ if preview.squash => "One commit for the whole review".to_owned(),
1 => "One commit, for the review's only chapter".to_owned(),
count => format!("{count} commits, one per chapter"),
},
app.theme_styles.accent,
)));
lines.push(Line::from(Span::styled(
"Staged from the reviewed revision. Never pushes, never amends.",
app.theme_styles.muted,
)));
lines.push(Line::from(""));
for commit in &commits {
lines.push(Line::from(Span::styled(
clip_terminal_cells_ellipsis(&commit.subject, row_width),
app.theme_styles.text,
)));
// The rationale is the reason the chapter exists, and it becomes the commit body.
if let Some(body) = commit.message.lines().nth(2) {
lines.push(Line::from(Span::styled(
format!(" {}", clip_terminal_cells_ellipsis(body, row_width)),
app.theme_styles.muted,
)));
}
for skipped in &commit.skipped {
lines.push(Line::from(Span::styled(
format!(" ! {skipped} cannot be committed from the review"),
app.theme_styles.warning,
)));
}
}
}
Err(error) => {
lines.push(Line::from(Span::styled(error.to_string(), app.theme_styles.error)))
}
}
if preview.running {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled("Committing…", app.theme_styles.accent)));
}
let footer = if preview.squash {
" enter commit · s one per chapter · esc cancel "
} else {
" enter commit · s squash into one · esc cancel "
};
let block = overlay_block(app, Icon::Finish.glyph(), "Commit the review");
// Size to the commit plan actually being previewed — a fixed box left a large empty well under
// a two-line message, which reads as a rendering fault rather than a deliberate frame.
let body = Paragraph::new(lines).wrap(Wrap { trim: false });
let height = u16::try_from(body.clone().block(block.clone()).line_count(width))
.unwrap_or(u16::MAX)
.saturating_add(crate::widgets::FOOTER_ROWS)
.clamp(7, area.height.saturating_sub(4).max(7));
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
frame.render_widget(Clear, popup);
let inner = crate::widgets::render_footed(frame, block, popup, footer, None, &app.theme_styles);
frame.render_widget(body, inner);
}

View File

@@ -0,0 +1,202 @@
//! Review help — the key reference, and the source picker.
use super::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::ReviewSourcePickerSelection;
use crate::keys_card::HelpGroup;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph};
use ratatui::Frame;
/// Panel label, shared by the rendered title and the popup-width computation.
const HELP_TITLE: &str = "Help · Guided Review";
/// The review's key card, drawn by the same renderer as the chat's.
pub(in crate::view::guided_review) fn render_help(frame: &mut Frame, area: Rect, app: &App) {
crate::keys_card::render(
frame,
area,
HELP_TITLE,
&help_groups(app),
" ? close ",
None,
&app.theme_styles,
);
}
/// Every key the review answers to, grouped for finding: moving, reading, feedback, and the
/// session. A key someone may rebind is named from the keymap, so the card says what is bound
/// rather than what shipped.
fn help_groups(app: &App) -> Vec<HelpGroup> {
use luxe_core::keymap::UiAction;
let chord = |action, fallback| super::super::chord(app, action, fallback);
// A shifted letter reads as the capital the review's other keys are written in: `E`, like `N`
let letter = |action, fallback| {
let bound = chord(action, fallback);
match bound.strip_prefix("shift+").filter(|key| key.chars().count() == 1) {
Some(key) => key.to_uppercase(),
None => bound,
}
};
let row = |keys: &str, words: &str| (keys.to_owned(), words.to_owned());
// A pull request's comments go to GitHub, so its review finishes there rather than with the
// agent
let pull_request = crate::app::github_post_is_pull_request(app);
let mut feedback = vec![
row(
"c",
if pull_request {
"comment, posted with the review"
} else {
"comment, for the agent to act on"
},
),
row(
"a",
if pull_request {
"ask the agent, which stays here"
} else {
"ask; the agent answers, never edits"
},
),
(
chord(UiAction::ReviewFindings, "alt+c"),
if pull_request {
"all comments: reply, verify".to_owned()
} else {
"all comments: send, reply, verify".to_owned()
},
),
row("e x", "edit, delete a draft"),
row("r", "resolve or verify"),
(chord(UiAction::ReviewReanchorFinding, "alt+r"), "re-anchor a stale comment".to_owned()),
];
if pull_request {
feedback.push(row("o", "open on GitHub"));
}
vec![
(
"Move",
vec![
row("space n", "next stop; past the last, finish"),
row("N", "previous stop"),
row("[ ]", "previous, next chapter"),
row("ctrl+↑/↓", "previous, next file"),
row("↑/↓", "line"),
row("pgup/pgdn", "page"),
row("ctrl+u/d", "half a page"),
row("←/→", "scroll sideways"),
row("home", "scroll back to the left"),
row("/", "find"),
],
),
(
"Read",
vec![
(chord(UiAction::ReviewToggleGuide, "g"), "show or hide the guide".to_owned()),
row("z", "show or hide the prose"),
(
chord(UiAction::ReviewToggleSplit, "ctrl+b"),
"side-by-side or unified".to_owned(),
),
row("w", "wrap long lines"),
row("f d", "open collapsed churn, say why"),
(
letter(UiAction::ReviewOpenInEditor, "E"),
"open the file in your editor".to_owned(),
),
],
),
("Feedback", feedback),
(
"Session",
vec![
row("s", "change the source"),
(chord(UiAction::ReviewRefresh, "ctrl+r"), "refresh".to_owned()),
(
chord(UiAction::ReviewFinish, "alt+enter"),
if pull_request { "post the review to GitHub" } else { "finish" }.to_owned(),
),
row("esc", "back to chat"),
],
),
]
}
pub(in crate::view::guided_review) fn render_source_picker(
frame: &mut Frame,
area: Rect,
app: &App,
selection: ReviewSourcePickerSelection,
) {
let width = area.width.clamp(28, 58);
let height = area.height.clamp(7, 11);
let popup = Rect::new(
area.x.saturating_add(area.width.saturating_sub(width) / 2),
area.y.saturating_add(area.height.saturating_sub(height) / 2),
width,
height,
);
let last_turn = if app.review.last_turn.is_some() {
"compare the latest completed turn"
} else {
"unavailable — no completed turn"
};
let rows = [
(ReviewSourcePickerSelection::WorkingTree, "Working Tree", "capture current changes"),
(ReviewSourcePickerSelection::LastTurn, "Last Turn", last_turn),
(ReviewSourcePickerSelection::Base, "Base", "enter a local reference"),
(ReviewSourcePickerSelection::Commit, "Commit", "enter an object identifier"),
];
let mut lines = rows
.into_iter()
.map(|(kind, label, detail)| {
let unavailable =
kind == ReviewSourcePickerSelection::LastTurn && app.review.last_turn.is_none();
let marker = if kind == selection {
if unavailable {
"×"
} else {
"›"
}
} else {
" "
};
let label_style =
if unavailable { app.theme_styles.muted } else { app.theme_styles.accent };
Line::from(vec![
Span::styled(format!("{marker} {label:<13}"), label_style),
Span::styled(detail, app.theme_styles.muted),
])
})
.collect::<Vec<_>>();
if let Some(entry) = app.guided_review_workspace.source_reference_entry.as_ref() {
let label = match entry.kind {
crate::guided_review::ReviewSourceReferenceKind::Base => "Base reference",
crate::guided_review::ReviewSourceReferenceKind::Commit => "Commit object ID",
};
let value = if entry.value.is_empty() { "_" } else { entry.value.as_str() };
lines.push(Line::from(vec![
Span::styled(format!("{label}: "), app.theme_styles.text),
Span::styled(value, app.theme_styles.accent),
]));
if let Some(error) = entry.error {
lines.push(Line::from(Span::styled(error, app.theme_styles.error)));
}
}
let hint = match app.guided_review_workspace.source_reference_entry.as_ref() {
Some(entry) => match entry.kind {
crate::guided_review::ReviewSourceReferenceKind::Base => " enter load base · esc back ",
crate::guided_review::ReviewSourceReferenceKind::Commit => {
" enter load commit · esc back "
}
},
None => " enter load · ↑/↓ choose · esc close ",
};
let block = overlay_block(app, Icon::Source.glyph(), "Change review source");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(frame, block, popup, hint, None, &app.theme_styles);
frame.render_widget(Paragraph::new(lines), body);
}

View File

@@ -0,0 +1,215 @@
use super::*;
use crate::fixture::{seeded_app, FixtureScenario};
use crate::guided_review::FinishReviewChoice;
use ratatui::{backend::TestBackend, Terminal};
use ratatui::{layout::Rect, Frame};
/// The rows `draw` puts on a `width` × `height` screen.
fn drawn(width: u16, height: u16, draw: impl FnOnce(&mut Frame)) -> Vec<String> {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("terminal");
terminal.draw(draw).expect("draw");
let buffer = terminal.backend().buffer();
(0..height).map(|y| (0..width).map(|x| buffer[(x, y)].symbol()).collect::<String>()).collect()
}
/// Where a card's top-left corner is, and how big it is, from its rounded corners.
fn card(rows: &[String]) -> (u16, u16, u16, u16) {
let top = rows.iter().position(|row| row.contains('╭')).expect("a top edge");
let bottom = rows.iter().rposition(|row| row.contains('╰')).expect("a bottom edge");
let chars: Vec<char> = rows[top].chars().collect();
let left = chars.iter().position(|c| *c == '╭').expect("left corner");
let right = chars.iter().position(|c| *c == '╮').expect("right corner");
(left as u16, top as u16, (right - left + 1) as u16, (bottom - top + 1) as u16)
}
/// The finish dialog is as tall as what it says, centered, with one row an option however
/// narrow, and the cursor on the choice it was given.
#[test]
fn the_finish_dialog_hugs_its_options_and_centers() {
let app = seeded_app("nord", FixtureScenario::GuidedReviewFinish).expect("fixture app");
for (width, height) in [(120u16, 40u16), (44, 31)] {
let area = Rect::new(0, 0, width, height);
let rows = drawn(width, height, |frame| {
render_finish_review(frame, area, &app, FinishReviewChoice::RequestFixes)
});
let text = rows.join("\n");
let (left, top, card_width, card_height) = card(&rows);
assert_eq!(left, (width - card_width) / 2, "centered across: {text}");
assert_eq!(top, (height - card_height) / 2, "and down: {text}");
let labels = ["Accept ", "Accept and commit", "Request fixes", "Comment only", "Keep"];
let at: Vec<usize> = labels
.iter()
.map(|label| rows.iter().position(|row| row.contains(label)).expect(label))
.collect();
assert!(at.windows(2).all(|pair| pair[1] == pair[0] + 1), "a row each: {text}");
// The last option, then the footer's rule and keys, then the frame
assert_eq!(usize::from(top + card_height), at[4] + 4, "nothing under the last: {text}");
assert!(rows[at[4] + 1].contains("────") && rows[at[4] + 2].contains("enter finish"));
assert!(text.contains("› Request fixes") && !text.contains("› Accept"), "{text}");
}
let finish = |app: &App| {
drawn(120, 40, |frame| {
let area = Rect::new(0, 0, 120, 40);
render_finish_review(frame, area, app, FinishReviewChoice::Accept)
})
.join("\n")
};
let text = finish(&app);
assert!(text.contains("Sends 2 comments, 1 of them again."), "{text}");
assert!(text.contains("Accept — mark it reviewed; the agent isn't told"), "in full: {text}");
// With nothing the agent already has, nothing goes again
let mut fresh = app;
for finding in &mut fresh.review.session_mut().expect("session").findings {
if finding.state == luxe_core::guided_review::FindingState::Open {
finding.state = luxe_core::guided_review::FindingState::Draft;
}
}
let text = finish(&fresh);
assert!(text.contains("Sends 2 comments."), "{text}");
}
/// On a screen smaller than their floor the finish and details dialogs stay inside it, and
/// where not even a few rows fit they say so rather than draw a card with its bottom missing.
///
/// The break this catches: both were sized with a floor and no ceiling, so below it the card
/// was wider or taller than the screen and ratatui clipped the border and the footer away.
#[test]
fn the_finish_and_details_dialogs_stay_inside_a_small_screen() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let first = app.review.session().expect("session").findings[0].id.clone();
app.guided_review_workspace.selected_finding_id = Some(first);
for (width, height) in [(30u16, 14u16), (44, 9), (60, 5), (36, 20)] {
let area = Rect::new(0, 0, width, height);
let finish = drawn(width, height, |frame| {
render_finish_review(frame, area, &app, FinishReviewChoice::Accept)
});
let details = drawn(width, height, |frame| render_finding_details(frame, area, &app));
for (name, rows) in [("finish", finish), ("details", details)] {
let text = rows.join("\n");
if text.contains("Make the window bigger") {
assert!(name == "finish" || height < 6, "{name} {width}x{height} had room: {text}");
continue;
}
if name == "finish" {
// every choice is on screen, or none of the card is: a cut-off list hides
// options the keys still act on
for label in
["Accept ", "Accept and commit", "Request fixes", "Comment only", "Keep"]
{
assert!(text.contains(label), "finish {width}x{height} lost {label}: {text}");
}
}
let (left, top, card_width, card_height) = card(&rows);
assert!(left + card_width <= width, "{name} {width}x{height} too wide: {text}");
assert!(top + card_height <= height, "{name} {width}x{height} too tall: {text}");
let last = &rows[usize::from(top + card_height - 1)];
assert!(last.contains('╯'), "{name} {width}x{height} lost its bottom: {text}");
// the keys sit in a row of the card, under the rule, not in its border
let keys = rows
.iter()
.find(|row| row.contains("esc cancel") || row.contains("esc close"))
.unwrap_or_else(|| panic!("{name} {width}x{height} lost its keys: {text}"));
assert!(keys.trim_start().starts_with('│'), "{name} {width}x{height}: {text}");
}
}
}
/// Behind the notice that stands in for the finish dialog, nothing but esc acts: Enter would
/// finish a review on a choice the reader cannot see.
#[test]
fn the_finish_dialog_behind_its_notice_takes_only_esc() {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFinish).expect("fixture app");
app.guided_review_workspace.finish_review_choice = Some(FinishReviewChoice::Accept);
let key = |code| KeyEvent::new(code, KeyModifiers::NONE);
let area = Rect::new(0, 0, 44, 9);
let notice =
drawn(44, 9, |frame| render_finish_review(frame, area, &app, FinishReviewChoice::Accept));
assert!(notice.join("\n").contains("Make the window bigger"), "{notice:?}");
assert!(app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Enter)));
assert!(!app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Esc)));
let area = Rect::new(0, 0, 60, 30);
drawn(60, 30, |frame| render_finish_review(frame, area, &app, FinishReviewChoice::Accept));
assert!(!app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Enter)));
}
/// The finish dialog is drawn the moment its whole card fits and not before, with a row clear
/// above and below, so a dialog that fits is never hidden and one that does not is never cut.
#[test]
fn the_finish_dialog_is_drawn_exactly_when_its_card_fits() {
let app = seeded_app("nord", FixtureScenario::GuidedReviewFinish).expect("fixture app");
let at = |height: u16| {
let area = Rect::new(0, 0, 60, height);
drawn(60, height, |frame| {
render_finish_review(frame, area, &app, FinishReviewChoice::Accept)
})
};
let (_, _, _, card_height) = card(&at(40));
let roomy = at(card_height + 2);
assert!(!roomy.join("\n").contains("Make the window bigger"), "{roomy:?}");
assert_eq!(card(&roomy).3, card_height, "the whole card, a row clear above and below");
let short = at(card_height + 1);
assert!(short.join("\n").contains("Make the window bigger"), "{short:?}");
}
/// Behind the notice that stands in for a finding's details, nothing but esc acts: the feedback
/// window's `x` would delete a comment the reader cannot see.
#[test]
fn a_findings_details_behind_their_notice_take_only_esc() {
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let first = app.review.session().expect("session").findings[0].id.clone();
let workspace = &mut app.guided_review_workspace;
workspace.selected_finding_id = Some(first);
workspace.findings_visible = true;
workspace.finding_details_visible = true;
let key = |code| KeyEvent::new(code, KeyModifiers::NONE);
let area = Rect::new(0, 0, 60, 5);
let rows = drawn(60, 5, |frame| render_finding_details(frame, area, &app));
assert!(rows.join("\n").contains("Make the window bigger"), "{rows:?}");
assert!(app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Char('x'))));
assert!(!app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Esc)));
let area = Rect::new(0, 0, 80, 30);
drawn(80, 30, |frame| render_finding_details(frame, area, &app));
assert!(!app.guided_review_workspace.hidden_preview_takes(key(KeyCode::Char('x'))));
}
/// Help sits in two columns where they fit and one where they do not, centered, with a blank
/// row between groups and none above the first.
#[test]
fn help_takes_two_columns_where_they_fit() {
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let rows_at = |width: u16, height: u16| {
drawn(width, height, |frame| render_help(frame, Rect::new(0, 0, width, height), &app))
};
let row_of = |rows: &[String], word: &str| {
rows.iter().position(|row| row.contains(word)).unwrap_or_else(|| panic!("{word}"))
};
let two = rows_at(97, 30);
let (left, top, width, height) = card(&two);
assert_eq!((left, top), ((97 - width) / 2, (30 - height) / 2), "centered");
assert_eq!(row_of(&two, "Move"), usize::from(top) + 1, "the first group leads");
assert_eq!(row_of(&two, "Feedback"), row_of(&two, "Move"), "side by side at 97");
let read = row_of(&two, "Read");
assert!(two[read - 1].chars().skip(usize::from(left) + 2).take(40).all(|c| c == ' '));
let one = rows_at(96, 44);
assert!(row_of(&one, "Feedback") > row_of(&one, "Move"), "stacked at 96");
let roomy = rows_at(130, 30);
let (left, top, width, height) = card(&roomy);
assert_eq!((left, top), ((130 - width) / 2, (30 - height) / 2), "centered with room");
}
/// The finish line counts what it sends and says how much of it the agent has already had,
/// because the guide's count of unsent leaves those out.
#[test]
fn finishing_says_what_it_sends_and_what_it_sends_again() {
assert_eq!(finish_carries(0, 0), "No comments to send — add one with c.");
assert_eq!(finish_carries(1, 0), "Sends 1 comment.");
assert_eq!(finish_carries(3, 0), "Sends 3 comments.");
assert_eq!(finish_carries(1, 1), "Sends 1 comment again.");
assert_eq!(finish_carries(2, 1), "Sends 2 comments, 1 of them again.");
}

View File

@@ -0,0 +1,71 @@
//! The offer to fix a pull request in a worktree — where it goes, what goes with it, or why not.
use super::overlays::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::PullRequestFix;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
pub(super) fn render_pull_request_fix(
frame: &mut Frame,
area: Rect,
app: &App,
fix: &PullRequestFix,
) {
let styles = &app.theme_styles;
let width = area.width.saturating_sub(4).clamp(50, 84).min(area.width);
let mut lines = Vec::new();
match (&fix.branch, &fix.refusal) {
(_, Some(refusal)) => lines.push(Line::from(Span::styled(refusal.clone(), styles.error))),
(Some(branch), None) => {
let with = match fix.comments {
0 => String::new(),
1 => " with your comment for the agent to address".to_string(),
n => format!(" with your {n} comments for the agent to address"),
};
lines.push(Line::from(crate::widgets::code_spans(
&format!(
"Checks #{} out on `{branch}` in a worktree of its own and starts a new \
session{with}.",
fix.number
),
styles.text,
styles,
)));
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"You can come back to this session at any time.",
styles.muted,
)));
}
(None, None) => lines.push(Line::from(Span::styled(
format!(
"{} Asking GitHub whether a fix could reach #{}…",
crate::statusline::spinner(app.guided_review_workspace.frame),
fix.number
),
styles.muted,
))),
}
let inner_width = usize::from(width.saturating_sub(4)).max(1);
let rows: usize =
lines.iter().map(|line| line.width().max(1).div_ceil(inner_width)).sum::<usize>()
+ 2
+ usize::from(crate::widgets::FOOTER_ROWS);
let rows = u16::try_from(rows).unwrap_or(u16::MAX);
let Some(popup) = crate::widgets::fit_review_preview(frame, area, (width, rows, 7), app) else {
return;
};
let hint = if fix.branch.is_some() && fix.refusal.is_none() {
" enter check out · esc cancel "
} else {
" esc close "
};
let block = overlay_block(app, Icon::GitHub.glyph(), "Fix in a worktree");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(frame, block, popup, hint, None, &app.theme_styles);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), body);
}

View File

@@ -0,0 +1,383 @@
//! The pull request preview — what opens on GitHub, and what happens first, before it does.
use super::overlays::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use crate::guided_review::{OpeningField, PullRequestOpening};
use luxe_core::github::Publication;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
/// What the draft leaves behind and how opening is going, pinned under the description.
fn tail_lines(
app: &App,
opening: &PullRequestOpening,
inner_width: u16,
spinner: &str,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut tail = Vec::new();
if let Some(left_out) = opening.prepared.as_ref().and_then(left_out) {
tail.push(Line::from(Span::styled(
clip_terminal_cells_ellipsis(&left_out, usize::from(inner_width)),
styles.warning,
)));
}
if let Some(error) = opening.error.as_deref() {
tail.push(Line::from(crate::widgets::code_spans(error, styles.error, styles)));
}
if opening.opening {
tail.push(Line::from(Span::styled(
format!("{spinner} Opening it on GitHub…"),
styles.muted,
)));
}
tail
}
/// The heading's parts: where the pull request goes, and what is unusual about it.
fn heading_parts(prepared: &crate::guided_review::PreparedOpening) -> Vec<String> {
let pull_request = &prepared.pull_request;
let mut parts = vec![format!("Into `{}` from `{}`", pull_request.base, pull_request.head)];
// Ready for review goes without saying; a draft is the exception, so only it is named
if pull_request.draft {
parts.push("as a draft".to_owned());
}
parts.extend(first(prepared).map(str::to_owned));
parts
}
/// How tall the popup wants to be.
///
/// Args: `(opening, area, (heading_height, body_rows, tail_rows))`.
fn wanted_height(
opening: &PullRequestOpening,
area: Rect,
(heading_height, body_rows, tail_rows): (u16, u16, u16),
) -> u16 {
// As tall as the draft, up to most of the screen; all of that while writing, which needs room
let most = area.height.saturating_sub(4).max(14);
match (&opening.prepared, opening.editing.as_ref()) {
(None, _) => (tail_rows + 3).max(5),
(Some(_), Some(_)) => most,
// Heading and its gap, the title and its label, a gap, the description and its label, then
// the frame, and anything pinned under the description after a gap of its own
(Some(_), None) => (heading_height
+ 3
+ 1
+ 1
+ body_rows.max(3)
+ tail_rows
+ u16::from(tail_rows > 0)
+ 2)
.min(most),
}
.saturating_add(crate::widgets::FOOTER_ROWS)
.min(area.height)
}
/// Draws the description — the editor while it is being written, otherwise the rendered markdown
/// — and returns whether it runs past its room.
fn render_description(
frame: &mut Frame,
app: &App,
opening: &PullRequestOpening,
(body, body_rows): (Option<Vec<Line<'static>>>, u16),
body_area: Rect,
) -> bool {
let styles = &app.theme_styles;
let mut overflows = false;
match (opening.editing.as_ref(), body) {
(Some((OpeningField::Body, editor)), _) => {
app.guided_review_workspace.field_width.set(body_area.width);
crate::widgets::text_field::render(frame, body_area, editor, styles);
}
_ if opening
.prepared
.as_ref()
.map_or("", |prepared| prepared.pull_request.body.as_str())
.trim()
.is_empty() =>
{
frame.render_widget(
Paragraph::new(Span::styled("(no description)", styles.muted)),
body_area,
)
}
(_, Some(body)) => {
// Clamped here, where the room is known, and remembered so scrolling back up
// starts moving at once instead of first unwinding an overshoot
let room = body_rows.saturating_sub(body_area.height);
opening.body_room.set(room);
overflows = room > 0;
let scroll = opening.body_scroll.min(room);
let text_area = Rect { width: body_area.width.saturating_sub(1), ..body_area };
frame.render_widget(
Paragraph::new(body).wrap(Wrap { trim: false }).scroll((scroll, 0)),
text_area,
);
crate::widgets::steered_scrollbar(
frame,
&mut app.hit.borrow_mut(),
body_area,
crate::mouse::ScrollRegionId::PullRequestBody,
usize::from(scroll),
usize::from(body_rows),
usize::from(body_area.height),
styles,
);
}
(_, None) => {}
}
overflows
}
/// The key hints for what the popup is doing right now.
fn opening_hint(opening: &PullRequestOpening, overflows: bool) -> String {
match (opening.opening, opening.editing.as_ref(), opening.prepared.as_ref()) {
(true, ..) => " opening… ".to_owned(),
(_, Some((OpeningField::Title, _)), _) => " enter save · esc cancel ".to_owned(),
(_, Some((OpeningField::Body, _)), _) => " ctrl+enter save · esc cancel ".to_owned(),
(_, None, Some(_)) => {
let scroll = if overflows { " · ↑/↓ scroll" } else { "" };
format!(
" enter open · t title · e description · E in your editor · d draft{scroll} · esc \
cancel "
)
}
(_, None, None) if opening.error.is_some() => " enter try again · esc cancel ".to_owned(),
(_, None, None) => " esc cancel ".to_owned(),
}
}
/// The heading rows, with the backticks around names drawn as emphasis.
fn render_heading(frame: &mut Frame, app: &App, rows: Vec<String>, area: Rect, inner_width: u16) {
let styles = &app.theme_styles;
let heading = rows.into_iter().map(|row| {
// the backticks are not drawn, so they get their room back
let room = usize::from(inner_width) + row.matches('`').count();
Line::from(crate::widgets::code_spans(
&clip_terminal_cells_ellipsis(&row, room),
styles.accent,
styles,
))
});
frame.render_widget(Paragraph::new(heading.collect::<Vec<_>>()), area);
}
/// The title: the editor while it is being written, otherwise the title in bold.
fn render_title(
frame: &mut Frame,
app: &App,
opening: &PullRequestOpening,
area: Rect,
inner_width: u16,
) {
let styles = &app.theme_styles;
match opening.editing.as_ref() {
Some((OpeningField::Title, editor)) => {
app.guided_review_workspace.field_width.set(area.width);
crate::widgets::text_field::render(frame, area, editor, styles);
}
_ => {
let title =
opening.prepared.as_ref().map_or("", |prepared| &prepared.pull_request.title);
frame.render_widget(
Paragraph::new(Span::styled(
clip_terminal_cells_ellipsis(title, usize::from(inner_width)),
styles.text.add_modifier(ratatui::style::Modifier::BOLD),
)),
area,
);
}
}
}
/// Draws the pull request preview: small while it drafts, and most of the screen once there is a
/// draft to read, since agent-written descriptions run long and are markdown.
pub(super) fn render_pull_request_opening(
frame: &mut Frame,
area: Rect,
app: &App,
opening: &PullRequestOpening,
) {
let styles = &app.theme_styles;
let width = area.width.saturating_sub(8).clamp(60, 120).min(area.width);
let inner_width = width.saturating_sub(3).max(1);
let spinner = crate::statusline::spinner(app.guided_review_workspace.frame);
let editing = opening.editing.as_ref();
let tail = tail_lines(app, opening, inner_width, spinner);
let tail_rows = crate::widgets::text_field::wrapped_rows(&tail, inner_width);
let heading = opening
.prepared
.as_ref()
.map(|prepared| heading_rows(&heading_parts(prepared), usize::from(inner_width)));
let heading_height = heading.as_ref().map_or(1, |rows| u16::try_from(rows.len()).unwrap_or(1));
let body = opening
.prepared
.as_ref()
.map(|prepared| crate::markdown::render_markdown(&prepared.pull_request.body, styles));
let body_rows =
body.as_ref().map_or(0, |body| crate::widgets::text_field::wrapped_rows(body, inner_width));
let overflows = std::cell::Cell::new(false);
let height = wanted_height(opening, area, (heading_height, body_rows, tail_rows));
let popup = crate::widgets::centered_rect(width, height, area);
let block = overlay_block(app, Icon::GitHub.glyph(), "Open pull request");
let inner = crate::widgets::footed_body(&block, popup);
frame.render_widget(Clear, popup);
match opening.prepared.as_ref() {
None => {
let mut lines = Vec::new();
if opening.error.is_none() {
lines.push(Line::from(Span::styled(
format!("{spinner} Drafting it from the review…"),
styles.muted,
)));
}
lines.extend(tail);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}
Some(_) => {
let title_rows = match editing {
Some((OpeningField::Title, editor)) => {
crate::widgets::text_field::rows(editor, inner_width).clamp(1, 3)
}
_ => 1,
};
let gap = u16::from(tail_rows > 0);
let [head, title_label, title, _, body_label, body_area, _, tail_area] =
ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Length(heading_height + 1),
ratatui::layout::Constraint::Length(1),
ratatui::layout::Constraint::Length(title_rows),
ratatui::layout::Constraint::Length(1),
ratatui::layout::Constraint::Length(1),
ratatui::layout::Constraint::Min(3),
ratatui::layout::Constraint::Length(gap),
ratatui::layout::Constraint::Length(tail_rows),
])
.areas(inner);
render_heading(frame, app, heading.unwrap_or_default(), head, inner_width);
frame.render_widget(Paragraph::new(label("Title", styles)), title_label);
render_title(frame, app, opening, title, inner_width);
frame.render_widget(Paragraph::new(label("Description", styles)), body_label);
overflows.set(render_description(frame, app, opening, (body, body_rows), body_area));
frame.render_widget(Paragraph::new(tail).wrap(Wrap { trim: false }), tail_area);
}
}
let hint = opening_hint(opening, overflows.get());
crate::widgets::render_footed(frame, block, popup, &hint, None, &app.theme_styles);
}
/// A section's name, quiet so what is under it reads first.
fn label(text: &'static str, styles: &crate::theme::styles::ThemeStyles) -> Span<'static> {
Span::styled(text, styles.muted)
}
/// `parts` joined with ` · ` into as few rows as fit `width`, breaking only between parts: a
/// heading cut mid-phrase, `commits and pushes fi…`, lost the part that mattered most.
pub(super) fn heading_rows(parts: &[String], width: usize) -> Vec<String> {
// backticks mark code and are not drawn, so they take no room
let cells = |text: &str| UnicodeWidthStr::width(text.replace('`', "").as_str());
let mut rows: Vec<String> = Vec::new();
for part in parts {
match rows.last_mut() {
Some(row) if cells(row) + 3 + cells(part) <= width => {
row.push_str(" · ");
row.push_str(part);
}
_ => rows.push(part.clone()),
}
}
rows
}
/// What Enter does before the pull request exists, for the heading: a reader should not have to
/// find out from `git log` that opening it committed and pushed.
fn first(prepared: &crate::guided_review::PreparedOpening) -> Option<&'static str> {
if !prepared.commits.is_empty() {
Some("commits and pushes first")
} else if matches!(prepared.publication, Publication::Pushed) {
None
} else {
Some("pushes first")
}
}
/// Changed files the pull request will not carry, which is the one thing opening does that a
/// reader could be surprised by afterward.
fn left_out(prepared: &crate::guided_review::PreparedOpening) -> Option<String> {
(prepared.commits.is_empty() && prepared.uncommitted > 0).then(|| {
let files = if prepared.uncommitted == 1 { "file" } else { "files" };
format!("{} changed {files} left out · not in the review", prepared.uncommitted)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::guided_review::PreparedOpening;
fn prepared(publication: Publication, uncommitted: usize, commits: &[&str]) -> PreparedOpening {
PreparedOpening {
pull_request: luxe_core::github::NewPullRequest {
head: "me:7-fix".into(),
base: "main".into(),
title: "Fix".into(),
body: String::new(),
draft: false,
},
publication,
uncommitted,
commits: commits.iter().map(|subject| (*subject).to_owned()).collect(),
}
}
#[test]
fn a_heading_breaks_between_its_parts() {
let parts =
["Into `main` from `todo-overdue`".to_owned(), "commits and pushes first".to_owned()];
assert_eq!(
heading_rows(&parts, 54),
["Into `main` from `todo-overdue` · commits and pushes first"]
);
assert_eq!(
heading_rows(&parts, 53),
["Into `main` from `todo-overdue`", "commits and pushes first"]
);
assert!(heading_rows(&[], 10).is_empty());
}
#[test]
fn the_heading_says_what_opening_does_first() {
assert_eq!(first(&prepared(Publication::Pushed, 0, &[])), None);
assert_eq!(
first(&prepared(Publication::Pushed, 2, &["One", "Two"])),
Some("commits and pushes first")
);
assert_eq!(first(&prepared(Publication::Unpublished, 0, &[])), Some("pushes first"));
assert_eq!(
first(&prepared(Publication::Ahead { commits: 1 }, 0, &[])),
Some("pushes first")
);
assert_eq!(left_out(&prepared(Publication::Pushed, 1, &["One"])), None, "it commits them");
assert_eq!(
left_out(&prepared(Publication::Pushed, 2, &[])).as_deref(),
Some("2 changed files left out · not in the review")
);
assert_eq!(
left_out(&prepared(Publication::Pushed, 1, &[])).as_deref(),
Some("1 changed file left out · not in the review")
);
}
}

View File

@@ -0,0 +1,75 @@
//! The stack preview — every pull request a review's chapters open as, before they do.
use super::overlays::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use crate::guided_review::StackOpening;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
pub(super) fn render_stack_opening(frame: &mut Frame, area: Rect, app: &App, stack: &StackOpening) {
let styles = &app.theme_styles;
let width = area.width.saturating_sub(4).clamp(50, 96).min(area.width);
let row_width = usize::from(width.saturating_sub(4));
let spinner = crate::statusline::spinner(app.guided_review_workspace.frame);
let mut lines = Vec::new();
match &stack.layers {
None if stack.error.is_none() => lines.push(Line::from(Span::styled(
format!("{spinner} Drafting a pull request per chapter…"),
styles.muted,
))),
None => {}
Some(layers) => {
let into = layers.first().map_or("", |layer| layer.base.as_str());
let mut parts = vec![format!(
"{} pull requests into `{into}`, each based on the one below",
layers.len()
)];
if stack.draft {
parts.push("as drafts".to_owned());
}
parts.push("commits and pushes first".to_owned());
for row in super::pull_request_opening::heading_rows(&parts, row_width) {
lines.push(Line::from(crate::widgets::code_spans(&row, styles.accent, styles)));
}
lines.push(Line::from(""));
for (index, layer) in layers.iter().enumerate() {
let row = format!("{}. `{}` — {}", index + 1, layer.head, layer.title);
lines.push(Line::from(crate::widgets::code_spans(
&clip_terminal_cells_ellipsis(&row, row_width),
styles.text,
styles,
)));
}
}
}
if let Some(error) = stack.error.as_deref() {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(error.to_owned(), styles.error)));
}
if stack.opening {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(format!("{spinner} Opening the stack…"), styles.muted)));
}
let inner_width = usize::from(width.saturating_sub(4)).max(1);
let rows: usize =
lines.iter().map(|line| line.width().max(1).div_ceil(inner_width)).sum::<usize>()
+ 2
+ usize::from(crate::widgets::FOOTER_ROWS);
let rows = u16::try_from(rows).unwrap_or(u16::MAX);
let Some(popup) = crate::widgets::fit_review_preview(frame, area, (width, rows, 8), app) else {
return;
};
let hint = match (stack.opening, stack.layers.is_some()) {
(true, _) => " opening… ",
(false, true) => " enter open · d draft · esc cancel ",
(false, false) => " esc close ",
};
let block = overlay_block(app, Icon::GitHub.glyph(), "Open as a stack");
frame.render_widget(Clear, popup);
let body = crate::widgets::render_footed(frame, block, popup, hint, None, &app.theme_styles);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: true }), body);
}

View File

@@ -0,0 +1,31 @@
use super::*;
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::{
event::{GuidedReviewFailure, GuidedReviewFailureKind},
guided_review::{
FileId, FindingId, FindingSeverity, FindingState, NonTextChange, NonTextChangeKind,
ReviewCheck, ReviewCheckStatus, ReviewItemRef,
},
};
use std::path::Path;
mod agent_activity;
mod attention_in_walkthrough;
mod composer;
mod footer_contract;
mod guide_interaction;
mod rail_divider;
mod scale;
mod verification;
mod context;
mod diff;
mod feedback;
mod footer;
mod guide;
mod loading;
mod previews;
use diff::*;
use previews::*;

View File

@@ -0,0 +1,40 @@
//! Agent activity — tests moved out of the module they cover.
use super::*;
use crate::fixture::{seeded_app, FixtureScenario};
use ratatui::{backend::TestBackend, Terminal};
/// After submitting, the review used to go silent with no sign the agent was working. It now
/// names the comments in flight.
#[test]
fn the_rail_reports_that_the_agent_is_working_on_a_comment() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let backend = TestBackend::new(160, 40);
let mut terminal = Terminal::new(backend).expect("test terminal");
let render_text = |terminal: &mut Terminal<TestBackend>, app: &App| {
terminal.draw(|frame| render(frame, frame.area(), app)).expect("render");
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect::<String>()
};
assert!(!render_text(&mut terminal, &app).contains("Agent working"));
let session = app.review.session_mut().expect("review session");
let finding_id = session.findings[0].id.clone();
let submission_id = luxe_core::guided_review::SubmissionId::new();
session
.queue_submission(
submission_id.clone(),
luxe_core::guided_review::ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&[],
0,
)
.expect("queue the submission");
session.dispatch_submission(&submission_id).expect("dispatch it");
let working = render_text(&mut terminal, &app);
assert!(
working.contains("Agent working on your comment"),
"the rail names the work in flight: {working}"
);
}

View File

@@ -0,0 +1,112 @@
//! Attention in walkthrough — tests moved out of the module they cover.
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{AttentionKind, AttentionSignal};
/// A concern about the file on screen belongs on the screen, not only in an index the reviewer
/// consulted before they started reading. Here it sits under the prose that should have
/// explained it, one `c` away from becoming a question the agent has to answer.
#[test]
fn the_walkthrough_carries_the_harness_signals_for_the_file_it_shows() {
let (width, height) = (170, 44);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewWide).unwrap();
app.update(Msg::TerminalResized { width, height });
let review = app.guided_review.clone().expect("the fixture has a review");
let file = review.files.first().expect("the review has a file");
let path = file
.new_path
.clone()
.or_else(|| file.old_path.clone())
.expect("a path")
.to_string_lossy()
.into_owned();
app.review.flags = vec![AttentionSignal {
kind: AttentionKind::BlindEdit,
path: Some(path.clone()),
detail: format!("{path} was edited without being read"),
aggregate: false,
file_id: Some(file.id.clone()),
hunk_id: None,
}];
let backend = ratatui::backend::TestBackend::new(width, height);
let mut terminal = ratatui::Terminal::new(backend).expect("test terminal");
terminal
.draw(|frame| super::render(frame, frame.area(), &app))
.expect("render the walkthrough");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(
text.contains("edited without being read"),
"the signal rides with the file in the walkthrough: {text}"
);
assert!(
!text.contains("unread "),
"and without a badge column restating its own sentence: {text}"
);
}
/// Past the cap of two a kind, every flagged file still wears its badge, and each kind over the
/// cap gets its own total rather than only the first kind a count.
#[test]
fn every_flagged_file_wears_its_badge_and_each_kind_over_the_cap_its_total() {
let secrets = ["src/a.rs", "src/b.rs", "src/c.rs", "src/d.rs"];
let unread = ["src/e.rs", "src/f.rs", "src/g.rs"];
let review = crate::fixture::flagged_review(&secrets, &unread);
let (tx, _rx) = tokio::sync::mpsc::channel(8);
let mut app = crate::app::App::new(
tx,
luxe_core::keymap::KeyMap::defaults(),
luxe_core::config::Config::default(),
);
app.update(Msg::Engine(luxe_core::event::Event::GuidedReviewLoaded {
request_id: luxe_core::guided_review::ReviewLoadRequestId::new(),
review: Box::new(review.clone()),
}));
let text = |line: ratatui::text::Line<'_>| -> String {
line.spans.iter().map(|span| span.content.as_ref()).collect()
};
let badges: Vec<String> = review
.files
.iter()
.map(|file| text(super::brief::file_line(&app, file, false, 100)))
.collect();
let (secret, unread_badge) = ("secret?", "unread");
assert!(badges[..4].iter().all(|row| row.contains(secret)), "{badges:#?}");
assert!(badges[4..].iter().all(|row| row.contains(unread_badge)), "{badges:#?}");
let notices: Vec<String> =
super::brief::notice_lines(&app, &review).into_iter().map(text).collect();
assert!(notices.contains(&"5 credential-shaped lines".to_string()), "{notices:#?}");
assert!(notices.contains(&"3 files edited without being read".to_string()), "{notices:#?}");
}
/// Two credential lines in one file are two flags and one thing to say: the walkthrough under that
/// file says it once.
#[test]
fn the_walkthrough_says_a_repeated_reason_once() {
let (width, height) = (170, 44);
let review = crate::fixture::flagged_review(&["src/a.rs"], &[]);
let (tx, _rx) = tokio::sync::mpsc::channel(8);
let mut app = crate::app::App::new(
tx,
luxe_core::keymap::KeyMap::defaults(),
luxe_core::config::Config::default(),
);
app.update(Msg::TerminalResized { width, height });
app.update(Msg::Engine(luxe_core::event::Event::GuidedReviewLoaded {
request_id: luxe_core::guided_review::ReviewLoadRequestId::new(),
review: Box::new(review),
}));
assert_eq!(app.review.flags.len(), 2, "one flag per credential line");
let backend = ratatui::backend::TestBackend::new(width, height);
let mut terminal = ratatui::Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| super::render(frame, frame.area(), &app)).expect("render");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert_eq!(text.matches("adds a line that looks like a credential").count(), 1, "{text}");
}

View File

@@ -0,0 +1,134 @@
//! Composer — the comment box, as tall as its field and placed where typing lands.
use super::*;
/// The composer is as tall as its field, which is three rows at least, and sits centered.
#[test]
fn the_composer_is_as_tall_as_its_field_and_centered() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
app.guided_review_workspace.begin_finding_draft(&files);
let rows = frame_rows(&mut app, 120, 40);
let (top, bottom) = modal_rows(&rows, "Comment on this");
let label = rows.iter().position(|row| row.contains("Comment:")).expect("label");
assert_eq!(label, top + 3, "location, gap, label");
assert_eq!(bottom - label - 1, 3, "a three-row field: {}", rows.join("\n"));
let lines = (1..=6).map(|n| format!("line {n}")).collect::<Vec<_>>().join("\n");
app.guided_review_workspace.finding_draft.as_mut().expect("draft").set_body(lines);
let rows = frame_rows(&mut app, 120, 40);
let (top, bottom) = modal_rows(&rows, "Comment on this");
let label = rows.iter().position(|row| row.contains("Comment:")).expect("label");
assert_eq!(bottom - label - 1, 6, "grows with what is written: {}", rows.join("\n"));
let corner = rows[top].chars().position(|c| matches!(c, '╭' | '┌')).unwrap();
assert_eq!(corner, (120 - 88) / 2, "{}", rows[top]);
assert!(top.abs_diff(rows.len() - 1 - bottom) <= 3, "{top} vs {bottom}");
// An error says so under the field, and the box grows by its row
app.guided_review_workspace.finding_draft.as_mut().expect("draft").error =
Some("Write something first.".into());
let rows = frame_rows(&mut app, 120, 40);
let (_, grown) = modal_rows(&rows, "Comment on this");
assert!(rows[grown - 1].contains("Write something first."), "{}", rows.join("\n"));
let label = rows.iter().position(|row| row.contains("Comment:")).expect("label");
assert_eq!(grown - label - 1, 7, "six rows of field and the error");
}
/// Writing a reply adds its label and its field under the list, and the box stays centered.
#[test]
fn a_reply_adds_its_field_under_the_list() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewOwnPullRequest).expect("fixture app");
// The second thread has no reply written yet, so writing one hides nothing above the field
app.guided_review_workspace.thread_answers.as_mut().expect("preview").selected = 1;
let rows = frame_rows(&mut app, 160, 60);
let (top, bottom) = modal_rows(&rows, "Answer on GitHub");
let before = bottom - top;
app.guided_review_workspace.thread_answers.as_mut().expect("preview").replying =
Some(crate::editor::Editor::new());
let rows = frame_rows(&mut app, 160, 60);
let (top, bottom) = modal_rows(&rows, "Answer on GitHub");
assert_eq!(bottom - top, before + 5, "a gap, a label and a three-row field");
assert!(top > 5 && top.abs_diff(rows.len() - 1 - bottom) <= 3, "{top} vs {bottom}");
}
#[test]
fn the_composer_is_a_location_and_a_box_to_type_in() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
app.guided_review_workspace.begin_finding_draft(&files);
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finding draft");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Comment on this"));
// The location names the file, not just a bare side/line pair — and names only itself:
// "Anchor:" was a word for the mechanism, not for the place.
assert!(text.contains("src/notification.rs"), "{text}");
assert!(!text.contains("Anchor:"));
// Nothing to pick. The verb already said what this asks of the agent.
assert!(!text.contains("Severity"));
assert!(!text.contains("severity"));
assert!(!text.contains("Proposed fix"));
assert!(text.contains("ctrl+enter save"));
assert!(text.contains("esc cancel"));
}
/// Severity used to be the only thing on screen saying which verb had opened the box.
///
/// It is gone, and a question still does something a comment does not — the agent answers it
/// and is forbidden to edit, and it leaves the moment it is saved instead of waiting for
/// `Alt+U`. If the composer looks identical either way, the reviewer has no way to notice they
/// pressed the wrong key until the agent has already rewritten the code they asked about.
#[test]
fn asking_and_commenting_do_not_open_the_same_looking_box() {
use ratatui::{backend::TestBackend, Terminal};
let render_draft = |ask: bool| {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
if ask {
app.guided_review_workspace.begin_question(&files);
} else {
app.guided_review_workspace.begin_finding_draft(&files);
}
let mut terminal = Terminal::new(TestBackend::new(100, 28)).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render composer");
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect::<String>()
};
let asked = render_draft(true);
assert!(asked.contains("Ask the agent about this"), "{asked}");
assert!(asked.contains("Question: "), "{asked}");
assert!(asked.contains("ctrl+enter ask the agent"), "a question does not wait for alt+u");
let commented = render_draft(false);
assert!(commented.contains("Comment on this"), "{commented}");
assert!(commented.contains("Comment: "), "{commented}");
assert!(commented.contains("ctrl+enter save"), "a comment batches");
}
/// The composer shows the terminal's cursor where typing lands, on a second line as much as
/// the first, so a comment can be edited rather than only appended to.
#[test]
fn the_composer_shows_its_cursor_where_typing_lands() {
use ratatui::{backend::Backend, backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
app.guided_review_workspace.begin_finding_draft(&files);
let draft = app.guided_review_workspace.finding_draft.as_mut().expect("draft");
draft.set_body("first line\nsecond");
let mut terminal = Terminal::new(TestBackend::new(100, 28)).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render composer");
let at = terminal.backend_mut().get_cursor_position().expect("cursor");
let buffer = terminal.backend().buffer().clone();
let row: String = (0..100).map(|x| buffer[(x, at.y)].symbol().to_string()).collect::<String>();
let before: String =
(0..at.x).map(|x| buffer[(x, at.y)].symbol().to_string()).collect::<String>();
assert!(row.contains("second"), "the cursor is on the line being written: {row}");
assert!(before.trim_end().ends_with("second"), "right after it: {before:?}");
}

View File

@@ -0,0 +1,305 @@
//! Context — the header, the rail and what they report about checks and outcomes.
use super::*;
/// The rail's files are a list you pick from, so the chosen one wears the slab — cut against
/// the rail's *own* fill, and without moving off the column it holds when the cursor is
/// somewhere else.
#[test]
fn the_rails_chosen_file_row_is_cut_into_a_slab_on_its_own_fill() {
use ratatui::{backend::TestBackend, Terminal};
crate::glyphs::set_tier(crate::glyphs::GlyphTier::Nerd);
// Every bundled theme paints the rail the same color as the app background, which would
// let a cap cut against the wrong canvas pass unnoticed. A theme is free to raise it.
const RAIL: ratatui::style::Color = ratatui::style::Color::Rgb(0x21, 0x1e, 0x1a);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewWide).expect("fixture app");
app.theme_styles.tool_bg = ratatui::style::Style::new().bg(RAIL);
let draw = |app: &App| {
let mut terminal = Terminal::new(TestBackend::new(160, 32)).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), app)).expect("render the rail");
terminal.backend().buffer().clone()
};
// Only the rail: the diff pane beside it names the same file in its own header.
let rail = crate::workspace_layout::LEFT_RAIL_WIDTH;
let placement = |buffer: &ratatui::buffer::Buffer| -> (u16, u16) {
(0..buffer.area.height)
.find_map(|y| {
let row: String = (0..rail).map(|x| buffer[(x, y)].symbol()).collect();
row.find("notification.rs")
.map(|byte| (unicode_width::UnicodeWidthStr::width(&row[..byte]) as u16, y))
})
.expect("the rail lists the chapter's file")
};
let chosen = draw(&app);
let (name_x, row) = placement(&chosen);
app.guided_review_workspace.position.file_id = None;
assert_eq!(
placement(&draw(&app)).0,
name_x,
"the frame is spent either way, so the name holds its column"
);
let line: String = (0..rail).map(|x| chosen[(x, row)].symbol()).collect();
let cap = crate::widgets::Cap::Open.glyph();
let cut = line.find(cap).expect("the chosen row opens on a cut");
let cut_x = unicode_width::UnicodeWidthStr::width(&line[..cut]) as u16;
assert!(cut_x < name_x, "and the cut opens before the name: {line:?}");
assert_eq!(
chosen[(cut_x, row)].bg,
RAIL,
"the cut tapers into the rail, not into the color behind it"
);
}
#[test]
fn wide_header_names_the_durable_review_outcome() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
app.review.session_mut().expect("review session").outcome =
Some(luxe_core::guided_review::ReviewOutcome::ChangesRequested);
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render review outcome");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Outcome: changes requested"));
}
#[test]
fn narrow_context_keeps_the_durable_outcome_before_clipped_context() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.review.session_mut().expect("review session").outcome =
Some(luxe_core::guided_review::ReviewOutcome::Commented);
let backend = TestBackend::new(80, 24);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render narrow review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Outcome: commented"));
}
#[test]
fn check_status_shows_on_the_wide_rail_and_medium_keeps_core_stats() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review.as_mut().expect("fixture review").checks.checks.push(ReviewCheck {
name: "cargo test".into(),
status: ReviewCheckStatus::Passed,
summary: None,
});
let wide_backend = TestBackend::new(160, 32);
let mut wide_terminal = Terminal::new(wide_backend).expect("wide terminal");
wide_terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render wide header");
let wide: String =
wide_terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
let compact_backend = TestBackend::new(100, 32);
let mut compact_terminal = Terminal::new(compact_backend).expect("compact terminal");
compact_terminal
.draw(|frame| render(frame, frame.area(), &app))
.expect("render compact header");
let compact: String =
compact_terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// Verification state rides on every tier: it is the difference between reading a change
// and vouching for it, so the compact header carries it alongside the core stats.
assert!(wide.contains("Checks ✓"));
assert!(wide.contains("1 file ·"), "singular reads as one file: {wide}");
assert!(compact.contains("1 file ·"));
assert!(compact.contains("Checks ✓"));
}
#[test]
fn wide_header_names_failed_checks_without_calling_them_pending() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review.as_mut().expect("fixture review").checks.checks.push(ReviewCheck {
name: "cargo test".into(),
status: ReviewCheckStatus::Failed,
summary: None,
});
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render failed checks");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Checks failed"));
assert!(!text.contains("Checks pending"));
}
#[test]
fn wide_header_names_unavailable_checks_when_no_check_is_pending_or_failed() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review.as_mut().expect("fixture review").checks.checks.push(ReviewCheck {
name: "remote gate".into(),
status: ReviewCheckStatus::Unavailable,
summary: Some("offline".into()),
});
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render unavailable checks");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// The only unavailable state today is a run that predates the final edit, so the label
// says that rather than the generic word.
assert!(text.contains("Verified before the last edit"), "{text}");
assert!(!text.contains("Checks pending"));
}
#[test]
fn guide_summary_lists_referenced_non_text_files() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let review = app.guided_review.as_mut().expect("fixture review");
let mut non_text = review.files[0].clone();
non_text.id = FileId::from_path_lineage(None, Some(Path::new("assets/icon.bin")));
non_text.new_path = Some("assets/icon.bin".into());
non_text.hunks.clear();
non_text.binary = true;
non_text.non_text = Some(NonTextChange {
kind: NonTextChangeKind::Binary,
summary: "Binary files differ".into(),
});
review.chapters[0].items.push(ReviewItemRef::File(non_text.id.clone()));
review.files.push(non_text);
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render guide summary");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("assets/icon.bin"));
}
#[test]
fn guide_summary_windows_long_file_lists_around_the_selected_file() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let review = app.guided_review.as_mut().expect("fixture review");
let template = review.files[0].clone();
let mut selected_id = None;
// More files than a chapter lists at once, so the list has to window
for number in 1..=9 {
let path = format!("src/support_{number}.rs");
let mut file = template.clone();
file.id = FileId::from_path_lineage(None, Some(Path::new(&path)));
// Hunks of their own, or the chapter's items resolve to whichever copy came last
for (index, hunk) in file.hunks.iter_mut().enumerate() {
hunk.id =
luxe_core::guided_review::HunkId::from_content(&file.id, &index.to_string(), &path);
}
file.new_path = Some(path.into());
review.chapters[0].items.push(ReviewItemRef::File(file.id.clone()));
selected_id = Some(file.id.clone());
review.files.push(file);
}
app.guided_review_workspace.position.file_id = selected_id;
// Tall enough for the rail's metadata block plus a windowed file list; the exact elided
// count depends on height, so assert that windowing happens and the selected file stays
// visible rather than pinning a specific number.
let backend = TestBackend::new(160, 20);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render guide summary");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// The guide windows the list and always keeps the cursor's file in it.
assert!(text.contains("support_9.rs"), "the selected file stays visible: {text}");
assert!(!text.contains("support_1.rs"), "and the rest is windowed away: {text}");
assert!(text.contains("above"), "saying what it left out: {text}");
}
#[test]
fn non_text_diff_focus_label_matches_the_active_pane() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let review = app.guided_review.as_mut().expect("fixture review");
let mut non_text = review.files[0].clone();
non_text.id = FileId::from_path_lineage(None, Some(Path::new("assets/icon.bin")));
non_text.new_path = Some("assets/icon.bin".into());
non_text.hunks.clear();
non_text.binary = true;
non_text.non_text = Some(NonTextChange {
kind: NonTextChangeKind::Binary,
summary: "Binary files differ".into(),
});
app.guided_review_workspace.position.file_id = Some(non_text.id.clone());
review.files.push(non_text);
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render non-text diff");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Binary change"));
assert!(!text.contains("Diff · active"));
}
#[test]
fn the_rail_reports_verification_only_when_it_is_missing() {
use ratatui::{backend::TestBackend, Terminal};
let render_rail = |app: &mut crate::app::App| -> String {
app.update(Msg::TerminalResized { width: 150, height: 48 });
let mut terminal = Terminal::new(TestBackend::new(150, 48)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect()
};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewDemo).expect("fixture");
let verified = render_rail(&mut app);
assert!(
!verified.contains("Nothing ran after the last edit"),
"a verified turn says nothing about it: {verified}"
);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewDemo).expect("fixture");
if let Some(provenance) =
app.guided_review.as_mut().and_then(|review| review.provenance.as_mut())
{
provenance.verified_after_last_edit = false;
}
let stale = render_rail(&mut app);
assert!(
stale.contains("Nothing ran after the last edit"),
"the one verification fact a self-authored summary will not volunteer: {stale}"
);
}
#[test]
fn ninety_column_review_uses_the_medium_context_layout() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("review fixture");
let backend = TestBackend::new(90, 24);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render medium boundary");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("01 / 01"));
assert!(!text.contains("01/01 · Shared notification model · src/notification.rs"));
}

View File

@@ -0,0 +1,331 @@
//! Diff — tabs, wrapping and scrolling in the diff pane.
use super::*;
/// Replaces the first hunk with lines indented one tab deeper each, which is what exposed the
/// defect: the rendered width fell one cell behind the measured width per tab.
pub(super) fn seed_tab_indented_hunk(app: &mut crate::app::App) {
use luxe_core::guided_review::{ReviewLine, ReviewLineKind};
let Some(hunk) = app
.guided_review
.as_mut()
.and_then(|review| review.files.first_mut().and_then(|file| file.hunks.first_mut()))
else {
panic!("the fixture has a hunk to replace");
};
hunk.lines = (1..=4u32)
.flat_map(|depth| {
let indent = "\t".repeat(depth as usize);
[
ReviewLine {
old_line: Some(depth * 2),
new_line: None,
kind: ReviewLineKind::Deletion,
text: format!("{indent}<div class=\"old-{depth}\">"),
},
ReviewLine {
old_line: None,
new_line: Some(depth * 2),
kind: ReviewLineKind::Addition,
text: format!("{indent}<div class=\"new-{depth}\">"),
},
]
})
.collect();
}
/// The column each add/delete row's tint reaches, one entry per tinted row.
///
/// Only the diff's own backgrounds count — row tint and the deeper intra-line wash — because a
/// selected row and a hunk header wear the selection tint, which is a different claim and a
/// different width.
pub(super) fn diff_tint_run_ends(
app: &crate::app::App,
buffer: &ratatui::buffer::Buffer,
) -> Vec<u16> {
let area = buffer.area;
let styles = &app.theme_styles;
let hues = [
styles.diff_add_bg.bg,
styles.diff_del_bg.bg,
styles.diff_add_emphasis.bg,
styles.diff_del_emphasis.bg,
];
let mut ends = Vec::new();
for y in 0..area.height {
let mut open = false;
for x in 0..area.width {
let tinted = hues.contains(&Some(buffer[(x, y)].bg));
if open && !tinted {
ends.push(x);
}
open = tinted;
}
if open {
ends.push(area.width);
}
}
ends
}
/// A tab is measured as zero cells and dropped by the buffer, so a row's tint used to stop one
/// cell short for every tab in it — a staircase down the right edge of any block of indented
/// code, and in side by side a column rule that wandered with the indentation.
#[test]
fn tab_indentation_does_not_ragged_the_row_tints() {
use ratatui::{backend::TestBackend, Terminal};
// One edge unified, one per column side by side — and never one per indentation depth,
// which is what the defect produced.
for (split, edges) in [(false, 1usize), (true, 2)] {
let (width, height) = (160u16, 30u16);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
seed_tab_indented_hunk(&mut app);
app.guided_review_workspace.layout = if split {
luxe_core::config::DiffLayout::Split
} else {
luxe_core::config::DiffLayout::Unified
};
app.update(Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("render");
let buffer = terminal.backend().buffer().clone();
let mut columns = diff_tint_run_ends(&app, &buffer);
assert!(columns.len() >= 4, "split={split}: several tinted diff rows are drawn");
columns.sort_unstable();
columns.dedup();
assert_eq!(
columns.len(),
edges,
"split={split}: tinted rows end at {columns:?} — indentation is moving the edge"
);
}
}
/// The indentation itself has to survive, not just the arithmetic about it: a tab-indented
/// file used to render flush left because the buffer drops control characters.
#[test]
fn tab_indentation_reaches_the_screen() {
use ratatui::{backend::TestBackend, Terminal};
let (width, height) = (160u16, 30u16);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
seed_tab_indented_hunk(&mut app);
app.guided_review_workspace.layout = luxe_core::config::DiffLayout::Unified;
app.update(Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("render");
let rendered: String =
terminal.backend().buffer().content.iter().map(ratatui::buffer::Cell::symbol).collect();
assert!(
rendered.contains(" <div class=\"new-3\">"),
"three tabs draw as twelve cells of indent: {rendered}"
);
}
/// Each row of a rendered frame, trimmed, so a phrase cannot match across a line break.
/// The frame's rows, and where the terminal cursor is with the text of its row up to it.
pub(super) fn frame_with_cursor(
app: &mut crate::app::App,
width: u16,
height: u16,
) -> (Vec<String>, (u16, u16), String) {
use ratatui::{backend::Backend, backend::TestBackend, Terminal};
app.update(Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
let at = terminal.backend_mut().get_cursor_position().expect("cursor");
let buffer = terminal.backend().buffer();
let rows = (0..height)
.map(|y| (0..width).map(|x| buffer[(x, y)].symbol()).collect::<String>())
.collect();
let before = (0..at.x).map(|x| buffer[(x, at.y)].symbol()).collect::<String>();
(rows, (at.x, at.y), before)
}
pub(super) fn frame_rows(app: &mut crate::app::App, width: u16, height: u16) -> Vec<String> {
use ratatui::{backend::TestBackend, Terminal};
app.update(Msg::TerminalResized { width, height });
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
let buffer = terminal.backend().buffer();
(0..height)
.map(|y| {
(0..width).map(|x| buffer[(x, y)].symbol()).collect::<String>().trim_end().to_owned()
})
.collect()
}
/// A review titled with a whole paragraph is cut, not left to eat the top of the guide.
///
/// The title is usually the session's first message, which is a sentence as often as it is a
/// name. Left to wrap it took four lines off the top of the pane and still ended mid-word,
/// which reads as a rendering fault rather than as a long title.
#[test]
fn a_long_review_title_is_cut_with_an_ellipsis() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let sentence = "Bulk delete (for example, selecting several messages with space or \
consecutive items with v) seems to remove messages from the list \
immediately, then some of them come back a moment later";
app.guided_review.as_mut().expect("review").context.title = sentence.into();
app.update(crate::app::Msg::TerminalResized { width: 180, height: 44 });
let mut terminal = Terminal::new(TestBackend::new(180, 44)).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Bulk delete"), "the title still opens as itself: {text}");
assert!(!text.contains("come back a moment later"), "and does not run on: {text}");
assert!(text.contains('\u{2026}'), "it is cut with an ellipsis: {text}");
}
/// Injects a long addition line into the fixture's first hunk for wrap/scroll tests.
pub(super) fn seed_long_line(app: &mut crate::app::App) -> String {
let long = "let very_long_identifier = compute_something(alpha, beta, gamma, delta, epsilon, zeta, eta);".to_string();
let review = app.guided_review.as_mut().expect("fixture review");
let hunk = review.files[0].hunks.first_mut().expect("fixture hunk");
let line = hunk
.lines
.iter_mut()
.find(|line| line.kind == luxe_core::guided_review::ReviewLineKind::Addition)
.expect("an addition line");
line.text = long.clone();
long
}
#[test]
fn word_wrap_soft_wraps_long_diff_lines_with_a_continuation_glyph() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
seed_long_line(&mut app);
app.guided_review_workspace.word_wrap = true;
let backend = TestBackend::new(90, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render wrapped diff");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// A continuation glyph marks the wrapped rows, and the tail of the long line is visible
// (it would be clipped off-screen under horizontal scroll).
assert!(text.contains('↳'), "wrapped rows carry a continuation glyph: {text}");
assert!(text.contains("epsilon") || text.contains("eta);"), "wrapped tail visible: {text}");
}
#[test]
fn long_file_paths_truncate_to_one_scannable_row_with_colored_counts() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let long_path = "crates/luxe-tui/src/view/guided_review/context.rs";
{
let review = app.guided_review.as_mut().expect("review");
let mut file = review.files[0].clone();
file.id = FileId::from_path_lineage(None, Some(Path::new(long_path)));
file.new_path = Some(long_path.into());
file.old_path = Some(long_path.into());
file.additions = Some(151);
file.deletions = Some(30);
review.chapters[0].items.push(ReviewItemRef::File(file.id.clone()));
review.files.push(file);
}
let backend = TestBackend::new(150, 40);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render file list");
let buffer = terminal.backend().buffer().clone();
let text: String = buffer.content.iter().map(|cell| cell.symbol()).collect();
// The 42-col rail can't fit the full path, so it truncates behind `…/` with the filename
// (and its colored counts) kept on one row — the full deep prefix is elided.
assert!(text.contains("…/"), "long path is truncated: {text}");
assert!(text.contains("context.rs +151"), "filename + counts stay on one row: {text}");
assert!(
!text.contains("luxe-tui/src/view/guided_review/context.rs"),
"the full deep path is not shown verbatim in the rail"
);
// The change counts are colored (green additions), matching the dock. Scope the check to
// the long file's rail row so it can't match a `+` in the diff pane or the metadata stats.
let row = (0..buffer.area.height)
.find(|&y| {
(0..40u16).map(|x| buffer[(x, y)].symbol()).collect::<String>().contains("context.rs")
})
.expect("the long file's rail row renders");
let plus_x = (0..42u16)
.find(|&x| buffer[(x, row)].symbol() == "+")
.expect("a `+` additions count in the rail row");
assert_eq!(buffer[(plus_x, row)].fg, app.theme_styles.success.fg.expect("success color"));
}
#[test]
fn horizontal_scroll_mode_clips_long_lines_without_a_continuation_glyph() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
seed_long_line(&mut app);
app.guided_review_workspace.word_wrap = false;
let backend = TestBackend::new(90, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render scrolled diff");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(!text.contains('↳'), "scroll mode shows no continuation glyph: {text}");
}
/// Scrolled all the way right, the longest line in the file ends at the pane's edge — even
/// when it is in a hunk other than the one under the cursor, which the pane draws all the same.
/// Both halves matter: one cell short of the end must still be hiding its last character, or
/// the bound is overshooting into blank space.
#[test]
fn scrolling_right_reaches_the_end_of_every_hunk_in_both_layouts() {
use luxe_core::guided_review::{HunkId, ReviewLineKind};
use ratatui::{backend::TestBackend, Terminal};
for (width, split) in [(160u16, true), (100, false)] {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.word_wrap = false;
let tail = "QTAIL";
let (file_id, first_hunk) = {
let review = app.guided_review.as_mut().expect("review");
let file = &mut review.files[0];
let mut later = file.hunks[0].clone();
later.id = HunkId::from_content(&file.id, "later", "a later hunk");
let line = later
.lines
.iter_mut()
.find(|line| line.kind == ReviewLineKind::Addition)
.expect("an addition");
line.text = format!("{}{tail}", "x".repeat(300));
file.hunks.push(later);
(file.id.clone(), file.hunks[0].id.clone())
};
app.update(Msg::TerminalResized { width, height: 60 });
let position = &mut app.guided_review_workspace.position;
position.file_id = Some(file_id);
position.hunk_id = Some(first_hunk);
position.line_offset = 0;
let files = app.guided_review.as_ref().expect("review").files.clone();
assert_eq!(app.guided_review_workspace.split_layout_showing(&files), split);
for _ in 0..100 {
app.update(Msg::GuidedReviewColumnNext);
}
let drawn = |app: &crate::app::App| {
let mut terminal = Terminal::new(TestBackend::new(width, 60)).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), app)).expect("render");
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect::<String>()
};
assert!(drawn(&app).contains(tail), "split={split}: the line's end is reachable");
app.guided_review_workspace.diff_column_offset -= 1;
let short = drawn(&app);
assert!(
short.contains("QTAI") && !short.contains(tail),
"split={split}: one cell back still hides the last character"
);
}
}

View File

@@ -0,0 +1,739 @@
//! Feedback — the drawer, the window, comment cards and the finish dialog.
use super::*;
/// What reviewers already said sits under the line it is about, with the reply beside it, and
/// every thread that cannot sit on a line is listed in the brief — none dropped.
#[test]
fn earlier_threads_sit_on_their_lines_and_the_rest_are_listed() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 170, 90);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("@mara-okafor · unresolved · 1 reply"), "{text}");
// A card, not a bar: the header rides in the top edge and the frame closes under it
assert!(has("╭─ @mara-okafor"), "the thread is framed: {text}");
assert!(rows.iter().any(|row| row.contains("╰─") && row.contains("╯")), "{text}");
assert!(has("Does anything still construct this from a raw string?"), "{text}");
assert!(has("@copilot-swe-agent: Only the webhook"), "{text}");
assert!(has("Discussion on GitHub"), "{text}");
assert!(has("3 threads · 2 unresolved · 1 comment"), "{text}");
assert!(!has("on the lines they are about"), "{text}");
assert!(has("@mara-okafor · src/dispatch/router.rs · outdated"), "{text}");
assert!(has("This match used to fall through"), "{text}");
// A longer name wraps the row, and the facts carry on under it
assert!(has("@jon-avery · src/api/webhook.rs · whole file"), "{text}");
assert!(has("resolved"), "{text}");
assert!(has("@jon-avery · in the conversation"), "{text}");
// The same thread in the unified layout, which draws its rows on its own path
app.guided_review_workspace.layout = luxe_core::config::DiffLayout::Unified;
let unified = frame_rows(&mut app, 170, 90);
assert!(
unified.iter().any(|row| row.contains("Does anything still construct this")),
"{}",
unified.join("\n")
);
}
#[test]
fn the_feedback_drawer_explains_the_empty_review_state() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings drawer");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Feedback"), "the drawer names itself: {text}");
assert!(text.contains("No feedback yet"));
// Both verbs, because a question and a comment are the same artifact here.
assert!(text.contains("c comments on it"));
assert!(text.contains("a asks the agent about it"));
assert!(text.contains("esc close"));
}
/// The window reads the comment under the cursor in full, as markdown, and a long one scrolls
/// in its own pane while the list stays put. Sending opens the same window with checkboxes.
#[test]
fn the_feedback_window_reads_a_long_comment_in_full() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let body = format!(
"## Why this matters\n\n{}\n\nThe **last** line.",
(1..=60).map(|n| format!("- point {n}")).collect::<Vec<_>>().join("\n")
);
let session = app.review.session_mut().expect("session");
session.findings[0].body = body;
let first = session.findings[0].id.clone();
app.guided_review_workspace.selected_finding_id = Some(first);
app.guided_review_workspace.findings_visible = true;
let rows = frame_rows(&mut app, 160, 44);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Why this matters") && !has("## Why"), "drawn as markdown: {text}");
assert!(has("point 1") && !has("The last line."), "{text}");
assert!(has("pgup/pgdn scroll"), "{text}");
assert!(has("Confirm the migration") && has("to verify"), "the list stays beside it: {text}");
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::PageDown,
crossterm::event::KeyModifiers::NONE,
)));
for _ in 0..10 {
app.guided_review_workspace.scroll_feedback(10);
}
let rows = frame_rows(&mut app, 160, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("The last line."), "{}", rows.join("\n"));
assert!(has("Confirm the migration"), "the list does not scroll with it");
// Moving to another comment reads it from the top
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Down,
crossterm::event::KeyModifiers::NONE,
)));
assert_eq!(app.guided_review_workspace.feedback_scroll, 0);
// A plain key the window does not use moves nothing behind it
let before = app.guided_review_workspace.position.clone();
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
crossterm::event::KeyCode::Char(' '),
crossterm::event::KeyModifiers::NONE,
)));
assert_eq!(app.guided_review_workspace.position, before);
app.guided_review_workspace.findings_visible = false;
app.update(crate::app::Msg::GuidedReviewOpenSendPreview);
let rows = frame_rows(&mut app, 160, 44);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Send to agent") && has("Send these comments to the agent"), "{text}");
assert!(has("2 of 2 included"), "{text}");
assert!(has("enter send · space include · ↑/↓ choose"), "{text}");
}
#[test]
fn the_feedback_drawer_orders_actionable_comments_before_finished_ones() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
for (title, state, severity) in [
("Stale anchor", FindingState::Stale, FindingSeverity::Note),
("Resolved concern", FindingState::Resolved, FindingSeverity::Issue),
("Draft thought", FindingState::Draft, FindingSeverity::Suggestion),
("Verify remediation", FindingState::NeedsVerification, FindingSeverity::Issue),
("Open concern", FindingState::Open, FindingSeverity::Issue),
("Blocking concern", FindingState::Open, FindingSeverity::Blocking),
] {
app.guided_review_workspace.begin_finding_draft(&files);
let mut finding = {
let draft = app.guided_review_workspace.finding_draft.as_mut().expect("draft");
draft.set_body(format!("{title}. Fixture feedback, kept for visual triage."));
draft.severity = severity;
draft.to_review_finding(FindingId::new()).expect("valid finding")
};
finding.state = state;
app.review
.session_mut()
.expect("review session")
.add_finding(finding)
.expect("add finding");
app.guided_review_workspace.discard_finding_draft();
}
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings drawer");
// The list's own columns, the left of the window: the pane beside it reads the selected
// comment in full, which would put its title on screen a second time.
let buffer = terminal.backend().buffer().clone();
let text: String = (0..32u16)
.map(|y| (5..60u16).map(|x| buffer[(x, y)].symbol()).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
let position = |title: &str| text.find(title).expect("a row in the drawer");
assert!(position("Blocking concern") < position("Open concern"));
assert!(position("Open concern") < position("Verify remediation"));
assert!(position("Verify remediation") < position("Draft thought"));
assert!(position("Draft thought") < position("Resolved concern"));
assert!(position("Resolved concern") < position("Stale anchor"));
}
/// The drawer's rows are cut from the same slab as every other list, so the one under the
/// cursor has to keep its neighbors' column. The rows arrive laid out, and a paragraph that
/// trims leading whitespace eats the frame off exactly the rows that are *not* selected —
/// which is the sideways shift the frame is spent to prevent.
#[test]
fn findings_drawer_holds_one_column_under_the_cursor() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings drawer");
let buffer = terminal.backend().buffer().clone();
// Where each title starts is where its row's text starts
let column_of = |label: &str| -> Option<u16> {
(0..buffer.area.height).find_map(|y| {
let row: String = (0..buffer.area.width).map(|x| buffer[(x, y)].symbol()).collect();
row.find(label).map(|byte| unicode_width::UnicodeWidthStr::width(&row[..byte]) as u16)
})
};
let columns: Vec<u16> = ["Retry path omits", "Confirm the migration", "Clarify the cancel"]
.iter()
.filter_map(|title| column_of(title))
.collect();
assert_eq!(columns.len(), 3, "the fixture carries three findings to compare");
assert!(
columns.windows(2).all(|pair| pair[0] == pair[1]),
"the chosen row shares its column with the rest: {columns:?}"
);
}
/// A comment renders under the line it is about, with what happens to it next.
///
/// It used to be a bare `R1` in a gutter, and reading your own words meant a drawer over the
/// far corner and a second overlay on top of that — which is why "where did my comment go" was
/// a question at all.
#[test]
fn a_comment_renders_under_the_line_it_is_anchored_to() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
// Offset zero is the hunk header; the first source row has stable old/new line anchors.
app.guided_review_workspace.position.line_offset = 1;
app.guided_review_workspace.begin_finding_draft(&files);
let finding = {
let draft = app.guided_review_workspace.finding_draft.as_mut().expect("finding draft");
draft.set_body("This line needs a compatibility check.");
draft.to_review_finding(FindingId::new()).expect("valid finding")
};
app.review.session_mut().expect("review session").add_finding(finding).expect("add finding");
app.guided_review_workspace.discard_finding_draft();
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render line marker");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(!text.contains("R1"), "a comment carries no label: {text}");
assert!(
text.contains("This line needs a compatibility check."),
"and says what it says, in the diff, not two overlays away: {text}"
);
assert!(
text.contains("unsent"),
"and what happens to it next, which a drawer never said: {text}"
);
}
/// A question the agent is answering spins on its own card, where the reader just wrote it,
/// and stops spinning once its turn is over.
#[test]
fn a_question_being_answered_says_so_on_its_card() {
use luxe_core::guided_review::{
FindingSeverity, FindingState, ReviewFeedbackMode, SubmissionDispatch, SubmissionId,
};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let session = app.review.session_mut().expect("review session");
session.findings[0].severity = FindingSeverity::Question;
session.findings[0].state = FindingState::Open;
let asked = session.findings[0].id.clone();
let submission = SubmissionId::new();
session
.queue_submission(
submission.clone(),
ReviewFeedbackMode::Question,
std::slice::from_ref(&asked),
&[],
0,
)
.expect("queued");
session.dispatch_submission(&submission).expect("dispatched");
let card = |app: &crate::app::App| {
let finding = app.review.session().expect("session").findings[0].clone();
super::diff_render::comment_lines(app, &[finding], 100)
.iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
};
let text = card(&app);
assert!(text.contains("the agent is answering…"), "{text}");
let session = app.review.session_mut().expect("review session");
for sent in &mut session.submissions {
sent.dispatch = SubmissionDispatch::Completed;
}
let text = card(&app);
assert!(!text.contains("answering"), "{text}");
assert!(text.contains("waiting on the agent"), "{text}");
}
/// A comment the agent answered without fixing, `not fixed` or a question back, is the
/// reader's to read, and its card says so rather than that the agent is still on it.
#[test]
fn a_comment_the_agent_replied_to_says_so_on_its_card() {
use luxe_core::guided_review::{
FindingMessage, FindingMessageAuthor, FindingState, ReviewFeedbackMode, SubmissionDispatch,
SubmissionId,
};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let session = app.review.session_mut().expect("review session");
session.findings[0].state = FindingState::Open;
session.findings[0].thread.push(FindingMessage {
author: FindingMessageAuthor::Agent,
body: "Agent reported: not fixed. The caller owns that timeout.".into(),
created_at_ms: 1,
});
let sent = SubmissionId::new();
let ids = [session.findings[0].id.clone()];
session
.queue_submission(sent.clone(), ReviewFeedbackMode::RequestFixes, &ids, &[], 0)
.expect("queued");
let card = |app: &crate::app::App| {
let finding = app.review.session().expect("session").findings[0].clone();
super::diff_render::comment_lines(app, &[finding], 100)
.iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
};
// sent again and still queued: back with the agent, whatever it said last time
assert!(card(&app).contains("waiting on the agent"), "{}", card(&app));
app.review.session_mut().expect("session").submissions[0].dispatch =
SubmissionDispatch::Completed;
let text = card(&app);
assert!(text.contains("the agent replied · alt+c reads it"), "{text}");
assert!(text.contains("agent: Agent reported: not fixed."), "{text}");
}
/// A comment a fix turn ended with no word on says so on its card, with Luxe's reason under
/// it, rather than still claiming the agent is on it.
#[test]
fn a_comment_with_no_word_from_the_agent_says_so_on_its_card() {
use luxe_core::guided_review::{FindingMessage, FindingMessageAuthor, FindingState};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let session = app.review.session_mut().expect("review session");
session.findings[0].state = FindingState::Open;
session.findings[0].thread.push(FindingMessage {
author: FindingMessageAuthor::System,
body: "No word from the agent on this comment: it wrote no report. Refresh the review \
to see the code as it is now."
.into(),
created_at_ms: 1,
});
let finding = session.findings[0].clone();
let text = super::diff_render::comment_lines(&app, &[finding], 100)
.iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
.collect::<Vec<_>>()
.join("\n");
assert!(text.contains("no word from the agent · alt+c says why"), "{text}");
assert!(!text.contains("waiting on the agent"), "{text}");
assert!(text.contains("luxe: No word from the agent on this comment: it wrote no report."));
}
/// A Suggestion used to be sendable by neither Request fixes nor Comment only, so a review
/// made entirely of suggestions was write-only. Severity is priority now, never routing.
#[test]
fn finish_review_sends_suggestions_like_any_other_comment() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
app.review
.session_mut()
.expect("review session")
.findings
.retain(|finding| finding.severity == FindingSeverity::Suggestion);
app.guided_review_workspace.open_finish_review(true);
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finish review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Sends 1 comment"));
assert!(!text.contains("No comments to send"));
}
#[test]
fn finish_review_identifies_when_no_feedback_can_be_submitted() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.open_finish_review(true);
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finish review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("No comments to send"));
assert!(text.contains("add one with c."));
}
#[test]
fn header_shows_feedback_snapshot_before_persistence_confirms() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.review.edits.insert(
luxe_core::guided_review::ReviewSessionSaveRequestId::new(),
crate::app::ReviewEditPurpose::Other,
);
app.review.edits.insert(
luxe_core::guided_review::ReviewSessionSaveRequestId::new(),
crate::app::ReviewEditPurpose::Send,
);
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render pending snapshot");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Saving feedback snapshot"));
assert!(!text.contains("Saving review"));
}
#[test]
fn finish_review_uses_the_light_theme_surface_for_inactive_choices() {
use ratatui::{backend::TestBackend, Terminal};
// No built-in is light any more, so the light palette a reader's own theme file could be
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFinish).expect("fixture app");
app.theme_styles = crate::fixture::light_theme_styles();
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finish review");
// Locate an inactive choice row by its label rather than a fixed cell, so adding a choice
// does not silently move the sample onto a different line.
let buffer = terminal.backend().buffer();
let row = (0..28u16)
.find(|&y| {
(0..100u16)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
.contains("Comment only")
})
.expect("the inactive Comment only row renders");
let column = (0..100u16)
.find(|&x| buffer[(x, row)].symbol() == "C")
.expect("the label starts somewhere on the row");
let cell = &buffer[(column, row)];
assert_eq!(cell.bg, app.theme_styles.tool_bg.bg.expect("light tool surface color"));
assert_eq!(cell.fg, app.theme_styles.text.fg.expect("light text color"));
}
/// The dialog that submits work is the worst place for the list to move. Its options are the
/// same slab every other list is cut from, so they share one column and sit on consecutive
/// rows — a chosen row wide enough to wrap opens a gap under itself and shifts the rest down.
#[test]
fn finish_review_options_share_a_column_and_a_row_each() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewFinish).expect("fixture app");
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finish review");
let buffer = terminal.backend().buffer().clone();
let placement = |label: &str| -> (u16, u16) {
(0..buffer.area.height)
.find_map(|y| {
let row: String = (0..buffer.area.width).map(|x| buffer[(x, y)].symbol()).collect();
row.find(label)
.map(|byte| (unicode_width::UnicodeWidthStr::width(&row[..byte]) as u16, y))
})
.unwrap_or_else(|| panic!("the {label} option renders"))
};
let options =
["Accept ", "Accept and commit", "Request fixes", "Comment only", "Keep reviewing"];
let placed: Vec<(u16, u16)> = options.iter().map(|label| placement(label)).collect();
assert!(
placed.windows(2).all(|pair| pair[0].0 == pair[1].0),
"one label column, chosen or not: {placed:?}"
);
assert!(
placed.windows(2).all(|pair| pair[1].1 == pair[0].1 + 1),
"one row each, so nothing shifts as the cursor moves: {placed:?}"
);
}
#[test]
fn finish_review_explains_pinned_submission_snapshots() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.open_finish_review(true);
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render finish review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("No comments to send"));
assert!(text.contains("Request fixes"));
assert!(text.contains("Request fixes"));
}
#[test]
fn draft_finding_details_only_advertise_draft_mutations() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session()
.expect("review session")
.findings
.iter()
.find(|finding| finding.state == FindingState::Draft)
.expect("draft finding");
app.guided_review_workspace.selected_finding_id = Some(finding.id.clone());
app.guided_review_workspace.finding_details_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render draft evidence");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("e edit · x delete · esc close"));
assert!(!text.contains("r resolve/reopen"));
}
#[test]
fn needs_verification_requires_explicit_verification_before_resolution() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session()
.expect("review session")
.findings
.iter()
.find(|finding| finding.state == FindingState::NeedsVerification)
.expect("verification finding");
app.guided_review_workspace.selected_finding_id = Some(finding.id.clone());
app.guided_review_workspace.finding_details_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render verification finding");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("r verify and resolve"));
assert!(!text.contains("r resolve · esc close"));
}
#[test]
fn finding_details_render_the_whole_thread_attributed_to_each_author() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session_mut()
.expect("review session")
.findings
.first_mut()
.expect("fixture finding");
finding.thread.push(luxe_core::guided_review::FindingMessage {
author: luxe_core::guided_review::FindingMessageAuthor::Agent,
body: "Agent reported: fixed the retry cap.\nRan focused tests.\nA longer audit trail remains durable.".into(),
created_at_ms: 42,
});
finding.thread.push(luxe_core::guided_review::FindingMessage {
author: luxe_core::guided_review::FindingMessageAuthor::Reviewer,
body: "The cap is right, but the caller still ignores the error.".into(),
created_at_ms: 43,
});
app.guided_review_workspace.selected_finding_id = Some(finding.id.clone());
app.guided_review_workspace.finding_details_visible = true;
let backend = TestBackend::new(120, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render evidence");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("an agent report is a claim; reviewer verification required"));
// Both halves of the exchange, attributed and in order.
assert!(text.contains("Agent:"));
assert!(text.contains("Agent reported: fixed the retry cap."));
assert!(text.contains("Ran focused tests."));
assert!(text.contains("Reviewer:"));
assert!(text.contains("The cap is right, but the caller still ignores the error."));
let agent_at = text.find("Agent:").expect("the agent speaks");
let reviewer_at = text.find("Reviewer:").expect("the reviewer replies");
assert!(agent_at < reviewer_at, "the thread reads in chronological order");
// Long bodies stay elided so one message cannot crowd out the rest of the thread.
assert!(!text.contains("A longer audit trail remains durable."));
}
#[test]
fn stale_finding_drawer_only_advertises_reanchoring() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session_mut()
.expect("review session")
.findings
.first_mut()
.expect("fixture finding");
finding.state = FindingState::Stale;
app.guided_review_workspace.selected_finding_id = Some(finding.id.clone());
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render stale drawer");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("alt+r re-anchor and verify"));
assert!(!text.contains("r resolve/reopen"));
assert!(!text.contains("x delete draft"));
}
#[test]
fn edit_draft_overlay_preserves_submitted_feedback_immutability() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session()
.expect("review session")
.findings
.iter()
.find(|finding| finding.state == FindingState::Draft)
.expect("draft finding")
.clone();
assert!(app.guided_review_workspace.begin_edit_finding_draft(&finding));
let backend = TestBackend::new(100, 28);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render edit draft");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Edit comment"));
assert!(text.contains("submitted feedback stays immutable"));
}
#[test]
fn stale_finding_details_expose_the_reanchor_shortcut() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding = app
.review
.session_mut()
.expect("review session")
.findings
.first_mut()
.expect("fixture finding");
finding.state = FindingState::Stale;
app.guided_review_workspace.selected_finding_id = Some(finding.id.clone());
app.guided_review_workspace.finding_details_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render stale details");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Pinned revision:"));
assert!(text.contains("alt+r re-anchor and verify"));
}
#[test]
fn submitted_finding_details_name_the_immutable_snapshot_revision() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding_id = app
.review
.session()
.expect("review session")
.findings
.first()
.expect("fixture finding")
.id
.clone();
app.review
.session_mut()
.expect("review session")
.queue_submission(
luxe_core::guided_review::SubmissionId::new(),
luxe_core::guided_review::ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&[],
0,
)
.expect("queue submission");
app.guided_review_workspace.selected_finding_id = Some(finding_id);
app.guided_review_workspace.finding_details_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render submitted details");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Submitted snapshot (queued):"));
assert!(!text.contains("Pinned revision:"));
}
#[test]
fn the_guide_foot_says_what_the_feedback_wants() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let files = app.guided_review.as_ref().expect("fixture review").files.clone();
app.guided_review_workspace.begin_finding_draft(&files);
let finding = {
let draft = app.guided_review_workspace.finding_draft.as_mut().expect("finding draft");
draft.set_body("The retry path should surface a bounded error.");
draft.severity = FindingSeverity::Blocking;
draft.to_review_finding(FindingId::new()).expect("valid finding")
};
app.review.session_mut().expect("review session").add_finding(finding).expect("add finding");
app.guided_review_workspace.discard_finding_draft();
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings header");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// Unsent leads over severity: a count that does not say none of it has left is the wrong
// fact to put in front of someone. The key that sends it is the footer's.
assert!(text.contains("FEEDBACK") && text.contains(" 1 · 1 unsent"), "{text}");
assert!(!text.contains("alt+u"), "{text}");
}

View File

@@ -0,0 +1,246 @@
//! Footer — what the key row says at each width, and where its keys can be clicked.
use super::*;
/// The footer trims its least important key the moment the row would overflow, and not a
/// cell before: all five fit in exactly their width, and a narrower row keeps what matters.
#[test]
fn the_footer_trims_by_priority_at_its_exact_width() {
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let labels = |width: u16| -> Vec<String> {
fit_footer_segments(ready_footer_segments(&app, width), width)
.into_iter()
.map(|segment| segment.label)
.collect()
};
let all = ["space next", "c comment", "a ask agent", "alt+enter finish", "? help"];
assert_eq!(footer_segments_width(&ready_footer_segments(&app, 200)), 64);
assert_eq!(labels(64), all);
assert_eq!(labels(63), ["space next", "c comment", "alt+enter finish", "? help"]);
assert_eq!(labels(49), ["space next", "alt+enter finish", "? help"]);
assert_eq!(labels(37), ["space next", "? help"], "a tie drops the later key");
assert_eq!(labels(0), ["? help"], "and one key always stays");
}
/// The footer draws each key in the accent and its words in body text, and the key under the
/// pointer lights up whole.
#[test]
fn the_footer_styles_its_keys_and_lights_the_hovered_one() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.pointer.hover = Some(crate::mouse::MouseTarget::ReviewFooter(ReviewFooterAction::Finish));
let segments = ready_footer_segments(&app, 200);
let line = footer_spans(&app, &segments, 200);
let styles = &app.theme_styles;
let span =
|text: &str| line.spans.iter().find(|span| span.content == text).map(|span| span.style);
assert_eq!(span("alt+enter finish"), Some(styles.selected_bg), "hovered, whole");
assert_eq!(span("c"), Some(styles.accent));
assert_eq!(span(" comment"), Some(styles.text));
assert_eq!(line.spans[0].content, "space", "no separator before the first key");
}
/// A footer that is not the ready one is styled the same way, and a sentence among its
/// segments stays a sentence.
#[test]
fn a_plain_footer_styles_keys_and_leaves_sentences() {
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let styles = &app.theme_styles;
let line = footer_hint_line("Refresh failed: no disk · r retry", styles);
let spans: Vec<(&str, Style)> =
line.spans.iter().map(|span| (span.content.as_ref(), span.style)).collect();
assert_eq!(
spans,
[
("Refresh failed: no disk", styles.text),
(" · ", styles.muted),
("r", styles.accent),
(" retry", styles.text),
]
);
for key in ["space", "enter", "esc", "tab", "pgup", "pgdn", "alt+c", "enter/↓", "?", "g"] {
assert!(is_key(key), "{key}");
}
for word in ["Refresh", "Search:", "type", "go"] {
assert!(!is_key(word), "{word}");
}
}
/// Each footer shortcut is clickable across exactly the cells it is drawn in.
#[test]
fn footer_clicks_land_on_the_key_drawn_there() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let rows = frame_rows(&mut app, 160, 40);
let footer = rows.last().expect("footer row");
let at = |label: &str| -> u16 {
let byte = footer.find(label).unwrap_or_else(|| panic!("{label} in {footer:?}"));
UnicodeWidthStr::width(&footer[..byte]) as u16
};
let hit = app.hit.borrow();
let target = |x: u16| hit.at(x, 39).cloned();
let finish = crate::mouse::MouseTarget::ReviewFooter(ReviewFooterAction::Finish);
let next = crate::mouse::MouseTarget::ReviewFooter(ReviewFooterAction::HunkNext);
let start = at("alt+enter finish");
assert_eq!(target(start), Some(finish.clone()));
assert_eq!(target(start + 15), Some(finish.clone()), "to its last cell");
assert_ne!(target(start + 16), Some(finish.clone()), "and no further");
assert_ne!(target(start - 2), Some(finish), "not on the separator");
assert_eq!(target(at("space next")), Some(next));
}
/// The feedback window offers to send from inside itself, and only where sending does
/// anything: not on someone else's pull request, whose comments go to GitHub.
#[test]
fn the_feedback_window_offers_sending() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let hint = |app: &mut App| frame_rows(app, 160, 40).join("\n");
let own = hint(&mut app);
assert!(own.contains("c reply · u send · esc close"), "{own}");
app.guided_review.as_mut().expect("review").source.base =
luxe_core::guided_review::ReviewBase::PullRequest {
number: 42,
repository: "acme/notify".into(),
base_ref: "main".into(),
head_ref: "topic".into(),
merge_base: "4f1c2d9a7e6b5c4d3e2f1a0b9c8d7e6f5a4b3c2d".into(),
head_oid: "a9d9d84ee3e848f0e1ea97eaef837126d3a7d983".into(),
};
let theirs = hint(&mut app);
assert!(!theirs.contains("u send"), "{theirs}");
}
/// The footer names finishing, which is where committing and opening a pull request live, and
/// the feedback list once there is feedback to list.
#[test]
fn the_footer_names_finishing_and_the_feedback_list() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
// The diff pane's share of the bottom row: the rail's own foot shares the row now
let footer = |app: &mut App| {
let last = frame_rows(app, 160, 40).last().cloned().unwrap_or_default();
last.rsplit('│').next().unwrap_or_default().trim().to_owned()
};
let bare = footer(&mut app);
assert!(bare.contains("alt+enter finish") && !bare.contains("alt+c feedback"), "{bare}");
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
// The window takes the keyboard, and the footer with it
assert!(footer(&mut app).is_empty(), "no footer under the window");
app.guided_review_workspace.findings_visible = false;
let with = footer(&mut app);
assert!(with.contains("alt+c feedback") && with.contains("alt+enter finish"), "{with}");
assert!(!with.contains("esc"), "Esc is the key nobody has to be told: {with}");
}
/// Read to the end, the guide says what finishing does next, named for what the dialog will
/// offer: a branch with no pull request can open one, someone else's pull request is posted.
#[test]
fn read_to_the_end_the_guide_says_what_finishing_offers() {
let all_read = |scenario| {
let mut app = seeded_app("nord", scenario).expect("fixture app");
// A branch GitHub has no pull request for
let mut snapshot = crate::fixture::dock_workspace_snapshot();
snapshot.pull_request = luxe_core::workspace::PullRequestPresence::None;
app.workspace = Some(snapshot);
let review = app.guided_review.clone().expect("review");
let workspace = &mut app.guided_review_workspace;
(workspace.pull_request_opening, workspace.thread_answers) = (None, None);
workspace.github_post = None;
for chapter in &review.chapters {
workspace.walked_chapters.insert(chapter.id.clone());
}
frame_rows(&mut app, 160, 44).join("\n")
};
let mut unread = seeded_app("nord", FixtureScenario::GuidedReviewOpenPullRequest).unwrap();
assert!(!frame_rows(&mut unread, 160, 44).join("\n").contains("All read"));
let opening = all_read(FixtureScenario::GuidedReviewOpenPullRequest);
assert!(opening.contains("All read · alt+enter to open a pull request"), "{opening}");
let theirs = all_read(FixtureScenario::GuidedReviewPullRequest);
assert!(theirs.contains("All read · alt+enter to post your review"), "{theirs}");
let own = all_read(FixtureScenario::GuidedReviewOwnPullRequest);
assert!(own.contains("All read · alt+enter to answer on GitHub"), "{own}");
}
/// Space walks the review without finishing it; once it is on the last stop of the last
/// chapter, Space again is "what now" and opens the finish dialog — for a pull request, the
/// post preview it finishes with.
#[test]
fn space_past_the_last_stop_opens_the_finish_dialog() {
let space = |app: &mut App| app.update(crate::app::Msg::GuidedReviewHunkNext);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let review = app.guided_review.clone().expect("review");
let last = review.chapters.last().expect("chapters").id.clone();
let mut steps = 0;
while !(app.guided_review_workspace.position.chapter_id.as_ref() == Some(&last)
&& app.guided_review_workspace.at_scope_end(&review))
{
space(&mut app);
assert!(app.guided_review_workspace.finish_review_choice.is_none(), "not yet");
steps += 1;
assert!(steps < 100, "walked off the review");
}
assert!(app.guided_review_workspace.is_chapter_walked(&last), "landing marks it read");
assert!(app.guided_review_workspace.finish_review_choice.is_none());
space(&mut app);
assert!(app.guided_review_workspace.finish_review_choice.is_some(), "then finishes");
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequest).expect("fixture app");
let (tx, _rx) = tokio::sync::mpsc::channel(8);
app.engine_tx = tx;
for _ in 0..100 {
space(&mut app);
if app.guided_review_workspace.github_post.is_some() {
break;
}
}
assert!(app.guided_review_workspace.github_post.is_some(), "the post preview");
}
/// Walked to the last stop, the diff pane's end marker names the key that finishes.
#[test]
fn the_end_of_the_reading_names_the_finish_key() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let mut text = String::new();
for _ in 0..40 {
app.update(crate::app::Msg::GuidedReviewHunkNext);
text = frame_rows(&mut app, 160, 44).join("\n");
if text.contains("last chapter") {
break;
}
}
assert!(text.contains("— last chapter reviewed · space or alt+enter finishes —"), "{text}");
}
#[test]
fn low_height_review_keeps_header_diff_row_and_footer() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("review fixture");
let backend = TestBackend::new(160, 7);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render short review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Refactor notification model"));
assert!(text.contains("pub struct Notification"));
assert!(text.contains("space next"));
assert!(!text.contains("Review needs 40 × 5 cells"));
}
#[test]
fn base_reference_entry_footer_names_load_and_local_cancel() {
use crate::guided_review::ReviewSourceReferenceKind;
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.toggle_source_picker();
app.guided_review_workspace.begin_source_reference_entry(ReviewSourceReferenceKind::Base);
let backend = TestBackend::new(100, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render source picker");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("enter load base"));
assert!(text.contains("esc back"));
}

View File

@@ -0,0 +1,120 @@
//! Every chord the review footer advertises must actually resolve to something.
//!
//! This exists because `Enter` did not. Both footers said "Enter open" from the day the
//! walkthrough shipped, but nothing was bound to it, so it fell through the review router's
//! catch-all into `Msg::Tick` — the rows looked like a list and behaved like paint. A promise
//! printed on screen is a contract; this test is what keeps it one.
use super::*;
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
use crate::main_loop::{route_key, RouteAction};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
/// Turns a footer label's leading chord ("Alt+V hide guide", "s change source") into the key
/// event a user would produce. `None` for a label that names a constraint rather than a key.
fn chord_of(label: &str) -> Option<KeyEvent> {
let chord = label.split_whitespace().next()?;
if label.contains("needs") {
return None;
}
let (modifiers, key) = match chord.split_once('+') {
Some(("alt", key)) => (KeyModifiers::ALT, key),
Some(("ctrl", key)) => (KeyModifiers::CONTROL, key),
Some(("shift", key)) => (KeyModifiers::SHIFT, key),
Some(_) => return None,
None => (KeyModifiers::NONE, chord),
};
let code = match key {
"enter" => KeyCode::Enter,
"space" => KeyCode::Char(' '),
"esc" => KeyCode::Esc,
other => {
let mut characters = other.chars();
let first = characters.next()?;
// A multi-character token is a word, not a key. A modified letter arrives from
// the terminal in lower case however the label spells it (`Ctrl+B` → `ctrl+'b'`).
let code = if modifiers.is_empty() { first } else { first.to_ascii_lowercase() };
characters.next().is_none().then_some(KeyCode::Char(code))?
}
};
Some(KeyEvent::new(code, modifiers))
}
#[test]
fn every_advertised_footer_chord_resolves_to_an_action() {
// Every state the surface can be in: the guide shown and put away, at every width tier.
// A chord the footer promises has to resolve in all of them, which is the invariant that
// focus-conditional routing kept breaking.
for guide_visible in [true, false] {
for width in [80u16, 100, 120, 160, 200] {
let scenario = FixtureScenario::GuidedReviewReady;
let mut reference = seeded_app("nord", scenario).expect("fixture app");
reference.update(Msg::TerminalResized { width, height: 44 });
reference.guided_review_workspace.guide_visible = guide_visible;
for segment in ready_footer_segments(&reference, width) {
let Some(key) = chord_of(&segment.label) else { continue };
// A fresh app per chord: several of these open a composer or move a pane, and
// a shared one would test each key against the last key's aftermath.
let mut app = seeded_app("nord", scenario).expect("fixture app");
app.update(Msg::TerminalResized { width, height: 44 });
app.guided_review_workspace.guide_visible = guide_visible;
let routed = route_key(&mut app, &key);
let inert = matches!(&routed, RouteAction::Msg(message) if matches!(**message, Msg::Tick))
|| matches!(routed, RouteAction::None);
assert!(
!inert,
"footer advertises {:?} with guide_visible={guide_visible} at {width} cols, but the router drops it ({routed:?})",
segment.label
);
}
}
}
}
/// `g` puts the guide away and brings it back, and the old chord still does too.
#[test]
fn g_toggles_the_guide() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.update(Msg::TerminalResized { width: 200, height: 30 });
assert!(app.guided_review_workspace.guide_visible);
app.update(Msg::Key(KeyEvent::new(KeyCode::Char('g'), KeyModifiers::NONE)));
assert!(!app.guided_review_workspace.guide_visible, "g hides it");
app.update(Msg::Key(KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT)));
assert!(app.guided_review_workspace.guide_visible, "alt+v brings it back");
}
/// The help overlay and the footer are the same contract said twice, so they must say it the
/// same way. They drifted once already: the footer said `f read all` while help said `f read
/// what is accounted for`, for a key that did neither.
#[test]
fn help_and_the_footer_name_the_same_keys() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.update(Msg::TerminalResized { width: 160, height: 44 });
app.guided_review_workspace.toggle_help();
let backend = ratatui::backend::TestBackend::new(160, 44);
let mut terminal = ratatui::Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| super::render(frame, frame.area(), &app)).expect("render help");
let help: String = (0..44u16)
.map(|y| {
(0..160u16)
.map(|x| terminal.backend().buffer()[(x, y)].symbol().to_owned())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n");
for segment in ready_footer_segments(&app, 160) {
let Some(chord) = segment.label.split_whitespace().next() else { continue };
// Esc and `?` are the two universals; help names them in its own words.
if matches!(chord, "esc" | "?") {
continue;
}
assert!(
help.contains(chord),
"the footer offers {chord:?} but help never mentions it:\n{help}"
);
}
}

View File

@@ -0,0 +1,190 @@
//! Guide — the walkthrough pane, its head and foot, and its scrolling.
use super::*;
/// A pull request's review leads with where it stands and who opened it, then gives the
/// author's own account under a heading that says whose words they are. It says once that the
/// work was done elsewhere, instead of the "no record" row a working-tree review would get.
#[test]
fn a_pull_request_review_leads_with_the_pull_request() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 160, 90);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("pull request #42"), "{text}");
assert!(has("by copilot-swe-agent (bot)"), "{text}");
assert!(has("1 failing") && has("11 checks") && has("changes requested"), "{text}");
assert!(has("copilot/category-enum") && has("→ main"), "{text}");
assert!(has("What the pull request says"), "{text}");
assert!(has("What it closes") && has("#318 A typo in a webhook"), "{text}");
assert!(!has("No record of the work behind this source"), "{text}");
}
/// A review with no chapters has nothing to have read, so it never claims all of it.
#[test]
fn a_review_with_no_chapters_is_not_all_read() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture");
app.guided_review.as_mut().expect("review").chapters.clear();
let rows = frame_rows(&mut app, 160, 44);
assert!(!rows.iter().any(|row| row.contains("All read")), "{}", rows.join("\n"));
}
/// A rule sits under the guide's head and over its foot, in place of the blank rows that used
/// to space them, so the part that scrolls reads as its own zone. With no feedback there is no
/// foot, and no rule for it. The diff's keys sit under a rule of their own.
#[test]
fn the_guide_rules_off_its_head_and_its_foot() {
let ruled = |row: &str| row.trim_start().starts_with("──────────");
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
let head_end = rows.iter().position(|row| row.contains("changes requested")).expect("head");
assert!(ruled(&rows[head_end + 1]), "under the head: {text}");
assert!(!rows.iter().any(|row| row.contains("FEEDBACK")), "nothing to list: {text}");
assert_eq!(rows.iter().filter(|row| ruled(row)).count(), 1, "{text}");
let keys = rows.iter().position(|row| row.contains("space next")).expect("the keys");
let (_, over_keys) = rows[keys - 1].split_once('│').expect("the diff's column");
assert!(over_keys.starts_with(" ─────────"), "a cell clear of the divider: {text}");
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture app");
app.guided_review_workspace.github_post = None;
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
let foot = rows.iter().position(|row| row.contains("FEEDBACK")).expect("foot");
assert!(ruled(&rows[foot - 1]), "over the foot: {text}");
}
/// The guide can be read without walking the review, and lets go when the cursor moves.
///
/// The wheel over this pane used to move the file selection, so reading the section you were
/// not standing in was impossible: every notch dragged the review's position along with the
/// view. Scrolling is now scrolling — and it releases on the next cursor move, because an
/// offset that outlives the reason it was pinned is a pane stuck where nobody is looking.
#[test]
fn the_guide_scrolls_for_reading_and_hands_itself_back_when_the_cursor_moves() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewLarge).expect("fixture app");
app.update(crate::app::Msg::TerminalResized { width: 180, height: 44 });
let mut terminal = Terminal::new(TestBackend::new(180, 44)).expect("test terminal");
let mut draw = |app: &App| {
terminal.draw(|frame| render(frame, frame.area(), app)).expect("render");
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect::<String>()
};
let followed = draw(&app);
let before = app.guided_review_workspace.position.clone();
for _ in 0..6 {
app.update(crate::app::Msg::GuidedReviewScrollGuide { up: false });
}
let scrolled = draw(&app);
assert_ne!(followed, scrolled, "the wheel moved the prose");
assert_eq!(
app.guided_review_workspace.position, before,
"and moved nothing else: reading is not navigating"
);
// Moving the cursor is the reader saying they are done reading elsewhere.
app.update(crate::app::Msg::GuidedReviewHunkNext);
let _ = draw(&app);
assert!(
app.guided_review_workspace.guide_scroll.get().is_none(),
"the guide follows the cursor again"
);
}
/// Stepping with `Space` keeps the hunk being read on screen in the guide.
///
/// The pane used to follow the chapter's title, so on a short terminal a chapter with a few
/// paragraphs of prose walked its own files off the bottom while the reader stepped through
/// them, and finding out which file was open meant reaching for the wheel.
#[test]
fn the_guide_keeps_the_hunk_being_read_on_screen() {
use ratatui::{backend::TestBackend, Terminal};
let (width, height) = (180u16, 26u16);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewLarge).expect("fixture app");
app.update(crate::app::Msg::TerminalResized { width, height });
let guide = crate::workspace_layout::guide_pane_width(width);
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
let mut checked = 0;
for _ in 0..80 {
let before = app.guided_review_workspace.position.clone();
app.update(crate::app::Msg::GuidedReviewHunkNext);
if app.guided_review_workspace.position == before {
app.update(crate::app::Msg::GuidedReviewChapterNext);
}
if app.guided_review_workspace.position.hunk_id.is_none() {
continue;
}
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render");
let buffer = terminal.backend().buffer();
let marked = (0..height).any(|y| (0..guide).any(|x| buffer[(x, y)].symbol() == "\u{2503}"));
assert!(
marked,
"the hunk being read is off the guide at {:?}",
app.guided_review_workspace.position
);
checked += 1;
}
assert!(checked > 10, "the walk visited hunks: {checked}");
}
/// The overview is the whole change on one page: the prose, then every chapter and file.
/// The guide and its evidence are on screen together, which is what deleted the mode switch:
/// there is nothing left to switch between.
#[test]
fn the_guide_and_its_evidence_share_the_screen() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewDemo).expect("review fixture");
app.update(Msg::TerminalResized { width: 180, height: 44 });
let mut terminal = Terminal::new(TestBackend::new(180, 44)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("render");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
// The guide: the change's intent, its chapters, and the files under them.
assert!(text.contains("free-form string"), "the intent: {text}");
assert!(text.contains("Make an invalid category unrepresentable"), "the chapter: {text}");
assert!(text.contains("src/notification.rs"), "its files: {text}");
// And the evidence, at the same time.
assert!(text.contains("@@ "), "the diff is beside it, not behind a mode: {text}");
}
/// Four labeled sections used to sit between the intent and the contents, and every one of
/// them repeated something already on the rail or already printed on the item it described.
#[test]
fn the_guide_does_not_repeat_what_its_own_head_says() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewBrief).expect("review fixture");
app.update(Msg::TerminalResized { width: 180, height: 48 });
let mut terminal = Terminal::new(TestBackend::new(180, 48)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("render");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
for gone in [
"What backs it up",
"What needs you",
"What the guide might not tell you",
"Scale",
"Enter opens the selected row",
"Why this change",
"What it does",
"The walkthrough",
] {
assert!(!text.contains(gone), "{gone:?} is still on the page: {text}");
}
// The step is the only "where am I" on the page: an item count beside it counted a
// different noun, never moved as the reader walked, and disagreed with the chapter tally
// down the left.
assert!(!text.contains("to review"), "no second progress counter: {text}");
assert!(!text.contains("Chapters "), "the chapter tally is beside the chapters: {text}");
assert!(text.contains("Step 1 of 2"), "and the step is capitalized: {text}");
}

View File

@@ -0,0 +1,165 @@
//! The guide is a document you can point at, not a page of paint.
//!
//! Reported from a real session: the marker never appeared, `Enter` did nothing, and clicking a
//! row did nothing — three separate breaks that added up to "I can't navigate the walkthrough".
//! Two of the three were focus-conditional routing; the surface no longer has a focus to condition
//! on, and these are what say so.
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
use crate::main_loop::{route_key, route_mouse, RouteAction};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ratatui::{backend::TestBackend, Terminal};
fn review_app(scenario: FixtureScenario, width: u16, height: u16) -> crate::app::App {
let mut app = seeded_app("nord", scenario).expect("review fixture");
app.update(Msg::TerminalResized { width, height });
app
}
fn draw(app: &mut crate::app::App, width: u16, height: u16) -> String {
let mut terminal = Terminal::new(TestBackend::new(width, height)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
terminal.backend().buffer().content.iter().map(ratatui::buffer::Cell::symbol).collect()
}
/// A slab fades with the surface it sits on.
///
/// Style patching touches the foreground and leaves the background alone, so a section heading
/// kept its undiluted accent fill behind a modal while the triangle caps either side of it —
/// foreground glyphs — dimmed correctly. The heading was then the brightest thing on a
/// backgrounded surface, and the caps looked detached from a badge that had not moved.
#[test]
fn a_section_heading_dims_with_everything_else_behind_a_modal() {
let ramp = {
let app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
app.theme_styles.slab.ramp()
};
let slab_cells = |app: &mut crate::app::App| {
let mut terminal = Terminal::new(TestBackend::new(180, 44)).expect("test terminal");
terminal.draw(|frame| crate::view::render(frame, app)).expect("render");
terminal.backend().buffer().content.iter().filter(|cell| ramp.contains(&cell.bg)).count()
};
let mut app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
let bright = slab_cells(&mut app);
assert!(bright > 0, "the surface draws slab headings when nothing is over it");
app.guided_review_workspace.help_visible = true;
assert_eq!(
slab_cells(&mut app),
0,
"no slab fill survives a modal — chrome recedes with the surface it is chrome for",
);
}
/// The guide opens on the first chapter and marks it, so the document has a place in it from
/// the moment it is drawn.
#[test]
fn the_guide_opens_on_the_first_chapter() {
let mut app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
let content = draw(&mut app, 180, 44);
let first = app.guided_review.as_ref().expect("a review").chapters[0].id.clone();
assert_eq!(app.guided_review_workspace.position.chapter_id, Some(first));
assert!(content.contains('›'), "and says so on the row: {content}");
}
/// `↑`/`↓` scroll what is being read, in every state the surface can be in. They used to mean
/// one thing or the other depending on which pane held focus, and on the surface that needed
/// them most they meant nothing at all.
#[test]
fn the_arrows_always_scroll_the_diff() {
for guide_visible in [true, false] {
let mut app = review_app(FixtureScenario::GuidedReviewLarge, 180, 44);
app.guided_review_workspace.guide_visible = guide_visible;
draw(&mut app, 180, 44);
let before = app.guided_review_workspace.position.line_offset;
app.update(Msg::Key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)));
assert!(
app.guided_review_workspace.position.line_offset > before,
"guide_visible={guide_visible}: ↓ moves the reading"
);
app.update(Msg::Key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)));
assert_eq!(app.guided_review_workspace.position.line_offset, before);
}
}
/// Stepping a chapter moves the one selection, so both panes follow it together.
#[test]
fn stepping_a_chapter_moves_the_one_selection() {
let mut app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
draw(&mut app, 180, 44);
let review = app.guided_review.clone().expect("a review");
assert_eq!(
app.guided_review_workspace.position.chapter_id,
Some(review.chapters[0].id.clone())
);
app.update(Msg::Key(KeyEvent::new(KeyCode::Char(']'), KeyModifiers::NONE)));
assert_eq!(
app.guided_review_workspace.position.chapter_id,
Some(review.chapters[1].id.clone()),
"] moves the chapter"
);
// And the diff follows: the file on screen belongs to the chapter the guide now marks.
let file = app.guided_review_workspace.position.file_id.clone().expect("a file");
let reach = &review.chapters[1];
let owner = review.files.iter().find(|candidate| candidate.id == file).expect("the file");
assert!(
reach.items.iter().any(|item| match item {
luxe_core::guided_review::ReviewItemRef::File(id) => *id == owner.id,
luxe_core::guided_review::ReviewItemRef::Hunk(id) =>
owner.hunks.iter().any(|hunk| hunk.id == *id),
}),
"the narration on screen owns the diff on screen"
);
}
/// Clicking a chapter row in the guide points the review at it.
#[test]
fn clicking_a_guide_chapter_opens_it() {
let mut app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
draw(&mut app, 180, 44);
let (rect, chapter_id) = app
.hit
.borrow()
.clicks()
.find_map(|(rect, target)| match target {
crate::mouse::MouseTarget::ReviewGuideChapter(id) => Some((rect, id.clone())),
_ => None,
})
.expect("the guide publishes its chapter rows as click targets");
let click = MouseEvent {
kind: MouseEventKind::Down(MouseButton::Left),
column: rect.x + 1,
row: rect.y,
modifiers: KeyModifiers::NONE,
};
let routed = route_mouse(&mut app, &click);
assert!(
matches!(&routed, RouteAction::Msg(message)
if matches!(&**message, Msg::GuidedReviewOpenChapter(id) if *id == chapter_id)),
"clicking a chapter opens it: {routed:?}"
);
}
/// `Alt+V` puts the guide away and brings it back, and the diff takes the room.
#[test]
fn the_guide_can_be_put_away() {
let mut app = review_app(FixtureScenario::GuidedReviewDemo, 180, 44);
let with_guide = draw(&mut app, 180, 44);
assert!(with_guide.contains("REVIEW"), "the guide names itself: {with_guide}");
let routed = route_key(&mut app, &KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT));
assert!(
!matches!(&routed, RouteAction::Msg(message) if matches!(**message, Msg::Tick)),
"alt+v is routed: {routed:?}"
);
app.update(Msg::GuidedReviewToggleGuide);
let without = draw(&mut app, 180, 44);
assert!(!without.contains("REVIEW"), "the guide is away: {without}");
assert!(without.contains("alt+v shows the guide"), "and says how to bring it back");
}

View File

@@ -0,0 +1,273 @@
//! Loading — fetching, failing and refreshing, and the recovery each offers.
use super::*;
/// A failed load keeps its way out, and a failed refresh of a review on screen says why when
/// there is room to.
#[test]
fn a_failed_load_names_its_recovery_at_every_width() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewRefreshing).expect("refresh fixture");
app.guided_review_workspace.mark_failed(
ReviewTarget::WorkingTree,
GuidedReviewFailure { kind: GuidedReviewFailureKind::Capture, message: "gone".into() },
);
assert!(resolve_footer(&app, 90).0.starts_with("Refresh failed: gone"));
assert_eq!(resolve_footer(&app, 89).0, "r retry · s change source · esc back to chat");
assert_eq!(resolve_footer(&app, 60).0, "r retry · s change source · esc back to chat");
assert_eq!(resolve_footer(&app, 59).0, "r retry · esc back");
app.guided_review = None;
assert_eq!(
resolve_footer(&app, 120).0,
"r retry · s change source · esc back to chat",
"with no review behind it there is nothing to refresh"
);
}
/// Fetching waits on the network, so the loading row says that is what it is doing.
#[test]
fn loading_a_pull_request_says_it_is_fetching() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review = None;
app.guided_review_workspace.load_state = GuidedReviewLoadState::Loading {
target: ReviewTarget::PullRequest { number: 42, repository: None },
};
let rows = frame_rows(&mut app, 120, 30);
assert!(rows.iter().any(|row| row.contains("Fetching pull request #42")), "{rows:?}");
assert!(rows.iter().any(|row| row.contains("Your working tree is not touched")), "{rows:?}");
}
#[test]
fn wide_header_shows_available_source_totals() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
let review = app.guided_review.as_ref().expect("fixture review");
let additions = review.stats.additions.expect("fixture additions");
let deletions = review.stats.deletions.expect("fixture deletions");
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render wide header");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
let files = review.stats.files;
let noun = if files == 1 { "file" } else { "files" };
assert!(text.contains(&format!("{files} {noun}")));
assert!(text.contains(&format!("+{additions} −{deletions}")));
}
#[test]
fn findings_drawer_offers_cancellation_only_for_a_queued_current_source_submission() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding_id = app
.review
.session()
.expect("review session")
.findings
.first()
.expect("fixture finding")
.id
.clone();
app.review
.session_mut()
.expect("review session")
.queue_submission(
luxe_core::guided_review::SubmissionId::new(),
luxe_core::guided_review::ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&[],
0,
)
.expect("queue submission");
app.guided_review_workspace.selected_finding_id = Some(finding_id);
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings drawer");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("x cancel sending"));
assert!(!text.contains("x delete"));
}
#[test]
fn findings_drawer_offers_retry_only_for_a_failed_current_source_submission() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let finding_id = app
.review
.session()
.expect("review session")
.findings
.first()
.expect("fixture finding")
.id
.clone();
let submission_id = luxe_core::guided_review::SubmissionId::new();
let session = app.review.session_mut().expect("review session");
session
.queue_submission(
submission_id.clone(),
luxe_core::guided_review::ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&[],
0,
)
.expect("queue submission");
session.dispatch_submission(&submission_id).expect("dispatch submission");
session.fail_submission(&submission_id).expect("fail submission");
app.guided_review_workspace.selected_finding_id = Some(finding_id);
app.guided_review_workspace.findings_visible = true;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render findings drawer");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("r retry sending"));
assert!(!text.contains("r resolve"));
}
#[test]
fn source_labels_preserve_the_selected_local_target() {
assert_eq!(source_label(&ReviewTarget::WorkingTree), "working tree");
assert_eq!(
source_label(&ReviewTarget::Base { reference: "origin/main".into() }),
"base origin/main"
);
}
#[test]
fn tiny_review_shows_the_minimum_size_and_return_affordance() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("review fixture");
let backend = TestBackend::new(39, 4);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render tiny review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Review needs 40 × 5 cells"));
assert!(text.contains("Resize, or esc back to chat"));
}
#[test]
fn long_failed_refresh_detail_keeps_wide_recovery_actions_visible() {
use ratatui::{backend::TestBackend, Terminal};
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewRefreshing).expect("refresh fixture");
app.guided_review_workspace.mark_failed(
ReviewTarget::WorkingTree,
GuidedReviewFailure { kind: GuidedReviewFailureKind::Capture, message: "界".repeat(100) },
);
let backend = TestBackend::new(100, 16);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render long failure");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Refresh failed:"));
assert!(text.contains("r retry"));
assert!(text.contains("s change source"));
assert!(text.contains("esc back to chat"));
}
#[test]
fn failed_refresh_keeps_the_pinned_diff_visible_with_recovery_controls() {
use ratatui::{backend::TestBackend, Terminal};
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewRefreshing).expect("refresh fixture");
app.guided_review_workspace.mark_failed(
ReviewTarget::WorkingTree,
GuidedReviewFailure {
kind: GuidedReviewFailureKind::Capture,
message: "source changed while capturing".into(),
},
);
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render failed refresh");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Refresh failed"));
assert!(text.contains("revision retained"));
assert!(text.contains("source changed while capturing"));
assert!(text.contains("src/notification.rs"));
assert!(text.contains("r retry"));
assert!(text.contains("s change source"));
}
#[test]
fn refresh_keeps_the_pinned_diff_visible_with_a_stale_indicator() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewRefreshing).expect("refresh fixture");
let backend = TestBackend::new(160, 32);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render refreshing review");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("Refreshing"));
assert!(text.contains("revision retained"));
assert!(text.contains("src/notification.rs"));
assert!(text.contains("pub struct Notification"));
}
#[test]
fn load_failure_shows_typed_error_and_width_appropriate_recovery_controls() {
use ratatui::{backend::TestBackend, Terminal};
let app = seeded_app("nord", FixtureScenario::GuidedReviewError).expect("error fixture");
let wide_backend = TestBackend::new(100, 30);
let mut wide_terminal = Terminal::new(wide_backend).expect("wide terminal");
wide_terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render wide error");
let wide: String =
wide_terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
let narrow_backend = TestBackend::new(58, 20);
let mut narrow_terminal = Terminal::new(narrow_backend).expect("narrow terminal");
narrow_terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render narrow error");
let narrow: String =
narrow_terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(wide.contains("Guided Review could not load"));
assert!(wide.contains("Could not capture a complete immutable"));
assert!(wide.contains("r retry"));
assert!(wide.contains("s change source"));
assert!(narrow.contains("r retry"));
assert!(!narrow.contains("s change source"));
}
#[test]
fn unavailable_last_turn_is_visibly_disabled_in_source_picker() {
use ratatui::{backend::TestBackend, Terminal};
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
app.guided_review_workspace.source_picker =
ReviewSourcePickerState::Open { selection: ReviewSourcePickerSelection::LastTurn };
let backend = TestBackend::new(100, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render source picker");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("× Last Turn"));
assert!(text.contains("unavailable — no completed turn"));
}

View File

@@ -0,0 +1,464 @@
//! Previews — the dialogs that confirm before anything leaves: post, answers, pull request, fix and stack.
use super::*;
/// Rows of the modal titled `title`: its top border's, and its footer rule's, which is where
/// what the modal says ends. The keys sit under the rule, on the last row inside the frame.
pub(super) fn modal_rows(rows: &[String], title: &str) -> (usize, usize) {
let top = rows
.iter()
.position(|row| row.contains(title) && row.contains(['╭', '┌']))
.expect("top border");
let keys = (top + 2..rows.len().saturating_sub(1))
.find(|&y| {
rows[y].contains("esc")
&& rows[y - 1].contains("────")
&& rows[y + 1].contains(['╰', '└'])
})
.expect("the footer");
(top, keys - 1)
}
/// The pull request preview is exactly as tall as what it holds: the heading under its top
/// border and the description down to the footer's rule, with nothing pinned under it. It
/// drafts and fails in a small box, a title being written wraps, and the scrollbar keeps its
/// own column.
#[test]
fn the_pull_request_preview_holds_exactly_what_it_shows() {
use crate::guided_review::OpeningField;
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewOpenPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 150, 44);
let (top, bottom) = modal_rows(&rows, "Open pull request");
assert!(rows[top + 1].contains("Into main from"), "{}", rows.join("\n"));
let closes = rows.iter().position(|row| row.contains("Closes #123")).expect("body");
assert_eq!(closes, bottom - 1, "{}", rows.join("\n"));
assert!(!rows[bottom].contains("scroll"), "a short description does not scroll");
// A title being written wraps onto a second row rather than running off
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
let mut editor = crate::editor::Editor::new();
editor.insert_text(&"A title that goes on ".repeat(8));
opening.editing = Some((OpeningField::Title, editor));
let rows = frame_rows(&mut app, 150, 44);
let label = rows.iter().position(|row| row.contains("│ Title")).expect("title label");
assert!(rows[label + 1].contains("A title that goes on"), "{}", rows.join("\n"));
assert!(rows[label + 2].contains("A title that goes on"), "wrapped: {}", rows.join("\n"));
assert!(rows[label + 4].contains("Description"), "{}", rows.join("\n"));
// Every body line one column wider than the text, so each wraps and none may reach the
// scrollbar's column: 120 wide at 15, less the frame and pad, less that column
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
opening.editing = None;
let prepared = opening.prepared.as_mut().expect("prepared");
// Alternately exactly as wide as the text, which ends at the lane's edge, and one wider,
// which must wrap rather than spill into the lane
let line = |n: usize| format!("{n:03} {}", "x".repeat(112 + n % 2));
assert_eq!((line(0).len(), line(1).len()), (116, 117));
prepared.pull_request.body = (0..60).map(line).collect::<Vec<_>>().join("\n\n");
let rows = frame_rows(&mut app, 150, 44);
let (top, bottom) = modal_rows(&rows, "Open pull request");
let corners: Vec<char> = rows[top].chars().collect();
let (left, right) = (
corners.iter().position(|c| matches!(c, '╭' | '┌')).unwrap(),
corners.iter().position(|c| matches!(c, '╮' | '┐')).unwrap(),
);
assert_eq!(right - left + 1, 120, "{}", rows[top]);
for row in &rows[top + 7..bottom - 3] {
let lane = row.chars().nth(right - 1).unwrap_or(' ');
assert!(!lane.is_alphanumeric(), "{row}");
let text = row.chars().nth(right - 2).unwrap_or(' ');
assert!(text == 'x' || text == ' ', "the text reaches the lane's edge: {row}");
}
assert!(rows[top + 7..bottom].iter().any(|row| row.chars().nth(right - 2) == Some('x')));
// The wider lines wrapped: a row begins with their remainder, not with a line number. A
// pane counted a column wider would fit them whole, with the last letter under the bar.
let wrapped = rows[top + 7..bottom].iter().any(|row| row.chars().nth(left + 2) == Some('x'));
assert!(wrapped, "{}", rows.join("\n"));
// Drafting, and failing, in a box sized to the words
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
opening.prepared = None;
opening.error = Some("GitHub would not say. ".repeat(12));
let rows = frame_rows(&mut app, 150, 44);
let (top, bottom) = modal_rows(&rows, "Open pull request");
let wrapped = rows[top + 1..bottom].iter().filter(|row| row.contains("GitHub")).count();
assert!(wrapped >= 2, "{}", rows.join("\n"));
assert_eq!(bottom - top + 1, (wrapped + 3).max(5), "{}", rows.join("\n"));
}
/// The post preview lists what GitHub will get — the review, then each comment on a line —
/// and shows the whole text of the one under the cursor, before anything is sent.
#[test]
fn the_post_preview_shows_what_each_comment_says_and_where() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture app");
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Post this review to acme/notify#42"), "{text}");
// The chosen verdict is the cut tab, with its icon and no arrow
assert!(has("Request changes") && !has("› Request changes"), "{text}");
// The review's own text, whole, in the pane: both paragraphs, not a title
assert!(has("An unknown category now fails the whole webhook"), "{text}");
assert!(has("Can we log and drop those for one release"), "{text}");
// Under its file, the way GitHub groups a review's comments
let listed = rows.windows(2).any(|pair| {
pair[0].contains("│ src/notification.rs ") && pair[1].contains("│ line 13 ")
});
assert!(listed, "the line comment is listed: {text}");
assert!(has("Summary"), "{text}");
assert!(!has("The review's own comment"), "the pane explains nothing the list shows: {text}");
// The keys on the frame sit under a rule of their own
let keys = rows.iter().position(|row| row.contains("enter post")).expect("the keys");
assert!(rows[keys - 1].contains("──────────"), "{text}");
// The question went to the agent and was answered; it is neither listed nor explained
assert_eq!(crate::app::github_post_item_count(&app), 2, "the review and one line comment");
assert!(!has("not posted"), "{text}");
// The card says what posts it, and carries no agent label: GitHub has no `R2`
assert!(has("alt+enter to post"), "{text}");
assert!(!has("R2"), "{text}");
assert!(
has("FEEDBACK") && has(" 3 · 2 unposted"),
"a question is not waiting to be posted: {text}"
);
assert!(has("○ notification.rs:13 Worth a doc comment here"), "the foot lists it: {text}");
assert!(
has("enter post · ↑/↓ comment · tab verdict · d draft summary · e edit summary"),
"{text}"
);
assert!(!has("pushed after"), "{text}");
// Down moves to the line comment, and the pane follows with its place and its words
app.update(crate::app::Msg::GuidedReviewMoveGithubPostItem(true));
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
assert_eq!(
rows.iter().filter(|row| row.contains("src/notification.rs:13")).count(),
1,
"heading the pane: {text}"
);
// Under the diff it sits on, ending at its own line, marked
let own = rows.iter().find(|row| row.contains("▎13 +")).expect("its line, marked");
assert!(own.contains("pub category: Category"), "{text}");
assert!(rows.iter().any(|row| row.contains("13 -") && row.contains("String")), "{text}");
assert!(!rows.iter().any(|row| row.contains("Can we log and drop")), "{text}");
assert!(rows.iter().any(|row| row.contains("Worth a doc comment here")), "{text}");
let post = app.guided_review_workspace.github_post.as_mut().expect("post preview");
let prepared = post.prepared.as_mut().expect("prepared");
prepared.head_moved = true;
prepared.own_pull_request = true;
post.verdict = luxe_core::github::ReviewEvent::Comment;
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Your pull request · comment only"), "{text}");
assert!(has("Pushed since you read it"), "{text}");
assert!(
has("enter post · ↑/↓ comment · d draft summary · e edit summary · w fix in a worktree · esc cancel"),
"a lone verdict offers no choice: {text}"
);
// Once everything is posted, the preview says so rather than asking for a comment
let posted = luxe_core::guided_review::PostedComment { review_id: 9, url: String::new() };
for finding in &mut app.review.session_mut().expect("session").findings {
if finding.severity != luxe_core::guided_review::FindingSeverity::Question {
finding.posted = Some(posted.clone());
}
}
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Already on GitHub · nothing new to post"), "{text}");
assert!(has("2 comments already on GitHub"), "{text}");
}
/// A narrow terminal keeps the keys that post and leave, dropping the rest to fit the frame.
#[test]
fn a_narrow_post_preview_keeps_its_keys_inside_the_frame() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture app");
let rows = frame_rows(&mut app, 72, 30);
let text = rows.join("\n");
let hint = rows.iter().find(|row| row.contains("enter post")).expect("the keys");
assert!(hint.contains("esc cancel"), "{text}");
assert!(!hint.contains("w fix in a worktree"), "the least-needed key goes: {text}");
assert!(hint.trim_end().ends_with('│'), "inside the frame, on a row of its own: {text}");
}
/// While it reads the pull request there is nothing to retry, so the preview offers only a
/// way out; once reading failed, Enter asks again. Titles read as plain text.
#[test]
fn the_post_preview_offers_a_retry_only_after_a_failure() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture app");
for finding in &mut app.review.session_mut().expect("session").findings {
finding.title = format!("Pin **{}**", finding.title);
}
let rows = frame_rows(&mut app, 160, 46);
let text = rows.join("\n");
assert!(text.contains("Pin ") && !text.contains("**"), "{text}");
let post = app.guided_review_workspace.github_post.as_mut().expect("preview");
post.prepared = None;
let rows = frame_rows(&mut app, 160, 46);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Reading the pull request…") && has("esc cancel"));
assert!(!has("enter retry"), "{}", rows.join("\n"));
app.guided_review_workspace.github_post.as_mut().expect("preview").error =
Some("GitHub did not answer.".into());
let rows = frame_rows(&mut app, 160, 46);
assert!(rows.iter().any(|row| row.contains("enter retry · esc cancel")));
}
/// The answers preview says whether the fix is on GitHub, what each thread will get — a
/// resolve, a reply in the reader's words — and where it stands locally. The threads it lists
/// are feedback now, so the brief counts them there instead of listing them twice.
#[test]
fn the_answers_preview_says_what_each_thread_gets() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewOwnPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 160, 60);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Answer these threads on acme/notify#42"), "{text}");
assert!(has("Resolving closes the thread; leave it open for the reviewer"), "{text}");
assert!(has("Your fix is not on GitHub yet: push this branch first."), "{text}");
assert!(has("✓ resolve") && has("verified"), "{text}");
assert!(has("reply: Only the webhook built it from a string"), "{text}");
let replies = rows.iter().filter(|row| row.contains("reply: ")).count();
assert_eq!(replies, 1, "a thread with nothing written shows no reply: {text}");
assert!(has("○ leave open") && has("open · mara"), "{text}");
assert!(
has("› ✓ resolve") && has(" ○ leave open"),
"the cursor marks the selected thread: {text}"
);
assert!(!has("R1") && !has("R2"), "the agent's names for threads stay off GitHub's: {text}");
assert!(has("enter post · space resolve · c reply"), "{text}");
// A fix the agent made and the reader has not looked at yet
for finding in &mut app.review.session_mut().expect("session").findings {
if finding.title.starts_with("jon-avery:") {
finding.state = luxe_core::guided_review::FindingState::NeedsVerification;
}
}
let answers = app.guided_review_workspace.thread_answers.as_mut().expect("preview");
answers.selected = 1;
let mut editor = crate::editor::Editor::new();
editor.insert_text("On it");
answers.replying = Some(editor);
let rows = frame_rows(&mut app, 160, 60);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Reply to @mara-okafor · type below") && has("On it"), "{text}");
assert!(has("reply: Only the webhook"), "another thread's reply stays listed: {text}");
assert_eq!(rows.iter().filter(|row| row.contains("type below")).count(), 1);
assert!(has("to verify · jon-avery:"), "{text}");
assert!(has("ctrl+enter save · esc cancel"), "{text}");
assert!(has("3 in your feedback"), "{text}");
assert!(has("○ conversation") && has("jon-avery: Could the changelog"), "{text}");
assert!(has("pull request #42 · notify"), "{text}");
}
/// The pull request preview shows where it goes, what happens first, and the draft; each field
/// edits in place, and the states before and after a draft say what they are.
#[test]
fn the_pull_request_preview_shows_the_draft_and_what_happens_first() {
use crate::guided_review::OpeningField;
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewOpenPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 150, 44);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Open pull request"), "{text}");
assert!(has("Into main from 123-category-enum · commits and pushes first"), "{text}");
assert!(!has("ready for review"), "a pull request is ready unless it is a draft: {text}");
assert!(has("Title") && has("Refactor notification model"), "{text}");
// The description is drawn as markdown: its heading is a heading, not three hashes
assert!(has("Description") && has("Shared notification model"), "{text}");
assert!(!has("### Shared"), "{text}");
assert!(has("Closes #123"), "{text}");
assert!(
has("enter open · t title · e description · E in your editor · d draft · esc cancel"),
"{text}"
);
// Centered: as far from the left edge as from the right
let top: Vec<char> =
rows.iter().find(|row| row.contains("Open pull request")).expect("top").chars().collect();
let left = top.iter().position(|c| matches!(c, '╭' | '┌')).expect("left corner");
// rows come back trimmed, so the right margin counts from the frame's width
let right = 150 - 1 - top.iter().rposition(|c| matches!(c, '╮' | '┐')).expect("corner");
assert!(left > 10 && left.abs_diff(right) <= 1, "{left} vs {right}: {text}");
// As tall as the draft
let top_row = rows.iter().position(|row| row.contains("Open pull request")).expect("top");
let bottom_row = rows.iter().position(|row| row.contains("esc cancel ")).expect("bottom");
assert!(rows[bottom_row - 1].contains("────"), "the keys under their rule: {text}");
assert!(rows[bottom_row - 2].contains("Closes #123"), "{text}");
let below = rows.len() - 1 - bottom_row;
assert!(top_row > 5 && top_row.abs_diff(below) <= 3, "{top_row} vs {below}: {text}");
// Editing shows the terminal's own cursor in the field, where typing lands
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
let editor = crate::editor::Editor::with_text("Name the categories", "Name the".len());
opening.editing = Some((OpeningField::Title, editor));
let (rows, _, before) = frame_with_cursor(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Name the categories"), "{}", rows.join("\n"));
assert!(has("enter save · esc cancel"), "{}", rows.join("\n"));
assert!(before.ends_with("Name the"), "{before:?}");
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
let mut editor = crate::editor::Editor::new();
editor.insert_text("First line\nSecond line");
opening.editing = Some((OpeningField::Body, editor));
let (rows, _, before) = frame_with_cursor(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("First line") && has("Second line"), "{}", rows.join("\n"));
assert!(before.ends_with("Second line"), "{before:?}");
assert!(has("ctrl+enter save · esc cancel"), "{}", rows.join("\n"));
// A long description scrolls, and says so
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
opening.editing = None;
let prepared = opening.prepared.as_mut().expect("prepared");
prepared.pull_request.body =
(1..=80).map(|n| format!("- item {n}")).collect::<Vec<_>>().join("\n");
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("item 1") && !has("item 80"), "{}", rows.join("\n"));
assert!(has("↑/↓ scroll"), "{}", rows.join("\n"));
assert!(has("Into main from 123-category-enum · commits and"), "{}", rows.join("\n"));
app.update(crate::app::Msg::GuidedReviewScrollPullRequest(1000));
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("item 80") && !has("item 1 "), "{}", rows.join("\n"));
app.update(crate::app::Msg::GuidedReviewScrollPullRequest(-1));
let rows = frame_rows(&mut app, 150, 44);
assert!(!rows.iter().any(|row| row.contains("item 80")), "one row up moves at once");
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
let prepared = opening.prepared.as_mut().expect("prepared");
prepared.pull_request.body = " ".into();
prepared.commits.clear();
prepared.uncommitted = 0;
prepared.publication = luxe_core::github::Publication::Pushed;
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("(no description)") && !has("first"), "nothing to do first: {}", rows.join("\n"));
assert!(!has("left out"), "{}", rows.join("\n"));
assert!(!has("scroll"), "{}", rows.join("\n"));
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
opening.prepared = None;
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Drafting it from the review…") && has("esc cancel"), "{}", rows.join("\n"));
assert!(!has("Enter try again"), "{}", rows.join("\n"));
let opening = app.guided_review_workspace.pull_request_opening.as_mut().expect("preview");
opening.error = Some("You're on `main`, the branch it would merge into.".into());
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("You're on main,") && !has("Drafting"), "{}", rows.join("\n"));
assert!(has("enter try again · esc cancel"), "{}", rows.join("\n"));
}
/// The offer to fix a pull request says where it goes and what goes with it, while GitHub is
/// asked says so, and a refusal says why and offers nothing to confirm.
#[test]
fn the_fix_offer_says_where_it_goes_or_why_not() {
let mut app =
seeded_app("nord", FixtureScenario::GuidedReviewFixPullRequest).expect("fixture app");
let rows = frame_rows(&mut app, 150, 44);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Fix in a worktree") && has("Checks #42 out on fix-redirects"), "{text}");
assert!(has("with your 3 comments for the agent to address."), "{text}");
assert!(has("enter check out · esc cancel"), "{text}");
let top = rows.iter().position(|row| row.contains("Fix in a worktree")).expect("top");
let bottom = rows.iter().position(|row| row.contains("esc cancel ")).expect("bottom");
assert!(rows[bottom - 2].contains("come back to this session at any time"), "tight: {text}");
assert!(top > 5 && top.abs_diff(rows.len() - 1 - bottom) <= 3, "centered: {text}");
let corner = rows[top].chars().position(|c| matches!(c, '╭' | '┌')).expect("corner");
let right = 150
- 1
- rows[top]
.chars()
.collect::<Vec<_>>()
.iter()
.rposition(|c| matches!(c, '╮' | '┐'))
.unwrap();
assert!(corner > 10 && corner.abs_diff(right) <= 1, "{corner} vs {right}");
for (comments, said) in [(1, "with your comment for the agent to address."), (0, "│ session.")]
{
app.guided_review_workspace.pull_request_fix.as_mut().unwrap().comments = comments;
let rows = frame_rows(&mut app, 150, 44);
assert!(rows.iter().any(|row| row.contains(said)), "{}", rows.join("\n"));
}
let fix = app.guided_review_workspace.pull_request_fix.as_mut().unwrap();
fix.branch = None;
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Asking GitHub whether a fix could reach #42") && has("esc close"));
let fix = app.guided_review_workspace.pull_request_fix.as_mut().unwrap();
fix.refusal = Some("The author did not allow edits by maintainers.".into());
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("did not allow edits") && has("esc close") && !has("Enter check out"));
assert!(!has("Asking GitHub"), "{}", rows.join("\n"));
}
/// The stack preview lists every pull request with its branch, says what happens first, and
/// says drafts, drafting, opening and a failure as each comes.
#[test]
fn the_stack_preview_lists_each_pull_request_and_what_happens_first() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewOpenStack).expect("fixture app");
let rows = frame_rows(&mut app, 150, 44);
let text = rows.join("\n");
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(
has("3 pull requests into main, each based on the one below · commits and pushes first"),
"{text}"
);
assert!(!has("ready for review"), "{text}");
assert!(has("1. 123-category-enum-part-1 — Shared notification model"), "{text}");
assert!(has("3. 123-category-enum — Reject unknown categories"), "{text}");
assert!(has("enter open · d draft · esc cancel"), "{text}");
let top = rows.iter().position(|row| row.contains("Open as a stack")).expect("top");
let bottom = rows.iter().position(|row| row.contains("esc cancel ")).expect("bottom");
assert!(rows[bottom - 2].contains("Reject unknown categories"), "tight: {text}");
assert!(top > 5 && top.abs_diff(rows.len() - 1 - bottom) <= 3, "centered: {text}");
let corner = rows[top].chars().position(|c| matches!(c, '╭' | '┌')).expect("corner");
let edge: Vec<char> = rows[top].chars().collect();
let right = 150 - 1 - edge.iter().rposition(|c| matches!(c, '╮' | '┐')).unwrap();
assert!(corner > 10 && corner.abs_diff(right) <= 1, "{corner} vs {right}");
let stack = app.guided_review_workspace.stack_opening.as_mut().unwrap();
stack.draft = true;
let rows = frame_rows(&mut app, 150, 44);
assert!(rows.iter().any(|row| row.contains("each based on the one below · as drafts")));
let stack = app.guided_review_workspace.stack_opening.as_mut().unwrap();
stack.opening = true;
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Opening the stack…") && has("opening…"), "{}", rows.join("\n"));
let stack = app.guided_review_workspace.stack_opening.as_mut().unwrap();
stack.opening = false;
stack.layers = None;
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("Drafting a pull request per chapter") && has("esc close"));
let stack = app.guided_review_workspace.stack_opening.as_mut().unwrap();
stack.error = Some("One chapter is one pull request.".into());
let rows = frame_rows(&mut app, 150, 44);
let has = |phrase: &str| rows.iter().any(|row| row.contains(phrase));
assert!(has("One chapter is one pull request.") && !has("Drafting"));
}

View File

@@ -0,0 +1,43 @@
//! Rail divider — tests moved out of the module they cover.
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
/// The rule clears the screen top and runs down through the shortcut row, and the shortcuts
/// start beside it rather than centered under both panes: they are the diff's keys.
#[test]
fn the_rail_rule_runs_down_beside_the_diffs_shortcuts() {
let (width, height) = (170, 44);
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewWide).unwrap();
app.update(Msg::TerminalResized { width, height });
let backend = ratatui::backend::TestBackend::new(width, height);
let mut terminal = ratatui::Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| super::render(frame, frame.area(), &app)).expect("render the review");
let buffer = terminal.backend().buffer().clone();
let column = (0..width)
.find(|x| {
(0..height).filter(|y| buffer[(*x, *y)].symbol() == "│").count()
> usize::from(height / 2)
})
.expect("a vertical rule exists");
let rows: Vec<u16> = (0..height).filter(|y| buffer[(column, *y)].symbol() == "│").collect();
assert!(!rows.contains(&0), "the rule clears the top row: {rows:?}");
assert!(rows.contains(&(height - 1)), "the rule reaches the shortcut row: {rows:?}");
assert!(rows.len() > 10, "it is still a rule, not a stub: {rows:?}");
// Where you are sits on the heading's row, at the rail's right edge, like peek's `2 of 5`
let head: String = (0..column).map(|x| buffer[(x, 1)].symbol()).collect();
assert!(head.contains("REVIEW"), "{head:?}");
assert!(head.trim_end().ends_with("Step 1 of 2"), "{head:?}");
let foot: String = (0..width).map(|x| buffer[(x, height - 1)].symbol()).collect();
let first_key = foot.find("space").expect("the footer names Space");
assert_eq!(
foot[..first_key].chars().count(),
usize::from(column) + 2,
"the shortcuts start one cell into the diff pane: {foot:?}"
);
}

View File

@@ -0,0 +1,69 @@
//! Scale — tests moved out of the module they cover.
use crate::app::Msg;
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::keymap::UiAction;
use std::collections::HashSet;
/// Every hunk stays reachable at scale. Chapter containment keeps the narrative honest, so the
/// walk has to prove it does not also strand part of the diff.
#[test]
fn every_hunk_in_a_large_review_is_reachable() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewLarge).expect("fixture app");
app.update(Msg::TerminalResized { width: 160, height: 44 });
// Folded noise counts too: the fold promises reachability, not omission.
app.update(Msg::DispatchUiAction(UiAction::ReviewToggleNoise));
let review = app.guided_review.clone().expect("large review");
let total: usize = review.files.iter().map(|file| file.hunks.len()).sum();
let mut seen: HashSet<String> = HashSet::new();
for _ in 0..review.chapters.len() {
for _ in 0..=total {
if let Some(hunk) = app.guided_review_workspace.position.hunk_id.as_ref() {
seen.insert(hunk.as_str().to_owned());
}
app.update(Msg::DispatchUiAction(UiAction::ReviewHunkNext));
}
app.update(Msg::DispatchUiAction(UiAction::ReviewChapterNext));
}
assert_eq!(seen.len(), total, "reached {} of {total} hunks", seen.len());
}
/// Non-text items are reachable too — a rename and a binary asset are review items, not gaps.
#[test]
fn non_text_items_are_reachable_at_scale() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewLarge).expect("fixture app");
app.update(Msg::TerminalResized { width: 160, height: 44 });
let review = app.guided_review.clone().expect("large review");
let non_text: Vec<_> = review
.files
.iter()
.filter(|file| file.non_text.is_some())
.map(|file| file.id.clone())
.collect();
assert!(non_text.len() >= 2, "the fixture carries a rename and a binary");
// Every non-text item stays reachable by walking chapters and stepping inside them: fold
// state and chapter containment must not strand part of the diff.
app.update(Msg::DispatchUiAction(UiAction::ReviewToggleNoise));
let mut seen = HashSet::new();
let items: usize = review
.files
.iter()
.map(|file| file.hunks.len() + usize::from(file.non_text.is_some()))
.sum();
for _ in 0..review.chapters.len() {
for _ in 0..=items {
if let Some(file) = app.guided_review_workspace.position.file_id.as_ref() {
seen.insert(file.clone());
}
app.update(Msg::DispatchUiAction(UiAction::ReviewHunkNext));
}
app.update(Msg::DispatchUiAction(UiAction::ReviewChapterNext));
}
for id in non_text {
assert!(seen.contains(&id), "walking the guide reaches every non-text item");
}
}

View File

@@ -0,0 +1,129 @@
//! Verification — tests moved out of the module they cover.
use super::*;
use crate::fixture::{seeded_app, FixtureScenario};
use luxe_core::guided_review::{
DiffSide, FindingAnchor, FindingMessage, FindingMessageAuthor, FindingState,
ReviewFeedbackMode, SubmissionId,
};
use ratatui::{backend::TestBackend, Terminal};
/// `NeedsVerification` used to be verified on trust: there was no way to see what the agent
/// changed at the anchor without refreshing the whole review and hunting for it.
#[test]
fn the_fix_view_shows_the_anchor_before_and_after() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let review = app.guided_review.clone().expect("fixture review");
let file = &review.files[0];
let hunk = &file.hunks[0];
let anchored =
hunk.lines.iter().find(|line| line.new_line.is_some()).expect("an anchored line");
let session = app.review.session_mut().expect("review session");
let finding_id = session.findings[0].id.clone();
{
let finding = &mut session.findings[0];
finding.anchor = FindingAnchor::Line {
file_id: file.id.clone(),
hunk_id: hunk.id.clone(),
side: DiffSide::New,
line: anchored.new_line.expect("new-side line"),
context_hash: anchored.context_hash(),
};
finding.state = FindingState::NeedsVerification;
finding.thread.push(FindingMessage {
author: FindingMessageAuthor::Agent,
body: "Fixed by bounding the retry loop.".into(),
created_at_ms: 0,
});
}
let submission_id = SubmissionId::new();
session
.queue_submission(
submission_id,
ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&review.files,
0,
)
.expect("queue the submission");
app.guided_review_workspace.selected_finding_id = Some(finding_id);
app.guided_review_workspace.findings_visible = true;
app.guided_review_workspace.toggle_finding_fix();
let backend = TestBackend::new(160, 40);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render the fix view");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("What changed here"), "{text}");
assert!(text.contains("When you commented"), "the submitted evidence is shown: {text}");
assert!(text.contains("Now"), "the current state is shown: {text}");
// The agent's word is presented as a claim, next to the code that settles it.
assert!(text.contains("a claim, not proof"), "{text}");
assert!(text.contains("r verify and resolve"), "{text}");
}
/// Remediation usually *moves* code, and "refresh and look for it yourself" abandons the
/// reviewer at the moment the tool should help. A dead anchor reports where the line went.
#[test]
fn a_moved_anchor_reports_where_the_line_went() {
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture app");
let review = app.guided_review.clone().expect("fixture review");
let file = &review.files[0];
let moved_line = file.hunks[1]
.lines
.iter()
.find(|line| line.new_line.is_some())
.expect("a line in the second hunk");
let session = app.review.session_mut().expect("review session");
let finding_id = session.findings[0].id.clone();
{
// Anchor the comment at a hunk that no longer exists, but whose source text has
// resurfaced elsewhere in the review — the shape a moved fix leaves behind.
let finding = &mut session.findings[0];
finding.anchor = FindingAnchor::Line {
file_id: file.id.clone(),
hunk_id: luxe_core::guided_review::HunkId::from_content(
&file.id, "vanished", "vanished",
),
side: DiffSide::New,
line: 4_242,
context_hash: moved_line.context_hash(),
};
finding.state = FindingState::NeedsVerification;
}
let submission_id = SubmissionId::new();
session
.queue_submission(
submission_id,
ReviewFeedbackMode::RequestFixes,
std::slice::from_ref(&finding_id),
&review.files,
0,
)
.expect("queue the submission");
// The submitted snapshot keeps the text the reviewer commented on, which is the handle.
if let Some(snapshot) = app
.review
.session_mut()
.and_then(|session| session.submissions.last_mut().and_then(|s| s.findings.first_mut()))
{
snapshot.evidence.source = Some(moved_line.text.clone());
}
app.guided_review_workspace.selected_finding_id = Some(finding_id);
app.guided_review_workspace.findings_visible = true;
app.guided_review_workspace.toggle_finding_fix();
let backend = TestBackend::new(160, 40);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal.draw(|frame| render(frame, frame.area(), &app)).expect("render the fix view");
let text: String =
terminal.backend().buffer().content.iter().map(|cell| cell.symbol()).collect();
assert!(text.contains("that line now lives at"), "{text}");
assert!(text.contains("src/notification.rs"), "the new home is named: {text}");
assert!(!text.contains("refresh the review"), "no dead end: {text}");
}

View File

@@ -0,0 +1,207 @@
//! The answers preview — what goes back to your own pull request's threads, before it does.
use super::overlays::overlay_block;
use crate::app::App;
use crate::glyphs::Icon;
use crate::guided_review::diff::clip_terminal_cells_ellipsis;
use crate::widgets::fit_review_preview;
use luxe_core::guided_review::ReviewFinding;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
/// One thread's rows: its cursor, what answering does to it, the reply typed so far and any error.
///
/// Args: `(app, answers, (index, row, finding), row_width)`.
fn thread_row(
app: &App,
answers: &crate::guided_review::ThreadAnswers,
(index, row, finding): (usize, &crate::guided_review::AnswerRow, &ReviewFinding),
row_width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let mut lines = Vec::new();
let thread = finding.github_thread.as_ref();
let cursor = if index == answers.selected { "›" } else { " " };
let conversation = thread.is_some_and(|thread| thread.conversation);
let can_resolve = thread.is_some_and(|thread| thread.can_resolve);
let (mark, action) = match (row.resolve, can_resolve, conversation) {
(true, _, _) => (crate::glyphs::Mark::Yes.glyph(), "resolve"),
// Said in the conversation, where a reply is a new comment and nothing resolves
(false, _, true) => ("○", "conversation"),
(false, true, false) => ("○", "leave open"),
(false, false, false) => ("○", "cannot resolve"),
};
let state = match finding.state {
luxe_core::guided_review::FindingState::Resolved => "verified",
luxe_core::guided_review::FindingState::NeedsVerification => "to verify",
_ => "open",
};
// No `R2`: that is the agent's name for a thread, and the title already says who opened it
let head = format!("{cursor} {mark} {action:<15}");
let detail = format!("{state} · {}", finding.title);
lines.push(Line::from(vec![
Span::styled(head.clone(), styles.accent),
Span::styled(
clip_terminal_cells_ellipsis(&detail, row_width.saturating_sub(head.width())),
styles.text,
),
]));
let editing = index == answers.selected && answers.replying.is_some();
if !editing && !row.reply.is_empty() {
let reply = format!(" reply: {}", row.reply.replace('\n', " "));
lines.push(Line::from(Span::styled(
clip_terminal_cells_ellipsis(&reply, row_width),
styles.muted,
)));
}
if let Some(error) = row.error.as_deref() {
lines.push(Line::from(Span::styled(format!(" {error}"), styles.error)));
}
lines
}
/// The list above the reply field: what this posts, whether the fix is on GitHub, one row per
/// thread, and what went wrong or is still happening.
fn answer_lines(
app: &App,
answers: &crate::guided_review::ThreadAnswers,
row_width: usize,
) -> Vec<Line<'static>> {
let styles = &app.theme_styles;
let title = app
.guided_review
.as_ref()
.and_then(|review| review.context.pull_request.as_ref())
.map_or_else(
|| "Answer these threads on GitHub".to_owned(),
|pr| format!("Answer these threads on {}#{}", pr.repository, pr.number),
);
let mut lines = vec![
Line::from(Span::styled(title, styles.accent)),
Line::from(Span::styled(
"Posts your reply to each thread. Resolving closes the thread; leave it open for the \
reviewer to close.",
styles.muted,
)),
];
match answers.prepared {
None => lines.push(Line::from(Span::styled(
format!(
"{} Asking GitHub whether the fix is there…",
crate::statusline::spinner(app.guided_review_workspace.frame)
),
styles.muted,
))),
Some((pushed, uncommitted)) => {
// A thread answered "fixed" points the reviewer at the pull request's head, so a fix
// that never reached it is the one thing worth stopping for
let warning = match (pushed, uncommitted) {
(true, false) => None,
(true, true) => {
Some("Some changes here are not committed yet, so they are not on GitHub.")
}
(false, false) => Some("Your fix is not on GitHub yet: push this branch first."),
(false, true) => Some("Your fix is not on GitHub yet: commit and push it first."),
};
if let Some(warning) = warning {
lines.push(Line::from(Span::styled(warning, styles.warning)));
}
}
}
lines.push(Line::from(""));
let findings = app.review.session().map_or(&[][..], |session| &session.findings[..]);
for (index, row) in answers.rows.iter().enumerate() {
if let Some(finding) = findings.iter().find(|finding| finding.id == row.finding_id) {
lines.extend(thread_row(app, answers, (index, row, finding), row_width));
}
}
if let Some(error) = answers.error.as_deref() {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(error.to_owned(), styles.error)));
}
if answers.sending {
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
format!(
"{} Answering on GitHub…",
crate::statusline::spinner(app.guided_review_workspace.frame)
),
styles.muted,
)));
}
lines
}
pub(super) fn render_thread_answers(
frame: &mut Frame,
area: Rect,
app: &App,
answers: &crate::guided_review::ThreadAnswers,
) {
let styles = &app.theme_styles;
let width = area.width.saturating_sub(4).clamp(50, 96).min(area.width);
let row_width = usize::from(width.saturating_sub(4));
let lines = answer_lines(app, answers, row_width);
let findings = app.review.session().map_or(&[][..], |session| &session.findings[..]);
// The reply is written in a field of its own under the list, where the cursor can be
let replying = answers.replying.as_ref().map(|editor| {
let label = answers
.rows
.get(answers.selected)
.and_then(|row| findings.iter().find(|finding| finding.id == row.finding_id))
.and_then(|finding| finding.github_thread.as_ref())
.map_or_else(String::new, |thread| format!("Reply to {} · ", author(&thread.author)));
(editor, Line::from(Span::styled(format!("{label}type below"), styles.muted)))
});
let inner_width = width.saturating_sub(3).max(1);
let list_rows = crate::widgets::text_field::wrapped_rows(&lines, inner_width);
let field_rows = replying
.as_ref()
.map_or(0, |(editor, _)| crate::widgets::text_field::rows(editor, inner_width).clamp(3, 8));
let reply_rows = if replying.is_some() { field_rows + 2 } else { 0 };
let rows = list_rows + reply_rows + 2 + crate::widgets::FOOTER_ROWS;
let Some(popup) = fit_review_preview(frame, area, (width, rows, 10), app) else {
return;
};
let hint = if answers.sending {
" answering… "
} else if answers.replying.is_some() {
" ctrl+enter save · esc cancel "
} else {
" enter post · space resolve · c reply · ↑/↓ choose · esc cancel "
};
let block = overlay_block(app, Icon::GitHub.glyph(), "Answer on GitHub");
frame.render_widget(Clear, popup);
let inner = crate::widgets::render_footed(frame, block, popup, hint, None, &app.theme_styles);
let [list_area, reply_area] = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Min(1),
ratatui::layout::Constraint::Length(reply_rows),
])
.areas(inner);
frame.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), list_area);
if let Some((editor, label)) = replying {
let [_, label_area, field_area] = ratatui::layout::Layout::vertical([
ratatui::layout::Constraint::Length(1),
ratatui::layout::Constraint::Length(1),
ratatui::layout::Constraint::Min(1),
])
.areas(reply_area);
frame.render_widget(Paragraph::new(label), label_area);
app.guided_review_workspace.field_width.set(field_area.width);
crate::widgets::text_field::render(frame, field_area, editor, styles);
}
}
/// A thread's author as GitHub writes one, `@login`, or what GitHub shows for an account that is
/// gone.
fn author(login: &str) -> String {
if login.is_empty() {
"a deleted account".to_owned()
} else {
format!("@{login}")
}
}