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,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");
}