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:
36
crates/luxe-tui/src/app/commands/cancel.rs
Normal file
36
crates/luxe-tui/src/app/commands/cancel.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Cancel — asking the engine to stop, and showing it only once it was asked.
|
||||
|
||||
use super::super::{App, AppState};
|
||||
use luxe_core::engine::Action;
|
||||
|
||||
/// Interrupts the turn. The screen stops only once the engine has the request, or once there is
|
||||
/// no engine left to be running anything.
|
||||
pub(in crate::app) fn cancel(app: &mut App) -> bool {
|
||||
let working = app.turn_in_flight() || super::super::events::has_unfinished_tools(app);
|
||||
// a live engine that did not hear the cancel is still working, and the screen must say
|
||||
// so; a closed one is not working at all, so the screen can stop with it
|
||||
if !app.send_action(Action::Cancel, "cancel") && !app.engine_tx.is_closed() {
|
||||
return true;
|
||||
}
|
||||
// The turn is over when the engine says so; until then this is a request
|
||||
if working {
|
||||
app.interrupt_sent_at = Some(app.frame_now());
|
||||
}
|
||||
// Interrupting means stop, not "finish the animation first": show what arrived.
|
||||
app.reveal_catch_up();
|
||||
app.streaming = false;
|
||||
app.status.state = AppState::Idle;
|
||||
app.status.turn_started = None;
|
||||
app.status.active_tool = None;
|
||||
// Cancel means stop: the engine drops its buffered steering too, so nothing still held
|
||||
// can arrive. It comes back to the composer rather than the transcript — interrupting is
|
||||
// usually the first half of "let me put that differently".
|
||||
let restored = app.cancel_pending_submissions();
|
||||
if restored > 0 {
|
||||
app.status.flash_toast(match restored {
|
||||
1 => "Interrupted · 1 message back in the composer".to_string(),
|
||||
n => format!("Interrupted · {n} messages back in the composer"),
|
||||
});
|
||||
}
|
||||
true
|
||||
}
|
||||
225
crates/luxe-tui/src/app/commands/editor.rs
Normal file
225
crates/luxe-tui/src/app/commands/editor.rs
Normal file
@@ -0,0 +1,225 @@
|
||||
//! Open in editor — `/editor`, and the key that opens the file a diff is showing.
|
||||
//!
|
||||
//! Each asks the main loop to hand the terminal to the reader's editor
|
||||
//! ([`crate::launcher::open_in_editor`]), which takes it back when the editor exits. The engine
|
||||
//! keeps running underneath, so opening a file mid-turn costs the turn nothing.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::super::App;
|
||||
use crate::launcher::OpenInEditor;
|
||||
|
||||
/// `/editor [path[:line]]`: the project with no argument, or that file or folder.
|
||||
pub(in crate::app) fn editor_command(app: &mut App, args: Option<&str>) {
|
||||
let root = project_root(app);
|
||||
let home = luxe_core::user_dirs::home_dir();
|
||||
match target_for(&root, home.as_deref(), args) {
|
||||
Ok(target) => app.outbox.editor_open = Some(target),
|
||||
Err(message) => app.status.flash_toast(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the file the preview is showing, at the top line in view.
|
||||
pub(in crate::app) fn open_peeked_file(app: &mut App) {
|
||||
let Some(view) = app.changes.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let line = crate::view::changes::line_in_view(view);
|
||||
let path = Path::new(&view.path);
|
||||
let path = match path.is_absolute() {
|
||||
true => path.to_path_buf(),
|
||||
false => project_root(app).join(path),
|
||||
};
|
||||
open_existing(app, path, line);
|
||||
}
|
||||
|
||||
/// Opens the file the review's cursor is in, at the cursor's line.
|
||||
///
|
||||
/// The working tree's copy, which is what an editor can change. For a review of a commit or of a
|
||||
/// pull request that is not checked out, that may differ from the diff on screen, and a file the
|
||||
/// change deleted is not there at all, which is said rather than opened empty.
|
||||
pub(in crate::app) fn open_reviewed_file(app: &mut App) {
|
||||
let Some(review) = app.guided_review.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let Some((file, line)) = app.guided_review_workspace.selected_new_line(&review.files) else {
|
||||
return;
|
||||
};
|
||||
let Some(path) = file.new_path.clone() else {
|
||||
app.status.flash_toast("This change deleted the file, so there is nothing to open");
|
||||
return;
|
||||
};
|
||||
let path = project_root(app).join(path);
|
||||
open_existing(app, path, line);
|
||||
}
|
||||
|
||||
/// Opens a project-relative file or folder from the FILES tree.
|
||||
pub(in crate::app) fn open_project_path(app: &mut App, relative: &str) {
|
||||
let path = project_root(app).join(relative);
|
||||
open_existing(app, path, None);
|
||||
}
|
||||
|
||||
/// Opens a project-relative folder, or the folder holding a file, in a file manager.
|
||||
///
|
||||
/// A terminal one takes the screen the way the editor does; with none installed, the desktop's own
|
||||
/// opens beside the terminal. A file manager can move and delete what the tree shows, so the tree
|
||||
/// reads its folders again when the screen comes back.
|
||||
pub(in crate::app) fn open_in_file_manager(app: &mut App, relative: &str) {
|
||||
let root = project_root(app);
|
||||
let Some(folder) = folder_for(&root, relative) else {
|
||||
app.status.flash_toast(format!("{relative} is not in the working tree"));
|
||||
return;
|
||||
};
|
||||
match luxe_core::program::file_manager() {
|
||||
Some((program, args)) => {
|
||||
app.outbox.file_manager =
|
||||
Some(crate::launcher::OpenInFileManager { program, args, folder });
|
||||
}
|
||||
None => {
|
||||
let label = luxe_core::paths::display(&folder);
|
||||
app.open_externally(folder.as_os_str(), &label);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder a file manager opens on for a tree row: the folder itself, or the one holding a
|
||||
/// file. `None` when it is not on disk.
|
||||
fn folder_for(root: &Path, relative: &str) -> Option<PathBuf> {
|
||||
let path = root.join(relative);
|
||||
let folder = match path.is_dir() {
|
||||
true => path,
|
||||
false => path.parent()?.to_path_buf(),
|
||||
};
|
||||
folder.is_dir().then_some(folder)
|
||||
}
|
||||
|
||||
fn open_existing(app: &mut App, path: PathBuf, line: Option<u32>) {
|
||||
if !path.exists() {
|
||||
let shown =
|
||||
luxe_core::paths::display(path.strip_prefix(project_root(app)).unwrap_or(&path));
|
||||
app.status.flash_toast(format!("{shown} is not in the working tree"));
|
||||
return;
|
||||
}
|
||||
app.outbox.editor_open = Some(OpenInEditor { path, line });
|
||||
}
|
||||
|
||||
fn project_root(app: &App) -> PathBuf {
|
||||
app.project_root.clone().unwrap_or_else(|| std::env::current_dir().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// What `/editor`'s argument names, resolved against the project.
|
||||
///
|
||||
/// Relative paths are the project's, `~/` is home, and a trailing `:N` is a line when the path
|
||||
/// without it is a file. A path that does not exist yet is fine when its folder does — the editor
|
||||
/// makes it on save, which is how a new file starts — and an error otherwise, since a typo in a
|
||||
/// folder name opens nothing useful.
|
||||
///
|
||||
/// Args: `(project root, home, argument)`.
|
||||
fn target_for(
|
||||
root: &Path,
|
||||
home: Option<&Path>,
|
||||
args: Option<&str>,
|
||||
) -> Result<OpenInEditor, String> {
|
||||
let written = args.map(str::trim).filter(|args| !args.is_empty());
|
||||
let Some(written) = written else {
|
||||
return Ok(OpenInEditor { path: root.to_path_buf(), line: None });
|
||||
};
|
||||
let unquoted = written
|
||||
.strip_prefix('"')
|
||||
.and_then(|rest| rest.strip_suffix('"'))
|
||||
.or_else(|| written.strip_prefix('\'').and_then(|rest| rest.strip_suffix('\'')))
|
||||
.unwrap_or(written);
|
||||
let resolve = |text: &str| -> PathBuf {
|
||||
let expanded = match (text.strip_prefix("~/"), home) {
|
||||
(Some(rest), Some(home)) => home.join(rest),
|
||||
_ if text == "~" => home.map_or_else(|| PathBuf::from(text), Path::to_path_buf),
|
||||
_ => PathBuf::from(text),
|
||||
};
|
||||
match expanded.is_absolute() {
|
||||
true => expanded,
|
||||
false => root.join(expanded),
|
||||
}
|
||||
};
|
||||
let path = resolve(unquoted);
|
||||
if path.exists() {
|
||||
return Ok(OpenInEditor { path, line: None });
|
||||
}
|
||||
if let Some((file, line)) = unquoted.rsplit_once(':') {
|
||||
if let Ok(line) = line.parse::<u32>() {
|
||||
let file = resolve(file);
|
||||
if file.is_file() {
|
||||
return Ok(OpenInEditor { path: file, line: Some(line) });
|
||||
}
|
||||
}
|
||||
}
|
||||
match path.parent().is_some_and(Path::is_dir) {
|
||||
true => Ok(OpenInEditor { path, line: None }),
|
||||
false => Err(format!("No such folder for {unquoted}")),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn project() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir_all(dir.path().join("scripts")).unwrap();
|
||||
std::fs::write(dir.path().join("scripts/install-dev.sh"), "#!/bin/sh\n").unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A file manager opens on a folder: the row's own, or the one holding the file, and nothing
|
||||
/// for a row that left the disk.
|
||||
#[test]
|
||||
fn a_file_manager_opens_on_the_folder_a_row_is_in() {
|
||||
let dir = project();
|
||||
let root = dir.path();
|
||||
assert_eq!(folder_for(root, "scripts"), Some(root.join("scripts")));
|
||||
assert_eq!(folder_for(root, "scripts/install-dev.sh"), Some(root.join("scripts")));
|
||||
assert_eq!(folder_for(root, "README.md"), Some(root.to_path_buf()), "a root file");
|
||||
assert_eq!(folder_for(root, "gone/file.rs"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_editor_opens_the_project() {
|
||||
let dir = project();
|
||||
let target = target_for(dir.path(), None, None).unwrap();
|
||||
assert_eq!(target, OpenInEditor { path: dir.path().to_path_buf(), line: None });
|
||||
assert_eq!(target_for(dir.path(), None, Some(" ")).unwrap().path, dir.path());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_is_the_projects_and_may_name_a_line() {
|
||||
let dir = project();
|
||||
let script = dir.path().join("scripts/install-dev.sh");
|
||||
let open = |args: &str| target_for(dir.path(), None, Some(args));
|
||||
assert_eq!(open("scripts/install-dev.sh").unwrap().path, script);
|
||||
assert_eq!(open("\"scripts/install-dev.sh\"").unwrap().path, script, "quoted");
|
||||
assert_eq!(open("scripts").unwrap().path, dir.path().join("scripts"), "a folder");
|
||||
assert_eq!(
|
||||
open("scripts/install-dev.sh:12").unwrap(),
|
||||
OpenInEditor { path: script.clone(), line: Some(12) }
|
||||
);
|
||||
assert_eq!(open(&script.display().to_string()).unwrap().path, script, "absolute");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_is_tilde() {
|
||||
let dir = project();
|
||||
let home = dir.path().join("scripts");
|
||||
let target = target_for(Path::new("/elsewhere"), Some(&home), Some("~/install-dev.sh"));
|
||||
assert_eq!(target.unwrap().path, home.join("install-dev.sh"));
|
||||
}
|
||||
|
||||
/// A new file in a folder that exists is how a file starts; a folder that does not exist is a
|
||||
/// typo, and the editor would open nothing useful.
|
||||
#[test]
|
||||
fn a_new_file_needs_its_folder() {
|
||||
let dir = project();
|
||||
let new = target_for(dir.path(), None, Some("scripts/new.sh")).unwrap();
|
||||
assert_eq!(new.path, dir.path().join("scripts/new.sh"));
|
||||
let typo = target_for(dir.path(), None, Some("scirpts/new.sh"));
|
||||
assert_eq!(typo, Err("No such folder for scirpts/new.sh".to_string()));
|
||||
}
|
||||
}
|
||||
353
crates/luxe-tui/src/app/commands/github.rs
Normal file
353
crates/luxe-tui/src/app/commands/github.rs
Normal file
@@ -0,0 +1,353 @@
|
||||
//! GitHub commands — `/pr`'s card, and what a status row's key sets going.
|
||||
//!
|
||||
//! The card and the detail beside `/github` both answer a row's key with a [`CheckAction`]; this is
|
||||
//! where each one becomes the work it names, through the machinery that already does that work.
|
||||
|
||||
use super::super::App;
|
||||
use luxe_core::engine::Action;
|
||||
use luxe_core::engine::PullRequestWrite;
|
||||
use luxe_core::github::overview::{CheckAction, PullRequestOverview};
|
||||
use luxe_core::github::PullRequestStatus;
|
||||
use luxe_core::guided_review::ReviewTarget;
|
||||
|
||||
/// Opens `/pr`'s card on the branch's pull request and asks for its overview.
|
||||
pub(in crate::app) fn open_pull_request_card(app: &mut App, status: PullRequestStatus) {
|
||||
let number = status.number;
|
||||
app.overlays.pull_request_card =
|
||||
Some(crate::github_detail::PullRequestCard::reading(number, Some(status)));
|
||||
read_overview(app, None, number, true);
|
||||
}
|
||||
|
||||
/// Asks the engine for a pull request's or issue's overview; the answer lands as
|
||||
/// `GithubOverviewRead`.
|
||||
pub(in crate::app) fn read_overview(
|
||||
app: &mut App,
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
pull_request: bool,
|
||||
) {
|
||||
let asked = Action::ReadGithubOverview { repository, number, pull_request };
|
||||
app.send_action(asked, "read a pull request overview");
|
||||
}
|
||||
|
||||
/// Asks the engine for everything said about a pull request or issue; the answer lands as
|
||||
/// `GithubConversationRead`.
|
||||
pub(in crate::app) fn read_conversation(
|
||||
app: &mut App,
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
pull_request: bool,
|
||||
) {
|
||||
let asked = Action::ReadGithubConversation { repository, number, pull_request };
|
||||
app.send_action(asked, "read a pull request conversation");
|
||||
}
|
||||
|
||||
/// Sends a reply or comment the reader confirmed; the answer lands as `GithubCommentPosted`.
|
||||
pub(in crate::app) fn post_comment(app: &mut App, post: luxe_core::engine::GithubPost) {
|
||||
let thread = post.thread.clone();
|
||||
if !app.send_action(Action::PostGithubComment(post), "post a comment") {
|
||||
// Said where the reader is looking, and the card stays open to try again
|
||||
let reason = "The engine is busy — try posting again in a moment.".to_string();
|
||||
if let Some(detail) = composing_detail(app) {
|
||||
detail.posted(thread.as_deref(), Some(reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the session's agent to draft a reply; the answer lands as `GithubReplyDrafted`.
|
||||
///
|
||||
/// A thread on the branch's own pull request may have become a comment in Guided Review, and
|
||||
/// what the review made of it — whether the reader verified the fix, what the agent reported doing
|
||||
/// — is evidence only this side holds, so it travels with the request.
|
||||
pub(in crate::app) fn draft_reply(
|
||||
app: &mut App,
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
pull_request: bool,
|
||||
ask: crate::github_detail::DraftAsk,
|
||||
) {
|
||||
let finding = finding_for(app, &ask.target);
|
||||
let request = luxe_core::engine::DraftRequest {
|
||||
request_id: ask.request_id,
|
||||
repository,
|
||||
number,
|
||||
pull_request,
|
||||
target: ask.target,
|
||||
conversation: ask.conversation,
|
||||
finding,
|
||||
note: ask.note,
|
||||
current: ask.current,
|
||||
};
|
||||
app.send_action(Action::DraftGithubReply(request), "draft a reply");
|
||||
}
|
||||
|
||||
/// The review comment a thread became, from the open feedback session, and where it stands.
|
||||
fn finding_for(
|
||||
app: &App,
|
||||
target: &luxe_core::engine::DraftTarget,
|
||||
) -> Option<luxe_core::engine::FindingEvidence> {
|
||||
use luxe_core::guided_review::{FindingMessageAuthor, FindingState};
|
||||
let luxe_core::engine::DraftTarget::Thread(thread) = target else { return None };
|
||||
let session = app.review.session()?;
|
||||
let finding = session.findings.iter().find(|finding| {
|
||||
finding.github_thread.as_ref().is_some_and(|linked| linked.id == thread.id)
|
||||
})?;
|
||||
let remediation = finding
|
||||
.thread
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|message| message.author == FindingMessageAuthor::Agent)
|
||||
.map(|message| message.body.clone());
|
||||
Some(luxe_core::engine::FindingEvidence {
|
||||
verified: finding.state == FindingState::Resolved,
|
||||
remediation,
|
||||
})
|
||||
}
|
||||
|
||||
/// Hands the draft being read to the reader's editor; what comes back replaces it.
|
||||
pub(in crate::app) fn edit_draft_externally(app: &mut App, text: String) {
|
||||
app.outbox.text_edit =
|
||||
Some(crate::launcher::TextEdit { text, target: crate::launcher::EditTarget::GithubDraft });
|
||||
}
|
||||
|
||||
/// The detail whose draft card is open: `/pr`'s, or the `/github` row's under the cursor.
|
||||
pub(in crate::app) fn composing_detail(
|
||||
app: &mut App,
|
||||
) -> Option<&mut crate::github_detail::GithubDetail> {
|
||||
use crate::github_detail::CardState;
|
||||
if let Some(card) = app.overlays.pull_request_card.as_mut() {
|
||||
if let CardState::Ready(detail) = &mut card.state {
|
||||
return Some(detail.as_mut());
|
||||
}
|
||||
}
|
||||
let panel = app.overlays.github.as_mut()?;
|
||||
let url = panel.rows().get(panel.selected).map(|item| item.url.clone())?;
|
||||
panel.details.get_mut(&url)
|
||||
}
|
||||
|
||||
/// Reads pull request `number`'s overview again wherever it is shown, after a change to it landed.
|
||||
pub(in crate::app) fn reread_overview(app: &mut App, repository: Option<String>, number: u64) {
|
||||
let card = app.overlays.pull_request_card.as_ref().is_some_and(|card| card.number == number);
|
||||
if card && repository.is_none() {
|
||||
read_overview(app, None, number, true);
|
||||
return;
|
||||
}
|
||||
let Some(panel) = app.overlays.github.as_mut() else { return };
|
||||
let here = panel.repository.clone();
|
||||
let url = panel
|
||||
.sections
|
||||
.iter()
|
||||
.flatten()
|
||||
.flat_map(|section| §ion.items)
|
||||
.find(|item| {
|
||||
item.number == number
|
||||
&& match repository.as_deref() {
|
||||
Some(slug) => item.repository.eq_ignore_ascii_case(slug),
|
||||
None => here
|
||||
.as_deref()
|
||||
.is_none_or(|here| here.eq_ignore_ascii_case(&item.repository)),
|
||||
}
|
||||
})
|
||||
.map(|item| item.url.clone());
|
||||
if let Some(url) = url {
|
||||
panel.asked.insert(url);
|
||||
read_overview(app, repository, number, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the card's overview again when the branch's pull request moved since it last did.
|
||||
pub(in crate::app) fn refresh_pull_request_card(app: &mut App) {
|
||||
let Some(luxe_core::workspace::PullRequestPresence::Found(status)) =
|
||||
app.workspace.as_ref().map(|workspace| workspace.pull_request.clone())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(card) = app.overlays.pull_request_card.as_mut() else { return };
|
||||
if !card.stale(&status) {
|
||||
return;
|
||||
}
|
||||
card.seen = Some(status);
|
||||
let number = card.number;
|
||||
read_overview(app, None, number, true);
|
||||
}
|
||||
|
||||
/// Does what a status row on `pr` offers.
|
||||
///
|
||||
/// Only the actions [`crate::github_detail::GithubDetail::acts`] allows reach here, since a row
|
||||
/// shows no key for any other. Work done in this checkout leaves for where it is done — the
|
||||
/// composer, Guided Review — and a change asked of GitHub stays where it was asked, saying what
|
||||
/// became of it when GitHub answers.
|
||||
pub(in crate::app) fn act_on_pull_request(
|
||||
app: &mut App,
|
||||
repository: Option<String>,
|
||||
pr: &PullRequestOverview,
|
||||
action: CheckAction,
|
||||
) {
|
||||
let number = pr.number;
|
||||
match action {
|
||||
// The threads become findings in a review of the working tree against the base, so a fix
|
||||
// lands where it is verified; the link is what lets the session find its way back
|
||||
CheckAction::ResolveThreads => {
|
||||
close_surfaces(app);
|
||||
let link = Action::LinkPullRequest { number, url: pr.url.clone() };
|
||||
app.send_quietly(link, "link the pull request");
|
||||
super::start_guided_review(app, ReviewTarget::OwnPullRequest { number });
|
||||
}
|
||||
CheckAction::FixChecks => {
|
||||
close_surfaces(app);
|
||||
ask_agent(app, &fix_checks_request(pr));
|
||||
}
|
||||
CheckAction::ResolveConflicts => {
|
||||
close_surfaces(app);
|
||||
ask_agent(app, &conflicts_request(pr));
|
||||
}
|
||||
// In a stack, the branch moves with the branches above it, which is what `/stack` is for
|
||||
CheckAction::UpdateBranch if pr.stack.is_some() => {
|
||||
close_surfaces(app);
|
||||
if app.send_action(
|
||||
Action::PlanRestack { request_id: luxe_core::restack::RestackId::new() },
|
||||
"plan a restack",
|
||||
) {
|
||||
app.overlays.restack = Some(crate::restack_panel::RestackPanel::Planning);
|
||||
}
|
||||
}
|
||||
CheckAction::UpdateBranch => {
|
||||
let write = PullRequestWrite::UpdateBranch { head_oid: pr.head_oid.clone() };
|
||||
change(app, repository, number, write);
|
||||
app.status.flash_toast(format!("Asking GitHub to bring #{number} up to date…"));
|
||||
}
|
||||
CheckAction::MarkReady => {
|
||||
change(app, repository, number, PullRequestWrite::MarkReady);
|
||||
app.status.flash_toast(format!("Marking #{number} ready for review…"));
|
||||
}
|
||||
CheckAction::OpenBelow(below) => {
|
||||
app.overlays.github = None;
|
||||
app.overlays.pull_request_card =
|
||||
Some(crate::github_detail::PullRequestCard::other(below));
|
||||
read_overview(app, repository, below, true);
|
||||
}
|
||||
// The confirmation sends these, through `confirm_change`
|
||||
CheckAction::Merge | CheckAction::EnableAutoMerge => {}
|
||||
CheckAction::DisableAutoMerge => {
|
||||
let write = PullRequestWrite::DisableAutoMerge { node_id: pr.node_id.clone() };
|
||||
change(app, repository, number, write);
|
||||
app.status.flash_toast(format!("Turning auto-merge off for #{number}…"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes the change a confirmation was left with — a merge, or auto-merge turned on; the
|
||||
/// confirmation stays open saying so until GitHub answers.
|
||||
pub(in crate::app) fn confirm_change(
|
||||
app: &mut App,
|
||||
repository: Option<String>,
|
||||
number: u64,
|
||||
write: PullRequestWrite,
|
||||
) {
|
||||
change(app, repository, number, write);
|
||||
}
|
||||
|
||||
fn change(app: &mut App, repository: Option<String>, number: u64, write: PullRequestWrite) {
|
||||
app.send_action(
|
||||
Action::ChangePullRequest { repository, number, write },
|
||||
"change a pull request",
|
||||
);
|
||||
}
|
||||
|
||||
/// Puts `request` in the composer for the reader to read, add to and send: work in this checkout
|
||||
/// is the agent's, but what it is asked to do is still the reader's to say.
|
||||
fn ask_agent(app: &mut App, request: &str) {
|
||||
if !app.editor.current_input().trim().is_empty() {
|
||||
app.editor.insert_text("\n\n");
|
||||
}
|
||||
app.editor.insert_text(request);
|
||||
app.status.flash_toast("Written in the composer — enter sends it to the agent".to_string());
|
||||
}
|
||||
|
||||
fn close_surfaces(app: &mut App) {
|
||||
app.overlays.github = None;
|
||||
app.overlays.pull_request_card = None;
|
||||
}
|
||||
|
||||
/// What the agent is asked when checks fail: which ones, where to read why, and to check its fix.
|
||||
fn fix_checks_request(pr: &PullRequestOverview) -> String {
|
||||
let names: Vec<String> = pr.failing.iter().map(|check| format!("`{}`", check.name)).collect();
|
||||
let which = match names.as_slice() {
|
||||
[] => String::new(),
|
||||
names => format!(" ({})", names.join(", ")),
|
||||
};
|
||||
format!(
|
||||
"Fix the failing checks on pull request #{}{which}. Read what failed with the git tool's \
|
||||
`checks` action, fix it in this checkout, and run what covers it before telling me what \
|
||||
you changed.",
|
||||
pr.number
|
||||
)
|
||||
}
|
||||
|
||||
/// What the agent is asked when the branch conflicts with its base: merge it in, never rewrite.
|
||||
fn conflicts_request(pr: &PullRequestOverview) -> String {
|
||||
format!(
|
||||
"Pull request #{} conflicts with `{base}`. Bring `{base}` into this branch with a merge — no \
|
||||
rebase and no force-push — resolve the conflicts, run the tests, and tell me what you \
|
||||
resolved and why.",
|
||||
pr.number,
|
||||
base = pr.base_ref
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The agent is told which checks failed and where to read why; a conflict is merged, never
|
||||
/// rebased, since the branch is published.
|
||||
#[test]
|
||||
fn what_the_agent_is_asked_names_the_work() {
|
||||
let pr = crate::fixture::pull_request_overview();
|
||||
let fix = fix_checks_request(&pr);
|
||||
assert!(
|
||||
fix.starts_with("Fix the failing checks on pull request #142 (`test (ubuntu-latest)`)")
|
||||
);
|
||||
assert!(fix.contains("`checks` action"));
|
||||
let conflicts = conflicts_request(&pr);
|
||||
assert!(conflicts.contains("conflicts with `main`") && conflicts.contains("no rebase"));
|
||||
}
|
||||
|
||||
/// A thread on your own pull request that became a review comment carries what the review made
|
||||
/// of it; another thread carries nothing.
|
||||
#[test]
|
||||
fn a_thread_that_became_a_review_comment_carries_its_evidence() {
|
||||
use crate::fixture::{seeded_app, FixtureScenario};
|
||||
let app = seeded_app("nord", FixtureScenario::GuidedReviewOwnPullRequest).expect("fixture");
|
||||
let linked = app
|
||||
.review
|
||||
.session()
|
||||
.and_then(|session| session.findings.iter().find(|f| f.github_thread.is_some()))
|
||||
.expect("a finding from a thread")
|
||||
.clone();
|
||||
let thread = |id: &str| {
|
||||
luxe_core::engine::DraftTarget::Thread(luxe_core::github::ReviewThread {
|
||||
id: id.into(),
|
||||
path: String::new(),
|
||||
line: None,
|
||||
start_line: None,
|
||||
side: luxe_core::github::ThreadSide::Right,
|
||||
outdated: false,
|
||||
resolved: false,
|
||||
file_level: false,
|
||||
comments: Vec::new(),
|
||||
total_comments: 0,
|
||||
anchor_text: None,
|
||||
can_reply: true,
|
||||
can_resolve: true,
|
||||
})
|
||||
};
|
||||
let id = linked.github_thread.as_ref().map(|t| t.id.clone()).unwrap_or_default();
|
||||
let evidence = finding_for(&app, &thread(&id)).expect("evidence");
|
||||
assert_eq!(
|
||||
evidence.verified,
|
||||
linked.state == luxe_core::guided_review::FindingState::Resolved
|
||||
);
|
||||
assert!(finding_for(&app, &thread("somewhere-else")).is_none());
|
||||
}
|
||||
}
|
||||
30
crates/luxe-tui/src/app/commands/menu.rs
Normal file
30
crates/luxe-tui/src/app/commands/menu.rs
Normal file
@@ -0,0 +1,30 @@
|
||||
//! Command menu — which commands can run on the screen the user is looking at.
|
||||
|
||||
use crate::app::App;
|
||||
|
||||
/// What the app can say about itself, for deciding which commands a menu lists.
|
||||
pub(in crate::app) fn command_context(app: &App) -> crate::commands::CommandContext {
|
||||
use crate::commands::{CommandContext, Surface};
|
||||
let review = app.current_view == crate::app::ViewMode::GuidedReview;
|
||||
CommandContext {
|
||||
surface: if review { Surface::Review } else { Surface::Chat },
|
||||
pull_request_review: review && crate::app::messages::github_post::is_pull_request(app),
|
||||
changes_pane: app.changes.is_some(),
|
||||
has_turn: app.has_user_message(),
|
||||
has_image: app.newest_visible_image().is_some(),
|
||||
messages_waiting: !app.pending_submissions.is_empty(),
|
||||
// The launch knows the branch before the first snapshot lands, and the snapshot keeps up
|
||||
// with a checkout made since
|
||||
in_repository: app.status.git_branch.is_some()
|
||||
|| app.workspace.as_ref().is_some_and(|state| state.project.git_branch.is_some()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands that can run here, the recently used first, with the keys bound to them now.
|
||||
pub(in crate::app) fn command_menu(app: &App) -> crate::commands::Menu {
|
||||
crate::commands::CommandRegistry::all().arrange(
|
||||
&command_context(app),
|
||||
&app.keymap,
|
||||
app.recent_commands.ids(),
|
||||
)
|
||||
}
|
||||
272
crates/luxe-tui/src/app/commands/review.rs
Normal file
272
crates/luxe-tui/src/app/commands/review.rs
Normal file
@@ -0,0 +1,272 @@
|
||||
//! Review commands — opening, refreshing and steering the guided review from the command layer.
|
||||
|
||||
use super::*;
|
||||
|
||||
const REVIEW_TARGET_ARGUMENT_LIMIT: usize = 256;
|
||||
pub(super) const REVIEW_TARGET_USAGE: &str =
|
||||
"Usage: /diff [refresh|turn|base <ref>|commit <oid>|pr <number or URL>]";
|
||||
pub(super) const LAST_TURN_UNAVAILABLE: &str =
|
||||
"No complete baseline is available for the latest turn.";
|
||||
|
||||
pub(super) fn dispatch_review_navigation_action(app: &mut App, action: UiAction) -> bool {
|
||||
if app.current_view != crate::app::ViewMode::GuidedReview {
|
||||
return false;
|
||||
}
|
||||
|
||||
let message = match action {
|
||||
UiAction::ReviewChapterNext => crate::app::Msg::GuidedReviewChapterNext,
|
||||
UiAction::ReviewChapterPrev => crate::app::Msg::GuidedReviewChapterPrevious,
|
||||
UiAction::ReviewFileNext => crate::app::Msg::GuidedReviewFileNext,
|
||||
UiAction::ReviewFilePrev => crate::app::Msg::GuidedReviewFilePrevious,
|
||||
UiAction::ReviewHunkNext => crate::app::Msg::GuidedReviewHunkNext,
|
||||
UiAction::ReviewHunkPrev => crate::app::Msg::GuidedReviewHunkPrevious,
|
||||
UiAction::ReviewOpenSelection => crate::app::Msg::GuidedReviewOpenSelection,
|
||||
UiAction::ReviewLineNext => crate::app::Msg::GuidedReviewLineNext,
|
||||
UiAction::ReviewLinePrev => crate::app::Msg::GuidedReviewLinePrevious,
|
||||
UiAction::ReviewPageNext => crate::app::Msg::GuidedReviewPageNext,
|
||||
UiAction::ReviewPagePrev => crate::app::Msg::GuidedReviewPagePrevious,
|
||||
UiAction::ReviewScrollLeft => crate::app::Msg::GuidedReviewColumnPrevious,
|
||||
UiAction::ReviewScrollRight => crate::app::Msg::GuidedReviewColumnNext,
|
||||
UiAction::ReviewLineStart => crate::app::Msg::GuidedReviewLineStart,
|
||||
UiAction::ReviewToggleGuide => crate::app::Msg::GuidedReviewToggleGuide,
|
||||
UiAction::ReviewAddFinding => crate::app::Msg::GuidedReviewBeginFinding,
|
||||
UiAction::ReviewAskQuestion => crate::app::Msg::GuidedReviewBeginQuestion,
|
||||
UiAction::ReviewOpenInBrowser => crate::app::Msg::GuidedReviewOpenInBrowser,
|
||||
UiAction::ReviewSend => crate::app::Msg::GuidedReviewOpenSendPreview,
|
||||
UiAction::ReviewEditFinding => crate::app::Msg::GuidedReviewEditSelectedFinding,
|
||||
UiAction::ReviewDeleteFinding => crate::app::Msg::GuidedReviewDeleteSelectedFindingDraft,
|
||||
UiAction::ReviewReanchorFinding => crate::app::Msg::GuidedReviewReanchorSelectedFinding,
|
||||
UiAction::ReviewFindings => crate::app::Msg::GuidedReviewToggleFindings,
|
||||
UiAction::ReviewResolveFinding => {
|
||||
crate::app::Msg::GuidedReviewToggleSelectedFindingResolved
|
||||
}
|
||||
UiAction::ReviewToggleNoise => crate::app::Msg::GuidedReviewToggleNoise,
|
||||
UiAction::ReviewToggleSplit => crate::app::Msg::GuidedReviewToggleSplit,
|
||||
UiAction::ReviewToggleWordWrap => crate::app::Msg::GuidedReviewToggleWordWrap,
|
||||
UiAction::ReviewSource => crate::app::Msg::GuidedReviewToggleSourcePicker,
|
||||
UiAction::ReviewHelp => crate::app::Msg::GuidedReviewToggleHelp,
|
||||
_ => return false,
|
||||
};
|
||||
app.update(message);
|
||||
true
|
||||
}
|
||||
|
||||
/// Opens the Changes pane on a sensible file, or puts it away.
|
||||
///
|
||||
/// "Sensible" is the first row the dock draws, which is the file with the most change in the
|
||||
/// directory with the most change — the same thing the eye lands on in the rail, so the keyboard
|
||||
/// and the mouse open the same file. A project with nothing changed says so and opens nothing:
|
||||
/// an empty pane over the transcript would be a surface with no content and no way to guess why.
|
||||
pub(in crate::app) fn toggle_changes(app: &mut App) {
|
||||
if app.changes.is_some() {
|
||||
app.update(crate::app::Msg::CloseChanges);
|
||||
return;
|
||||
}
|
||||
match crate::app::messages::changes::changed_files(app).first() {
|
||||
Some(file) => app.update(crate::app::Msg::OpenChanges(file.path.clone())),
|
||||
None => app.status.flash_toast("Nothing has changed in this project yet".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the review key means right now.
|
||||
///
|
||||
/// The working tree, until it is empty and this session put something into a commit. A commit
|
||||
/// moves `HEAD` and takes the diff against it to zero, so the key would otherwise open a review of
|
||||
/// nothing at the exact moment there is most to read — while the turn's own retained baseline,
|
||||
/// which is content on disk rather than a Git range, still holds the whole change.
|
||||
fn default_review_target(app: &App) -> ReviewTarget {
|
||||
let clean = app.workspace.as_ref().is_some_and(|state| state.changes.total_files == 0);
|
||||
match app.review.last_turn.as_ref() {
|
||||
Some((session_id, turn_id)) if clean && app.worktree_emptied => {
|
||||
ReviewTarget::LastTurn { session_id: session_id.clone(), turn_id: turn_id.clone() }
|
||||
}
|
||||
_ => ReviewTarget::WorkingTree,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the review key means: show me the review, creating one first if there is not one yet.
|
||||
///
|
||||
/// Distinct from [`start_guided_review`], which always captures — that is what the source picker
|
||||
/// and `/diff <target>` want, because they are naming a *different* thing to review. This is the
|
||||
/// bare verb, and its answer is usually the review already pinned.
|
||||
pub(in crate::app) fn open_or_start_guided_review(app: &mut App) {
|
||||
// Pinned, complete, and labeled if the tree has moved under it. Someone coming back to the
|
||||
// review they just left should not wait for a re-capture to get there.
|
||||
if app.guided_review.is_some() && app.review.queued.is_none() {
|
||||
app.current_view = crate::app::ViewMode::GuidedReview;
|
||||
app.dock.scroll = 0;
|
||||
return;
|
||||
}
|
||||
start_guided_review(app, default_review_target(app));
|
||||
}
|
||||
|
||||
/// Ends the session to remove its worktree when nothing is uncommitted, or says what is.
|
||||
pub(in crate::app) fn worktree_removal_checked(app: &mut App, uncommitted: Vec<String>) {
|
||||
let Some(root) = app.worktree_removal_check.take() else {
|
||||
return;
|
||||
};
|
||||
if uncommitted.is_empty() {
|
||||
app.outbox.worktree_removal = Some(root);
|
||||
return;
|
||||
}
|
||||
let shown: Vec<&str> = uncommitted.iter().take(5).map(String::as_str).collect();
|
||||
let more = uncommitted.len().saturating_sub(shown.len());
|
||||
let tail = if more > 0 { format!(" and {more} more") } else { String::new() };
|
||||
app.push_convo(ConvoBlock::System(format!(
|
||||
"The worktree has work that is not committed: {}{tail}. Commit it, or discard it, and \
|
||||
`/worktree remove` again.",
|
||||
shown.join(", ")
|
||||
)));
|
||||
}
|
||||
|
||||
/// Opens a review, or parks the request until the turn that is running finishes.
|
||||
///
|
||||
/// The engine will not capture mid-turn — `turn.rs` re-queues anything it cannot act on — so
|
||||
/// switching to the review surface here left the reader on a full-screen "Capturing the working
|
||||
/// tree" that had not started, blind to the agent still producing the very change they wanted to
|
||||
/// read. A review is a pinned immutable revision, and there is no honest one to pin while the
|
||||
/// change is still being written.
|
||||
pub(in crate::app) fn start_guided_review(app: &mut App, target: ReviewTarget) {
|
||||
use crate::app::types::{QueuedReview, QueuedReviewState};
|
||||
// Already captured while the reader stayed in the conversation: this press is them taking the
|
||||
// tray row up on its offer.
|
||||
if app.review.queued.as_ref().is_some_and(|queued| queued.state == QueuedReviewState::Ready) {
|
||||
app.review.queued = None;
|
||||
app.current_view = crate::app::ViewMode::GuidedReview;
|
||||
app.dock.scroll = 0;
|
||||
return;
|
||||
}
|
||||
if app.turn_in_flight() {
|
||||
app.review.queued = Some(QueuedReview { target, state: QueuedReviewState::Waiting });
|
||||
return;
|
||||
}
|
||||
// Idle, so the capture can start at once — but the surface still does not open until there is
|
||||
// a whole review to open. Arriving on a half-built one and watching the prose rewrite itself
|
||||
// under you is the same bad experience whether the wait was five seconds or a turn long.
|
||||
app.review.queued =
|
||||
Some(QueuedReview { target: target.clone(), state: QueuedReviewState::Capturing });
|
||||
app.status.animating = true;
|
||||
app.guided_review_workspace.begin_loading(target.clone());
|
||||
dispatch_guided_review(app, target);
|
||||
}
|
||||
|
||||
/// Starts the capture the tray is waiting on, without taking the screen.
|
||||
///
|
||||
/// The reader has been in the conversation since they asked; pulling them into a full-screen review
|
||||
/// the moment a background job finishes would take the display away from whatever they moved on to.
|
||||
/// The tray says when it is ready and `Ctrl+G` opens it.
|
||||
pub(in crate::app) fn flush_queued_review(app: &mut App) {
|
||||
use crate::app::QueuedReviewState;
|
||||
let Some(queued) = app.review.queued.as_mut() else { return };
|
||||
if queued.state != QueuedReviewState::Waiting {
|
||||
return;
|
||||
}
|
||||
queued.state = QueuedReviewState::Capturing;
|
||||
app.status.animating = true;
|
||||
let target = queued.target.clone();
|
||||
app.guided_review_workspace.begin_loading(target.clone());
|
||||
dispatch_guided_review(app, target);
|
||||
}
|
||||
|
||||
/// Starts a typed review source load without deriving source state in the UI.
|
||||
fn dispatch_guided_review(app: &mut App, target: ReviewTarget) {
|
||||
let request_id = ReviewLoadRequestId::new();
|
||||
app.active_guided_review_request = Some(request_id.clone());
|
||||
if !app.send_action(
|
||||
Action::LoadGuidedReview { request_id, target: target.clone() },
|
||||
"load a review",
|
||||
) {
|
||||
app.active_guided_review_request = None;
|
||||
app.guided_review_workspace.mark_failed(
|
||||
target,
|
||||
GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Capture,
|
||||
message: "Could not start the review.".into(),
|
||||
},
|
||||
);
|
||||
app.review.queued = None;
|
||||
app.push_convo(ConvoBlock::System("Could not start the review.".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
/// Refreshes the currently pinned immutable review with an optimistic revision guard.
|
||||
pub(in crate::app) fn refresh_guided_review(app: &mut App) {
|
||||
let Some(review) = app.guided_review.as_ref() else {
|
||||
app.push_convo(ConvoBlock::System("No review is available to refresh.".to_string()));
|
||||
return;
|
||||
};
|
||||
let (review_id, expected_revision, target) =
|
||||
(review.id.clone(), review.revision_id.clone(), review.target.clone());
|
||||
crate::app::navigation::enter_guided_review(app, target.clone());
|
||||
let request_id = ReviewLoadRequestId::new();
|
||||
app.active_guided_review_request = Some(request_id.clone());
|
||||
if !app.send_action(
|
||||
Action::RefreshGuidedReview { request_id, review_id, expected_revision },
|
||||
"refresh the review",
|
||||
) {
|
||||
app.active_guided_review_request = None;
|
||||
app.guided_review_workspace.mark_failed(
|
||||
target,
|
||||
GuidedReviewFailure {
|
||||
kind: GuidedReviewFailureKind::Capture,
|
||||
message: "Could not refresh the review.".into(),
|
||||
},
|
||||
);
|
||||
app.push_convo(ConvoBlock::System("Could not refresh the review.".to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::app) fn parse_review_target(
|
||||
arguments: Option<&str>,
|
||||
last_turn_target: Option<&(String, String)>,
|
||||
) -> Result<ReviewTarget, &'static str> {
|
||||
let Some(arguments) = arguments.map(str::trim).filter(|value| !value.is_empty()) else {
|
||||
return Ok(ReviewTarget::WorkingTree);
|
||||
};
|
||||
if arguments.len() > REVIEW_TARGET_ARGUMENT_LIMIT || arguments.chars().any(char::is_control) {
|
||||
return Err(REVIEW_TARGET_USAGE);
|
||||
}
|
||||
if arguments == "turn" {
|
||||
return last_turn_target
|
||||
.map(|(session_id, turn_id)| ReviewTarget::LastTurn {
|
||||
session_id: session_id.clone(),
|
||||
turn_id: turn_id.clone(),
|
||||
})
|
||||
.ok_or(LAST_TURN_UNAVAILABLE);
|
||||
}
|
||||
if arguments.split_whitespace().count() != 2 {
|
||||
return Err(REVIEW_TARGET_USAGE);
|
||||
}
|
||||
|
||||
let mut parts = arguments.split_whitespace();
|
||||
let kind = parts.next().ok_or(REVIEW_TARGET_USAGE)?;
|
||||
let value = parts.next().ok_or(REVIEW_TARGET_USAGE)?;
|
||||
match kind {
|
||||
"base" => Ok(ReviewTarget::Base { reference: value.to_string() }),
|
||||
"commit" => Ok(ReviewTarget::Commit { oid: value.to_string() }),
|
||||
"pr" => parse_pull_request(value).ok_or(REVIEW_TARGET_USAGE),
|
||||
_ => Err(REVIEW_TARGET_USAGE),
|
||||
}
|
||||
}
|
||||
|
||||
/// A pull request as a reader would name one: `123`, `#123`, or its web address.
|
||||
///
|
||||
/// A URL keeps its `owner/name`, so the engine can tell the checkout's own pull request from an
|
||||
/// upstream's; any host is accepted, since GitHub Enterprise lives on its own. Trailing pieces of a
|
||||
/// URL copied from a browser (`/files`, a query, a fragment) are ignored.
|
||||
fn parse_pull_request(value: &str) -> Option<ReviewTarget> {
|
||||
let number = |text: &str| text.parse::<u64>().ok().filter(|number| *number > 0);
|
||||
if let Some(number) = number(value.strip_prefix('#').unwrap_or(value)) {
|
||||
return Some(ReviewTarget::PullRequest { number, repository: None });
|
||||
}
|
||||
let address = value.split_once("://").map_or(value, |(_, rest)| rest);
|
||||
let address = address.split(['?', '#']).next()?;
|
||||
let segments: Vec<&str> = address.split('/').filter(|segment| !segment.is_empty()).collect();
|
||||
match segments.as_slice() {
|
||||
[_host, owner, name, "pull", pr, ..] => Some(ReviewTarget::PullRequest {
|
||||
number: number(pr)?,
|
||||
repository: Some(format!("{owner}/{name}")),
|
||||
}),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
335
crates/luxe-tui/src/app/commands/slash.rs
Normal file
335
crates/luxe-tui/src/app/commands/slash.rs
Normal file
@@ -0,0 +1,335 @@
|
||||
//! Slash commands — the commands run by id, and what each one does.
|
||||
|
||||
use super::super::{App, ConvoBlock};
|
||||
use super::{
|
||||
cycle_mode, dispatch_action, editor, github_searches, list_github, open_pull_request_card,
|
||||
parse_review_target, refresh_guided_review, start_guided_review, toggle_changes, toggle_keys,
|
||||
};
|
||||
use crate::commands::id;
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use luxe_core::config::{Config, DockPosition};
|
||||
use luxe_core::engine::Action;
|
||||
use luxe_core::keymap::{load_keybindings, UiAction};
|
||||
|
||||
/// Runs a command handled by id, with whatever arguments were typed after its trigger, and answers
|
||||
/// whether its id is one this knows.
|
||||
pub(super) fn run_slash(app: &mut App, cmd: &crate::commands::Command) -> bool {
|
||||
match cmd.id.as_ref() {
|
||||
id::NEW => {
|
||||
if app.leave_for_session(crate::app::NextSession::New) {
|
||||
tracing::info!("/new — starting a new session");
|
||||
}
|
||||
}
|
||||
id::SESSIONS => app.open_sessions(),
|
||||
id::MODEL => {
|
||||
// Opens the searchable model picker (also reachable from the palette). Selecting a
|
||||
// model sends `Action::SetModel`, switching the active model in-session.
|
||||
app.open_model_picker();
|
||||
}
|
||||
id::THINKING => app.open_thinking_picker(),
|
||||
id::THEME => app.open_theme_picker(),
|
||||
id::LOGIN => {
|
||||
// `/login openai` skips the provider list; a bare `/login` shows it.
|
||||
app.open_auth_wizard(cmd.args.as_deref().map(str::trim).filter(|a| !a.is_empty()));
|
||||
}
|
||||
id::CONFIG => {
|
||||
app.open_configuration();
|
||||
}
|
||||
id::SETTINGS => {
|
||||
app.open_settings();
|
||||
}
|
||||
id::LOGOUT => {
|
||||
app.logout_provider(cmd.args.as_deref().map(str::trim).filter(|a| !a.is_empty()));
|
||||
}
|
||||
id::AUTH => {
|
||||
app.report_auth_status();
|
||||
}
|
||||
id::HELP => toggle_keys(app),
|
||||
// What the workspace last heard, at once, and a fresh look behind it: the snapshot that
|
||||
// lands afterwards brings the statusline and the dock up to date
|
||||
id::GITHUB => {
|
||||
if list_github(app) {
|
||||
let configured = app.config.github.sections();
|
||||
let searches = github_searches(app);
|
||||
let panel = crate::github_panel::GithubPanel::with_searches(&configured, searches);
|
||||
app.overlays.github = Some(panel);
|
||||
}
|
||||
}
|
||||
id::STACK => {
|
||||
if app.send_action(
|
||||
Action::PlanRestack { request_id: luxe_core::restack::RestackId::new() },
|
||||
"plan a restack",
|
||||
) {
|
||||
app.overlays.restack = Some(crate::restack_panel::RestackPanel::Planning);
|
||||
}
|
||||
}
|
||||
id::PR => {
|
||||
let presence = app
|
||||
.workspace
|
||||
.as_ref()
|
||||
.map(|workspace| workspace.pull_request.clone())
|
||||
.unwrap_or_default();
|
||||
app.send_quietly(Action::RefreshWorkspace, "refresh the workspace");
|
||||
// A pull request opens in its card; without one, the sentence saying why there is none
|
||||
match &presence {
|
||||
luxe_core::workspace::PullRequestPresence::Found(pr) => {
|
||||
open_pull_request_card(app, pr.clone());
|
||||
}
|
||||
_ => app.push_convo(ConvoBlock::System(crate::pull_request::report(&presence))),
|
||||
}
|
||||
}
|
||||
id::WORKTREE => worktree_command(app, cmd.args.as_deref()),
|
||||
id::EDITOR => editor::editor_command(app, cmd.args.as_deref()),
|
||||
id::COST => {
|
||||
let report = crate::cost_report::render_with_plan(
|
||||
&app.status.session,
|
||||
app.status.plan_usage.as_ref(),
|
||||
);
|
||||
app.push_convo(ConvoBlock::System(report));
|
||||
}
|
||||
// The engine owns the measurement — it is the only place the assembled prompt, the tool
|
||||
// block and the active transcript all exist at once — so the report arrives as an event.
|
||||
id::CONTEXT => {
|
||||
app.send_action(Action::RequestContextComposition, "show the context");
|
||||
}
|
||||
// Same reasoning as `/context`: only the engine can see the transcript, and the summary
|
||||
// costs a provider call, so the answer comes back as an event rather than inline.
|
||||
id::COMPACT => {
|
||||
let focus = cmd.args.as_deref().map(str::trim).filter(|args| !args.is_empty());
|
||||
let action = Action::CompactNow { focus: focus.map(str::to_string) };
|
||||
app.send_action(action, "compact");
|
||||
}
|
||||
id::LSP => {
|
||||
let text = match app.workspace.as_ref() {
|
||||
Some(workspace) => crate::tooling::render_lsp(&workspace.tooling),
|
||||
None => {
|
||||
"Language-server status isn't ready yet — try again in a moment.".to_string()
|
||||
}
|
||||
};
|
||||
app.push_convo(ConvoBlock::System(text));
|
||||
}
|
||||
id::DEBUG => {
|
||||
let text = match app.workspace.as_ref() {
|
||||
Some(workspace) => crate::tooling::render_debug(&workspace.tooling),
|
||||
None => "Debug-adapter status isn't ready yet — try again in a moment.".to_string(),
|
||||
};
|
||||
app.push_convo(ConvoBlock::System(text));
|
||||
}
|
||||
id::IMAGES => {
|
||||
let report = crate::tooling::render_images(
|
||||
app.images.tier(),
|
||||
crate::graphics::ImageTier::resolve_detail(app.config.images.unwrap_or_default())
|
||||
.reason,
|
||||
app.config.conversation.image_max_rows(),
|
||||
);
|
||||
app.push_convo(ConvoBlock::System(report));
|
||||
}
|
||||
id::MCP => {
|
||||
let text = match app.workspace.as_ref() {
|
||||
Some(workspace) => crate::tooling::render_mcp(&workspace.tooling),
|
||||
None => "MCP status isn't ready yet — try again in a moment.".to_string(),
|
||||
};
|
||||
app.push_convo(ConvoBlock::System(text));
|
||||
}
|
||||
id::TOOLS => {
|
||||
let text = match app.workspace.as_ref() {
|
||||
Some(workspace) => crate::tooling::render_tools(&workspace.tooling),
|
||||
None => "Tool status isn't ready yet — try again in a moment.".to_string(),
|
||||
};
|
||||
app.push_convo(ConvoBlock::System(text));
|
||||
}
|
||||
// `/peek [path]` — the cheap look. Bare, it opens whatever the dock leads with; with a
|
||||
// path, that file. A path nothing has changed still opens, because "this file is clean" is
|
||||
// an answer and refusing to show it is not.
|
||||
id::CHANGES => match cmd.args.as_deref().map(str::trim).filter(|path| !path.is_empty()) {
|
||||
Some(path) => app.update(crate::app::Msg::OpenChanges(path.to_string())),
|
||||
None => toggle_changes(app),
|
||||
},
|
||||
id::DIFF => {
|
||||
let arguments = cmd.args.as_deref().map(str::trim).filter(|args| !args.is_empty());
|
||||
if arguments == Some("refresh") {
|
||||
refresh_guided_review(app);
|
||||
} else if arguments.is_none() {
|
||||
// The same verb as its key: the review already pinned, or one taken now
|
||||
dispatch_action(app, UiAction::ReviewOpen);
|
||||
} else {
|
||||
let target =
|
||||
match parse_review_target(cmd.args.as_deref(), app.review.last_turn.as_ref()) {
|
||||
Ok(target) => target,
|
||||
Err(message) => {
|
||||
app.push_convo(ConvoBlock::System(message.to_string()));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
start_guided_review(app, target);
|
||||
}
|
||||
}
|
||||
id::DOCK => {
|
||||
let action = match cmd.args.as_deref() {
|
||||
None => UiAction::ToggleDock,
|
||||
Some("show") => UiAction::ShowDock,
|
||||
Some("hide") => UiAction::HideDock,
|
||||
Some("auto") => UiAction::ResetDockAuto,
|
||||
Some("left") => {
|
||||
app.dock.position = DockPosition::Left;
|
||||
return true;
|
||||
}
|
||||
Some("right") => {
|
||||
app.dock.position = DockPosition::Right;
|
||||
return true;
|
||||
}
|
||||
Some(_) => {
|
||||
app.push_convo(ConvoBlock::System(
|
||||
"Usage: /dock [show|hide|auto|left|right]".to_string(),
|
||||
));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
dispatch_action(app, action);
|
||||
}
|
||||
id::STATUSLINE => {
|
||||
let action = match cmd.args.as_deref() {
|
||||
None | Some("toggle") => UiAction::ToggleStatusline,
|
||||
Some("show") => UiAction::ShowStatusline,
|
||||
Some("hide") => UiAction::HideStatusline,
|
||||
Some("auto") => UiAction::ResetStatuslineAuto,
|
||||
Some(_) => {
|
||||
app.push_convo(ConvoBlock::System(
|
||||
"Usage: /statusline [show|hide|auto|toggle]".to_string(),
|
||||
));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
dispatch_action(app, action);
|
||||
}
|
||||
id::MOUSE => {
|
||||
// Set an explicit state, or toggle when bare; ToggleMouse pushes the status line.
|
||||
let desired = match cmd.args.as_deref() {
|
||||
None | Some("toggle") => !app.mouse_enabled,
|
||||
Some("on") => true,
|
||||
Some("off") => false,
|
||||
Some(_) => {
|
||||
app.push_convo(ConvoBlock::System("Usage: /mouse [on|off|toggle]".to_string()));
|
||||
return true;
|
||||
}
|
||||
};
|
||||
if desired != app.mouse_enabled {
|
||||
dispatch_action(app, UiAction::ToggleMouse);
|
||||
}
|
||||
}
|
||||
id::MODE => match cmd.args.as_deref().map(str::trim).filter(|arg| !arg.is_empty()) {
|
||||
// The engine knows the modes and answers a name it does not with a notice
|
||||
Some(name) => {
|
||||
app.send_action(Action::SetMode(name.to_ascii_lowercase()), "change the mode");
|
||||
}
|
||||
None => cycle_mode(app),
|
||||
},
|
||||
id::REVIEW => {
|
||||
let focus = cmd.args.as_deref().map(str::trim).filter(|arg| !arg.is_empty());
|
||||
let action = Action::RequestReview { focus: focus.map(str::to_string) };
|
||||
app.send_action(action, "request a review");
|
||||
}
|
||||
id::PERMISSIONS => permissions_command(app, cmd.args.as_deref()),
|
||||
_ => return false,
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Turns auto-approve on, off, or over (`/permissions [on|off|toggle]`).
|
||||
fn permissions_command(app: &mut App, arguments: Option<&str>) {
|
||||
let desired = match arguments.map(str::trim) {
|
||||
None | Some("") | Some("toggle") => !app.permission_auto_approve,
|
||||
Some("on") => true,
|
||||
Some("off") => false,
|
||||
Some(_) => {
|
||||
app.push_convo(ConvoBlock::System(
|
||||
"Usage: /permissions [on|off|toggle] — on auto-approves tool asks; off prompts"
|
||||
.to_string(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
// the screen says what the engine does, so it changes only once the engine was told
|
||||
if !app.send_action(Action::SetPermissionAutoApprove(desired), "set auto-approve") {
|
||||
return;
|
||||
}
|
||||
app.permission_auto_approve = desired;
|
||||
let msg = if desired {
|
||||
"Auto-approve ON — tool permission asks are allowed automatically (deny rules still apply)."
|
||||
} else {
|
||||
"Auto-approve OFF — you'll be prompted before asked-for tool calls."
|
||||
};
|
||||
app.push_convo(ConvoBlock::System(msg.to_string()));
|
||||
}
|
||||
|
||||
pub(crate) fn reload_config(app: &mut App, repo_root: &std::path::Path) {
|
||||
let new_config = Config::load(repo_root);
|
||||
app.themes.reread();
|
||||
for notice in crate::app::theme_notices(&new_config, &app.themes) {
|
||||
app.push_convo(ConvoBlock::System(notice));
|
||||
}
|
||||
let theme_name = new_config.resolved_theme_name(&app.themes);
|
||||
let resolved = new_config.resolved_theme(&app.themes);
|
||||
let dock_mode = new_config.dock.mode();
|
||||
app.theme_styles = ThemeStyles::from_resolved(&resolved, &theme_name);
|
||||
app.dock.configured = dock_mode;
|
||||
app.dock.position = new_config.dock.position();
|
||||
crate::glyphs::resolve_vocabulary(new_config.glyphs());
|
||||
app.statusline_state.configured = new_config.statusline.visibility();
|
||||
app.guided_review_workspace.word_wrap = new_config.diff.word_wrap();
|
||||
app.guided_review_workspace.layout = new_config.diff.layout();
|
||||
app.banner = app.banner.with_animation(new_config.banner_animation());
|
||||
app.notifier = crate::notify::create_notifier(
|
||||
new_config.any_notifications(),
|
||||
new_config.notification_method(),
|
||||
);
|
||||
app.config = new_config;
|
||||
app.keymap = app.keymap.clone().with_overrides(load_keybindings(repo_root));
|
||||
tracing::info!(theme = theme_name, "reload complete — config + keybindings refreshed");
|
||||
}
|
||||
|
||||
/// Where the session works, and — with `remove` — ending it and removing its worktree.
|
||||
///
|
||||
/// Removal is refused while the worktree has anything uncommitted, naming it: the branch keeps
|
||||
/// the committed work, and nothing else would. Git refuses too, which is the last word.
|
||||
fn worktree_command(app: &mut App, arguments: Option<&str>) {
|
||||
let snapshot = app.workspace.as_ref();
|
||||
let worktree = snapshot.and_then(|snapshot| snapshot.worktree.clone());
|
||||
let branch = snapshot.and_then(|snapshot| snapshot.project.git_branch.clone());
|
||||
let root = snapshot.map(|snapshot| snapshot.project.root.clone());
|
||||
let say = |app: &mut App, text: String| app.push_convo(ConvoBlock::System(text));
|
||||
match (arguments.map(str::trim).filter(|arguments| !arguments.is_empty()), worktree, root) {
|
||||
(None, Some(place), _) => say(
|
||||
app,
|
||||
format!(
|
||||
"This session works in its own worktree, `{place}`, on branch `{}`. Your checkout \
|
||||
is untouched. `/worktree remove` ends the session and removes the worktree once \
|
||||
its work is committed; the branch stays, and resuming the session makes the \
|
||||
worktree again.",
|
||||
branch.unwrap_or_default()
|
||||
),
|
||||
),
|
||||
(None, None, _) => say(
|
||||
app,
|
||||
"This session works in your checkout. `luxe --worktree` starts one that works in a \
|
||||
checkout of its own."
|
||||
.into(),
|
||||
),
|
||||
(Some("remove"), Some(_), Some(root)) => {
|
||||
// Asked of git now, not read from the last snapshot, which may predate a file made
|
||||
// outside Luxe
|
||||
if app.send_action(Action::CheckWorktreeRemoval, "check the worktree") {
|
||||
app.worktree_removal_check = Some(root);
|
||||
}
|
||||
}
|
||||
(Some("remove"), _, _) => {
|
||||
say(app, "This session has no worktree of its own to remove.".into());
|
||||
}
|
||||
(Some(other), _, _) => {
|
||||
say(app, format!("`/worktree {other}` is not something it does: try `/worktree` or `/worktree remove`."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
35
crates/luxe-tui/src/app/commands/slash/tests.rs
Normal file
35
crates/luxe-tui/src/app/commands/slash/tests.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use super::*;
|
||||
use crate::fixture::{seeded_app, FixtureScenario};
|
||||
|
||||
/// Every slash command the registry lists is one `run_slash` has an arm for.
|
||||
///
|
||||
/// The break this catches: a command added to the table, or an id renamed in one place, compiled
|
||||
/// and did nothing when run.
|
||||
#[test]
|
||||
fn every_slash_command_is_one_run_slash_knows() {
|
||||
for command in crate::commands::CommandRegistry::all().iter() {
|
||||
if command.kind != crate::commands::CommandKind::Slash {
|
||||
continue;
|
||||
}
|
||||
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("fixture");
|
||||
assert!(run_slash(&mut app, command), "{} has no arm in run_slash", command.id);
|
||||
}
|
||||
}
|
||||
|
||||
/// A slash command nothing handles says so and is not remembered as used.
|
||||
///
|
||||
/// The break this catches: `dispatch` counted every slash command as run, so an unknown id closed
|
||||
/// the menu on nothing and then led the next one as recently used.
|
||||
#[test]
|
||||
fn a_slash_command_nothing_handles_says_so() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("fixture");
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
let mut unknown = registry.parse_slash("/cost").expect("a slash command");
|
||||
unknown.id = "cmd.unknown".into();
|
||||
|
||||
super::super::dispatch(&mut app, unknown);
|
||||
|
||||
let said = app.status.toast.as_ref().map(|(said, _)| said.as_str());
|
||||
assert_eq!(said, Some("Session cost did nothing here"));
|
||||
assert!(!app.recent_commands.ids().iter().any(|id| id == "cmd.unknown"));
|
||||
}
|
||||
19
crates/luxe-tui/src/app/commands/tests.rs
Normal file
19
crates/luxe-tui/src/app/commands/tests.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use super::*;
|
||||
use crate::fixture::{seeded_app, seeded_session, FixtureScenario};
|
||||
use crate::guided_review::GuidedReviewLoadState;
|
||||
use luxe_core::keymap::KeyMap;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
/// Runs a command the way the palette, the flyout and a typed `/…` all do.
|
||||
pub(super) fn run(app: &mut App, command: &crate::commands::Command) {
|
||||
dispatch(app, command.clone());
|
||||
}
|
||||
|
||||
mod answering;
|
||||
mod github;
|
||||
mod opening;
|
||||
mod palette;
|
||||
mod review_target;
|
||||
mod slash;
|
||||
|
||||
use answering::*;
|
||||
318
crates/luxe-tui/src/app/commands/tests/answering.rs
Normal file
318
crates/luxe-tui/src/app/commands/tests/answering.rs
Normal file
@@ -0,0 +1,318 @@
|
||||
//! Answering — your own pull request's threads, sent as shown, and the worktree check.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn key(code: crossterm::event::KeyCode) -> crate::app::Msg {
|
||||
crate::app::Msg::Key(crossterm::event::KeyEvent::new(
|
||||
code,
|
||||
crossterm::event::KeyModifiers::NONE,
|
||||
))
|
||||
}
|
||||
|
||||
/// Your own pull request, its threads adopted, the answers preview closed.
|
||||
pub(super) fn own_pull_request() -> (App, mpsc::Receiver<Action>) {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewOwnPullRequest).expect("fixture");
|
||||
app.guided_review_workspace.thread_answers = None;
|
||||
let (engine_tx, engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
(app, engine_rx)
|
||||
}
|
||||
|
||||
/// On your own pull request the finish chooser keeps its local choices — committing the fixes is
|
||||
/// one — and adds answering on GitHub, which asks whether the fix is there before anything else.
|
||||
#[test]
|
||||
fn finishing_your_own_pull_request_offers_answering_on_github() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
assert!(app.guided_review_workspace.finish_offers_answers);
|
||||
let mut seen = Vec::new();
|
||||
for _ in 0..6 {
|
||||
app.guided_review_workspace.move_finish_review_choice(true);
|
||||
seen.push(app.guided_review_workspace.finish_review_choice.expect("open"));
|
||||
}
|
||||
assert!(seen.contains(&crate::guided_review::FinishReviewChoice::AnswerOnGitHub), "{seen:?}");
|
||||
assert!(seen.contains(&crate::guided_review::FinishReviewChoice::AcceptAndCommit));
|
||||
while app.guided_review_workspace.finish_review_choice
|
||||
!= Some(crate::guided_review::FinishReviewChoice::AnswerOnGitHub)
|
||||
{
|
||||
app.guided_review_workspace.move_finish_review_choice(true);
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
|
||||
assert!(app.guided_review_workspace.finish_review_choice.is_none());
|
||||
let answers = app.guided_review_workspace.thread_answers.as_ref().expect("preview");
|
||||
assert_eq!(answers.rows.len(), 3, "two threads and a conversation comment");
|
||||
assert!(answers.rows[0].resolve, "the verified thread resolves by default");
|
||||
assert!(!answers.rows[1].resolve, "the unfixed one does not");
|
||||
assert!(!answers.rows[2].resolve, "nor does the conversation, which cannot be resolved");
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::PrepareThreadAnswers { .. })));
|
||||
|
||||
// Someone else's pull request, or a working tree, offers no such choice
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
assert!(!app.guided_review_workspace.finish_offers_answers);
|
||||
}
|
||||
|
||||
/// What is sent is what the preview shows: the reader's reply in their words, the resolves they
|
||||
/// chose, and nothing for a thread left alone.
|
||||
#[test]
|
||||
fn answers_are_sent_as_shown_with_the_readers_own_reply() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenThreadAnswers);
|
||||
let _ = engine_rx.try_recv();
|
||||
|
||||
// A reply on the second thread, typed with real keys; Enter is a new line, not a send
|
||||
app.update(key(crossterm::event::KeyCode::Down));
|
||||
app.update(key(crossterm::event::KeyCode::Char('c')));
|
||||
for character in "Not fixed yet.".chars() {
|
||||
app.update(key(crossterm::event::KeyCode::Char(character)));
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
for character in "Next push.".chars() {
|
||||
app.update(key(crossterm::event::KeyCode::Char(character)));
|
||||
}
|
||||
assert!(engine_rx.try_recv().is_err(), "typing sends nothing");
|
||||
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
)));
|
||||
// Sending is refused while a reply is still being written
|
||||
app.update(key(crossterm::event::KeyCode::Char('c')));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmThreadAnswers);
|
||||
assert!(engine_rx.try_recv().is_err(), "not while replying");
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
// and resolving the first stops, so it is left alone entirely
|
||||
app.update(key(crossterm::event::KeyCode::Up));
|
||||
app.update(key(crossterm::event::KeyCode::Char(' ')));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
|
||||
let Ok(Action::AnswerThreads { answers, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected answers");
|
||||
};
|
||||
assert_eq!(answers.len(), 1, "a thread neither resolved nor replied to is not sent");
|
||||
assert_eq!(answers[0].reply.as_deref(), Some("Not fixed yet.\nNext push."), "the Esc kept it");
|
||||
assert!(!answers[0].resolve);
|
||||
// Named by comment: which thread that is, the engine reads from the session
|
||||
let session = app.review.session().expect("session");
|
||||
let finding = session.findings.iter().find(|f| f.id == answers[0].finding_id).unwrap();
|
||||
assert!(finding.github_thread.is_some(), "a comment that came from a thread");
|
||||
|
||||
// In flight, the preview cannot be closed
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
assert!(app.guided_review_workspace.thread_answers.as_ref().is_some_and(|a| a.sending));
|
||||
}
|
||||
|
||||
/// Results mark what landed in one save; a thread that failed stays on screen saying why, and a
|
||||
/// preview with nothing left closes.
|
||||
#[test]
|
||||
fn answered_threads_are_marked_and_failed_ones_stay_with_why() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenThreadAnswers);
|
||||
let _ = engine_rx.try_recv();
|
||||
let rows = app.guided_review_workspace.thread_answers.as_ref().expect("preview").rows.clone();
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
app.update(crate::app::Msg::GuidedReviewMoveThreadAnswers(true));
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmThreadAnswers);
|
||||
let Ok(Action::AnswerThreads { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected answers");
|
||||
};
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ThreadsAnswered {
|
||||
request_id: request_id.clone(),
|
||||
results: vec![
|
||||
luxe_core::guided_review::ThreadAnswerResult {
|
||||
finding_id: rows[0].finding_id.clone(),
|
||||
reply_url: None,
|
||||
resolved: true,
|
||||
error: None,
|
||||
},
|
||||
luxe_core::guided_review::ThreadAnswerResult {
|
||||
finding_id: rows[1].finding_id.clone(),
|
||||
reply_url: None,
|
||||
resolved: false,
|
||||
error: Some("GitHub refused it: Resource not accessible by integration.".into()),
|
||||
},
|
||||
],
|
||||
}));
|
||||
|
||||
let answers = app.guided_review_workspace.thread_answers.as_ref().expect("still open");
|
||||
// The conversation comment was not answered, so it stays too
|
||||
assert_eq!(answers.rows.len(), 2);
|
||||
assert_eq!(answers.rows[0].finding_id, rows[1].finding_id, "the one that failed stays");
|
||||
assert_eq!(answers.rows[1].finding_id, rows[2].finding_id);
|
||||
assert!(answers.rows[0].error.as_deref().is_some_and(|error| error.contains("not accessible")));
|
||||
let mut refreshed = false;
|
||||
while let Ok(action) = engine_rx.try_recv() {
|
||||
match action {
|
||||
Action::RefreshWorkspace => refreshed = true,
|
||||
// The engine records what landed on the session as it answers
|
||||
Action::EditReview { .. } => panic!("the TUI does not mark answered threads itself"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert!(refreshed, "the bar's thread count changed on GitHub, so it is asked again at once");
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text))
|
||||
if text == "[review] Answered 1 thread on GitHub; 1 thread did not go, and say why."
|
||||
));
|
||||
|
||||
// A stale answer changes nothing
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ThreadsAnswered {
|
||||
request_id: luxe_core::guided_review::ThreadAnswersId::new(),
|
||||
results: Vec::new(),
|
||||
}));
|
||||
assert_eq!(app.guided_review_workspace.thread_answers.as_ref().expect("open").rows.len(), 2);
|
||||
}
|
||||
|
||||
/// A comment in the conversation has no resolve to toggle, and says so, pointing at the reply.
|
||||
#[test]
|
||||
fn a_conversation_comment_has_nothing_to_resolve() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenThreadAnswers);
|
||||
let _ = engine_rx.try_recv();
|
||||
app.update(crate::app::Msg::GuidedReviewMoveThreadAnswers(true));
|
||||
app.update(crate::app::Msg::GuidedReviewMoveThreadAnswers(true));
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
let answers = app.guided_review_workspace.thread_answers.as_ref().expect("preview");
|
||||
assert!(!answers.rows[2].resolve);
|
||||
assert_eq!(
|
||||
app.status.toast(),
|
||||
Some("A comment in the conversation has nothing to resolve: c replies")
|
||||
);
|
||||
}
|
||||
|
||||
/// A thread GitHub will not let this account resolve or reply to says so instead of toggling,
|
||||
/// while its neighbor that allows it toggles as usual.
|
||||
#[test]
|
||||
fn a_thread_you_may_not_resolve_says_so() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
let second = app
|
||||
.review
|
||||
.session()
|
||||
.expect("session")
|
||||
.findings
|
||||
.iter()
|
||||
.filter(|finding| finding.github_thread.is_some())
|
||||
.nth(1)
|
||||
.map(|finding| finding.id.clone())
|
||||
.expect("two threads");
|
||||
for finding in &mut app.review.session_mut().expect("session").findings {
|
||||
if finding.id == second {
|
||||
let thread = finding.github_thread.as_mut().expect("thread");
|
||||
thread.can_resolve = false;
|
||||
thread.can_reply = false;
|
||||
}
|
||||
}
|
||||
app.update(crate::app::Msg::GuidedReviewOpenThreadAnswers);
|
||||
let _ = engine_rx.try_recv();
|
||||
let resolve = |app: &App, row: usize| {
|
||||
app.guided_review_workspace.thread_answers.as_ref().unwrap().rows[row].resolve
|
||||
};
|
||||
assert!(resolve(&app, 0));
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
assert!(!resolve(&app, 0), "the first may be resolved, so it toggles");
|
||||
app.update(crate::app::Msg::GuidedReviewMoveThreadAnswers(true));
|
||||
app.update(crate::app::Msg::GuidedReviewToggleThreadResolve);
|
||||
assert!(!resolve(&app, 1));
|
||||
assert!(app.status.toast().is_some_and(|toast| toast.contains("resolve")));
|
||||
app.update(crate::app::Msg::GuidedReviewBeginThreadReply);
|
||||
assert!(app.guided_review_workspace.thread_answers.as_ref().unwrap().replying.is_none());
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmThreadAnswers);
|
||||
assert!(engine_rx.try_recv().is_err(), "nothing to send");
|
||||
}
|
||||
|
||||
/// Whether the fix is on GitHub reaches the preview, and a failure before any thread was touched
|
||||
/// stops the spinner and says why.
|
||||
#[test]
|
||||
fn preparing_and_failing_reach_the_preview() {
|
||||
let (mut app, mut engine_rx) = own_pull_request();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenThreadAnswers);
|
||||
let Ok(Action::PrepareThreadAnswers { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ThreadAnswersPrepared {
|
||||
request_id: request_id.clone(),
|
||||
pushed: true,
|
||||
uncommitted: false,
|
||||
}));
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.thread_answers.as_ref().unwrap().prepared,
|
||||
Some((true, false))
|
||||
);
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmThreadAnswers);
|
||||
let Ok(Action::AnswerThreads { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected answers");
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ThreadAnswersFailed {
|
||||
request_id,
|
||||
message: "The GitHub CLI is not signed in.".into(),
|
||||
}));
|
||||
let answers = app.guided_review_workspace.thread_answers.as_ref().unwrap();
|
||||
assert!(!answers.sending);
|
||||
assert_eq!(answers.error.as_deref(), Some("The GitHub CLI is not signed in."));
|
||||
}
|
||||
|
||||
/// `/worktree` says where the session works. `remove` asks git, through the engine, what is
|
||||
/// uncommitted right now — a snapshot can predate a file made outside Luxe — and is refused,
|
||||
/// naming it, unless nothing is; then the session ends with its worktree to remove.
|
||||
#[test]
|
||||
fn worktree_says_where_and_removes_only_committed_work() {
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
let last = |app: &App| match app.convo.last().map(|item| item.block()) {
|
||||
Some(ConvoBlock::System(text)) => text.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let mut app = seeded_app("nord", FixtureScenario::DockWide).expect("fixture");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
run(&mut app, ®istry.parse_slash("/worktree").expect("parses"));
|
||||
assert!(last(&app).starts_with("This session works in your checkout."), "{}", last(&app));
|
||||
run(&mut app, ®istry.parse_slash("/worktree remove").expect("parses"));
|
||||
assert!(last(&app).contains("no worktree of its own"), "{}", last(&app));
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
|
||||
let workspace = app.workspace.as_mut().expect("workspace");
|
||||
workspace.worktree = Some(".luxe/worktrees/topic".into());
|
||||
workspace.project.git_branch = Some("topic".into());
|
||||
let root = workspace.project.root.clone();
|
||||
run(&mut app, ®istry.parse_slash("/worktree").expect("parses"));
|
||||
assert!(
|
||||
last(&app).starts_with(
|
||||
"This session works in its own worktree, `.luxe/worktrees/topic`, on branch `topic`."
|
||||
),
|
||||
"{}",
|
||||
last(&app)
|
||||
);
|
||||
|
||||
// Git says something is uncommitted: refused, naming it
|
||||
run(&mut app, ®istry.parse_slash("/worktree remove").expect("parses"));
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::CheckWorktreeRemoval)));
|
||||
let files: Vec<String> = (1..=7).map(|n| format!("stray-{n}.txt")).collect();
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::WorktreeRemovalChecked {
|
||||
uncommitted: files,
|
||||
}));
|
||||
assert!(last(&app).starts_with("The worktree has work that is not committed: stray-1.txt"));
|
||||
assert!(last(&app).contains("and 2 more"), "{}", last(&app));
|
||||
assert_eq!(app.outbox.worktree_removal, None);
|
||||
|
||||
// An answer nobody asked for changes nothing
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::WorktreeRemovalChecked {
|
||||
uncommitted: Vec::new(),
|
||||
}));
|
||||
assert_eq!(app.outbox.worktree_removal, None);
|
||||
|
||||
// Nothing uncommitted: the session ends to remove it
|
||||
run(&mut app, ®istry.parse_slash("/worktree remove").expect("parses"));
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::CheckWorktreeRemoval)));
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::WorktreeRemovalChecked {
|
||||
uncommitted: Vec::new(),
|
||||
}));
|
||||
assert_eq!(app.outbox.worktree_removal, Some(root));
|
||||
|
||||
run(&mut app, ®istry.parse_slash("/worktree prune").expect("parses"));
|
||||
assert!(last(&app).contains("is not something it does"), "{}", last(&app));
|
||||
}
|
||||
334
crates/luxe-tui/src/app/commands/tests/github.rs
Normal file
334
crates/luxe-tui/src/app/commands/tests/github.rs
Normal file
@@ -0,0 +1,334 @@
|
||||
//! GitHub posts — a review posted to a pull request, and the conversation read back.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A post fixture with its engine channel in hand, and the post's request id.
|
||||
pub(super) fn post_fixture(
|
||||
) -> (App, mpsc::Receiver<Action>, luxe_core::guided_review::PullRequestPostId) {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost)
|
||||
.expect("pull request post fixture");
|
||||
let (engine_tx, engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
let request_id =
|
||||
app.guided_review_workspace.github_post.as_ref().expect("post preview").request_id.clone();
|
||||
(app, engine_rx, request_id)
|
||||
}
|
||||
|
||||
/// A pull request's review finishes on GitHub: Alt+Enter asks GitHub what the preview needs rather
|
||||
/// than opening the local finish choices, and Alt+U offers to check it out for the agent.
|
||||
#[test]
|
||||
fn finishing_a_pull_request_review_asks_github_and_alt_u_offers_a_worktree() {
|
||||
let mut app =
|
||||
seeded_app("nord", FixtureScenario::GuidedReviewPullRequest).expect("pull request fixture");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
|
||||
assert!(app.guided_review_workspace.finish_review_choice.is_none());
|
||||
let post = app.guided_review_workspace.github_post.as_ref().expect("post preview");
|
||||
assert!(post.prepared.is_none(), "nothing to preview until GitHub answers");
|
||||
let Ok(Action::PreparePullRequestPost { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected the engine to be asked");
|
||||
};
|
||||
assert_eq!(request_id, post.request_id);
|
||||
|
||||
// Alt+U cannot reach an agent that has not got the code: it offers to check it out instead
|
||||
app.guided_review_workspace.github_post = None;
|
||||
app.update(crate::app::Msg::GuidedReviewOpenSendPreview);
|
||||
assert!(app.guided_review_workspace.send_preview.is_none());
|
||||
assert!(app.guided_review_workspace.pull_request_fix.is_some());
|
||||
}
|
||||
|
||||
/// Confirming names the preview it shows, with the verdict on screen and the session revision the
|
||||
/// preview was drawn from, so the engine posts that and nothing else; it plans the post with the
|
||||
/// same function over the same comments, and refuses if they moved. While it is in flight the
|
||||
/// dialog cannot be closed, since closing it would drop the answer that says where it landed.
|
||||
#[test]
|
||||
fn confirming_posts_the_preview_it_shows_and_holds_the_dialog_open() {
|
||||
let (mut app, mut engine_rx, prepared) = post_fixture();
|
||||
assert!(crate::app::github_post_plan(&app).expect("prepared").is_ok(), "postable");
|
||||
let verdict = app.guided_review_workspace.github_post.as_ref().expect("preview").verdict;
|
||||
let revision = app.review.session().expect("session").revision;
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
|
||||
let Ok(Action::PostPullRequestReview { request_id, verdict: sent, session_revision }) =
|
||||
engine_rx.try_recv()
|
||||
else {
|
||||
panic!("expected a post");
|
||||
};
|
||||
assert_eq!(request_id, prepared, "the preview the engine read, not a new attempt");
|
||||
assert_eq!(sent, verdict);
|
||||
assert_eq!(session_revision, revision);
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewCancelGithubPost);
|
||||
assert!(app.guided_review_workspace.github_post.as_ref().is_some_and(|post| post.posting));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
assert!(engine_rx.try_recv().is_err(), "a second press does not post twice");
|
||||
}
|
||||
|
||||
/// GitHub refuses an author's verdict on their own pull request, so the preview offers a comment
|
||||
/// and nothing else once it knows.
|
||||
#[test]
|
||||
fn an_authors_own_pull_request_offers_only_a_comment() {
|
||||
let (mut app, _engine_rx, _) = post_fixture();
|
||||
let post = app.guided_review_workspace.github_post.as_mut().expect("post preview");
|
||||
post.prepared = None;
|
||||
let request_id = post.request_id.clone();
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestPostPrepared {
|
||||
request_id,
|
||||
patches: Vec::new(),
|
||||
head_moved: false,
|
||||
own_pull_request: true,
|
||||
}));
|
||||
app.update(crate::app::Msg::GuidedReviewMoveGithubVerdict(true));
|
||||
|
||||
let post = app.guided_review_workspace.github_post.as_ref().expect("post preview");
|
||||
assert_eq!(post.verdict, luxe_core::github::ReviewEvent::Comment);
|
||||
assert_eq!(post.verdicts(), &[luxe_core::github::ReviewEvent::Comment]);
|
||||
}
|
||||
|
||||
/// A post that landed marks what it carried and records the verdict, in one save; an answer for an
|
||||
/// attempt nobody is waiting on changes nothing.
|
||||
#[test]
|
||||
fn a_landed_post_marks_its_comments_and_a_stale_answer_is_ignored() {
|
||||
let (mut app, mut engine_rx, _) = post_fixture();
|
||||
let shown = crate::app::github_post_plan(&app).expect("prepared").expect("postable");
|
||||
let finding_ids: Vec<_> = shown.placed.iter().map(|placed| placed.finding_id.clone()).collect();
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
let Ok(Action::PostPullRequestReview { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a post");
|
||||
};
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestReviewPosted {
|
||||
request_id: luxe_core::guided_review::PullRequestPostId::new(),
|
||||
github_review_id: 1,
|
||||
url: "https://example.invalid/stale".into(),
|
||||
finding_ids: finding_ids.clone(),
|
||||
}));
|
||||
assert!(engine_rx.try_recv().is_err(), "a stale answer saves nothing");
|
||||
assert!(app.guided_review_workspace.github_post.is_some());
|
||||
|
||||
let url = "https://github.com/acme/notify/pull/42#pullrequestreview-9".to_owned();
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestReviewPosted {
|
||||
request_id,
|
||||
github_review_id: 9,
|
||||
url: url.clone(),
|
||||
finding_ids: finding_ids.clone(),
|
||||
}));
|
||||
|
||||
assert!(app.guided_review_workspace.github_post.is_none());
|
||||
assert_eq!(app.guided_review_workspace.posted_review_url.as_deref(), Some(url.as_str()));
|
||||
// The engine marked what went and recorded the verdict as it posted; the TUI sends nothing,
|
||||
// and takes the marks when the desk's save arrives
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
assert!(!finding_ids.is_empty());
|
||||
}
|
||||
|
||||
/// A failure keeps the preview open with GitHub's reason, and posting again is allowed.
|
||||
#[test]
|
||||
fn a_failed_post_says_why_and_can_be_tried_again() {
|
||||
let (mut app, mut engine_rx, _) = post_fixture();
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
let Ok(Action::PostPullRequestReview { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a post");
|
||||
};
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestPostFailed {
|
||||
request_id,
|
||||
message: "GitHub refused the review: Line could not be resolved.".into(),
|
||||
}));
|
||||
|
||||
let post = app.guided_review_workspace.github_post.as_ref().expect("still open");
|
||||
assert!(!post.posting);
|
||||
assert!(post.error.as_deref().is_some_and(|error| error.contains("Line could not")));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::PostPullRequestReview { .. })));
|
||||
}
|
||||
|
||||
/// Requesting changes with nothing to say is refused before anything is sent.
|
||||
#[test]
|
||||
fn requesting_changes_without_a_summary_sends_nothing() {
|
||||
let (mut app, mut engine_rx, _) = post_fixture();
|
||||
let session = app.review.session_mut().expect("session");
|
||||
session.findings.retain(|finding| {
|
||||
!matches!(finding.anchor, luxe_core::guided_review::FindingAnchor::Review)
|
||||
|| finding.severity == luxe_core::guided_review::FindingSeverity::Question
|
||||
});
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmGithubPost);
|
||||
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
assert!(!app.guided_review_workspace.github_post.as_ref().expect("open").posting);
|
||||
assert!(
|
||||
app.status.toast().is_some_and(|toast| toast.starts_with("Requesting changes needs")),
|
||||
"{:?}",
|
||||
app.status.toast()
|
||||
);
|
||||
}
|
||||
|
||||
/// The verdict steps through what is on offer both ways and wraps at either end.
|
||||
#[test]
|
||||
fn the_verdict_steps_both_ways_and_wraps() {
|
||||
use luxe_core::github::ReviewEvent::{Approve, Comment, RequestChanges};
|
||||
let (mut app, _engine_rx, _) = post_fixture();
|
||||
let post = app.guided_review_workspace.github_post.as_mut().expect("post preview");
|
||||
post.verdict = Comment;
|
||||
let mut forward = Vec::new();
|
||||
for _ in 0..3 {
|
||||
post.move_verdict(true);
|
||||
forward.push(post.verdict);
|
||||
}
|
||||
assert_eq!(forward, [Approve, RequestChanges, Comment]);
|
||||
let mut back = Vec::new();
|
||||
for _ in 0..3 {
|
||||
post.move_verdict(false);
|
||||
back.push(post.verdict);
|
||||
}
|
||||
assert_eq!(back, [RequestChanges, Approve, Comment]);
|
||||
}
|
||||
|
||||
/// Request changes needs a summary, and the preview is where it is written: `c` there opens a
|
||||
/// comment on the review as a whole, over the preview, and once it is saved the preview posts it.
|
||||
#[test]
|
||||
fn a_summary_is_written_from_the_preview_and_posts_with_it() {
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
let (mut app, mut engine_rx, _) = post_fixture();
|
||||
let session = app.review.session_mut().expect("session");
|
||||
session.findings.retain(|finding| {
|
||||
!matches!(finding.anchor, luxe_core::guided_review::FindingAnchor::Review)
|
||||
|| finding.severity == luxe_core::guided_review::FindingSeverity::Question
|
||||
});
|
||||
assert!(matches!(
|
||||
crate::app::github_post_plan(&app),
|
||||
Some(Err(luxe_core::guided_review::PostPlanError::NeedsBody))
|
||||
));
|
||||
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE)));
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("summary composer");
|
||||
assert_eq!(draft.anchor, luxe_core::guided_review::FindingAnchor::Review);
|
||||
for character in "Bound the redirects.".chars() {
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(
|
||||
KeyCode::Char(character),
|
||||
KeyModifiers::NONE,
|
||||
)));
|
||||
}
|
||||
assert!(app.guided_review_workspace.github_post.is_some(), "typing stays in the composer");
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::CONTROL)));
|
||||
let Ok(Action::EditReview {
|
||||
request_id,
|
||||
edit: luxe_core::engine::ReviewEdit::Comment { draft, .. },
|
||||
..
|
||||
}) = engine_rx.try_recv()
|
||||
else {
|
||||
panic!("expected the summary to be sent to the review desk");
|
||||
};
|
||||
// What the desk stores for it, answering this edit
|
||||
let mut stored = app.review.session.clone().expect("session");
|
||||
stored
|
||||
.add_finding(luxe_core::guided_review::ReviewFinding {
|
||||
id: luxe_core::guided_review::FindingId::new(),
|
||||
label: String::new(),
|
||||
anchor: draft.anchor,
|
||||
severity: draft.severity,
|
||||
title: draft.title,
|
||||
body: draft.body,
|
||||
proposed_fix: draft.proposed_fix,
|
||||
state: luxe_core::guided_review::FindingState::Draft,
|
||||
thread: Vec::new(),
|
||||
posted: None,
|
||||
github_thread: None,
|
||||
})
|
||||
.expect("the summary is a valid comment");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ReviewSessionSaved {
|
||||
request_id,
|
||||
session: Box::new(stored),
|
||||
}));
|
||||
|
||||
let plan = crate::app::github_post_plan(&app).expect("prepared").expect("postable now");
|
||||
assert_eq!(plan.review.body, "Bound the redirects.");
|
||||
assert!(app.guided_review_workspace.finding_draft.is_none());
|
||||
}
|
||||
|
||||
/// `/pr` opens the branch's pull request in its card and asks for the overview. Its threads are
|
||||
/// work to do: once the overview lands, `t` opens them in a review against the working tree, as
|
||||
/// `/pr` used to on its own. A merged one has nothing left to resolve, and a branch with no pull
|
||||
/// request gets the sentence saying so.
|
||||
#[test]
|
||||
fn slash_pr_opens_the_card_and_its_threads_are_a_key_away() {
|
||||
use luxe_core::github::overview::{Overview, PullRequestOverview};
|
||||
use luxe_core::github::{CheckRollup, PullRequestState, PullRequestStatus, ReviewDecision};
|
||||
use luxe_core::workspace::PullRequestPresence;
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
for (state, opens) in [(PullRequestState::Open, true), (PullRequestState::Merged, false)] {
|
||||
let mut app = seeded_app("nord", FixtureScenario::DockWide).expect("fixture app");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
app.workspace.as_mut().expect("workspace").pull_request =
|
||||
PullRequestPresence::Found(PullRequestStatus {
|
||||
number: 146,
|
||||
title: "Round trip".into(),
|
||||
url: "https://github.com/acme/app/pull/146".into(),
|
||||
state,
|
||||
draft: false,
|
||||
review_decision: None,
|
||||
checks: CheckRollup::default(),
|
||||
unresolved_threads: 2,
|
||||
head_oid: "f6195af".into(),
|
||||
stack: None,
|
||||
});
|
||||
|
||||
run(&mut app, ®istry.parse_slash("/pr").expect("/pr parses"));
|
||||
assert_eq!(app.overlays.pull_request_card.as_ref().map(|card| card.number), Some(146));
|
||||
let asked = std::iter::from_fn(|| engine_rx.try_recv().ok()).any(|action| {
|
||||
matches!(
|
||||
action,
|
||||
Action::ReadGithubOverview { repository: None, number: 146, pull_request: true }
|
||||
)
|
||||
});
|
||||
assert!(asked, "the card asks for its overview");
|
||||
|
||||
let overview = PullRequestOverview {
|
||||
number: 146,
|
||||
state,
|
||||
review_decision: Some(ReviewDecision::ChangesRequested),
|
||||
unresolved_threads: 2,
|
||||
viewer: luxe_core::github::overview::Viewer {
|
||||
author: true,
|
||||
can_push: true,
|
||||
can_merge: true,
|
||||
},
|
||||
..crate::fixture::pull_request_overview()
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GithubOverviewRead {
|
||||
repository: None,
|
||||
number: 146,
|
||||
overview: Some(Overview::PullRequest(Box::new(overview))),
|
||||
error: None,
|
||||
local: None,
|
||||
}));
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
let loaded =
|
||||
std::iter::from_fn(|| engine_rx.try_recv().ok()).find_map(|action| match action {
|
||||
Action::LoadGuidedReview { target, .. } => Some(target),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(
|
||||
loaded,
|
||||
opens.then_some(luxe_core::guided_review::ReviewTarget::OwnPullRequest { number: 146 }),
|
||||
"{state:?}"
|
||||
);
|
||||
assert_eq!(app.overlays.pull_request_card.is_none(), opens, "acting leaves the card");
|
||||
}
|
||||
|
||||
let mut app = seeded_app("nord", FixtureScenario::DockWide).expect("fixture app");
|
||||
app.workspace.as_mut().expect("workspace").pull_request = PullRequestPresence::None;
|
||||
run(&mut app, ®istry.parse_slash("/pr").expect("/pr parses"));
|
||||
assert!(app.overlays.pull_request_card.is_none());
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text)) if text == "This branch has no pull request on GitHub."
|
||||
));
|
||||
}
|
||||
637
crates/luxe-tui/src/app/commands/tests/opening.rs
Normal file
637
crates/luxe-tui/src/app/commands/tests/opening.rs
Normal file
@@ -0,0 +1,637 @@
|
||||
//! Opening — a branch's pull request, a fix for someone else's, and a review opened as a stack.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A branch's review, with the status row saying what GitHub has for the branch.
|
||||
pub(super) fn branch_review(
|
||||
presence: luxe_core::workspace::PullRequestPresence,
|
||||
) -> (App, mpsc::Receiver<Action>) {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("fixture");
|
||||
let mut snapshot = app.workspace.clone().unwrap_or_else(|| {
|
||||
luxe_core::workspace::WorkspaceSnapshot::empty(
|
||||
luxe_core::workspace::WorkspaceScopeId::new("scope-a"),
|
||||
luxe_core::workspace::ProjectIdentity::non_git(
|
||||
"/project".into(),
|
||||
"project",
|
||||
"/project",
|
||||
),
|
||||
)
|
||||
});
|
||||
snapshot.pull_request = presence;
|
||||
app.workspace = Some(snapshot);
|
||||
let (engine_tx, engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
(app, engine_rx)
|
||||
}
|
||||
|
||||
pub(super) fn found(
|
||||
state: luxe_core::github::PullRequestState,
|
||||
) -> luxe_core::workspace::PullRequestPresence {
|
||||
luxe_core::workspace::PullRequestPresence::Found(luxe_core::github::PullRequestStatus {
|
||||
number: 40,
|
||||
title: "Earlier".into(),
|
||||
url: String::new(),
|
||||
state,
|
||||
draft: false,
|
||||
review_decision: None,
|
||||
checks: Default::default(),
|
||||
unresolved_threads: 0,
|
||||
head_oid: String::new(),
|
||||
stack: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Offered where the branch has no open pull request, as far as the status row knows, and
|
||||
/// choosing it asks the engine for the draft.
|
||||
#[test]
|
||||
fn finishing_a_branch_without_a_pull_request_offers_opening_one() {
|
||||
use crate::guided_review::FinishReviewChoice;
|
||||
use luxe_core::github::PullRequestState;
|
||||
use luxe_core::workspace::PullRequestPresence;
|
||||
for (presence, offered) in [
|
||||
(PullRequestPresence::None, true),
|
||||
(found(PullRequestState::Closed), true),
|
||||
(found(PullRequestState::Open), false),
|
||||
(PullRequestPresence::Unknown, false),
|
||||
(PullRequestPresence::Unavailable { reason: "no gh".into() }, false),
|
||||
] {
|
||||
let (mut app, _) = branch_review(presence.clone());
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
assert_eq!(app.guided_review_workspace.finish_offers_opening, offered, "{presence:?}");
|
||||
let mut seen = Vec::new();
|
||||
for _ in 0..7 {
|
||||
app.guided_review_workspace.move_finish_review_choice(true);
|
||||
seen.push(app.guided_review_workspace.finish_review_choice.expect("open"));
|
||||
}
|
||||
assert_eq!(seen.contains(&FinishReviewChoice::OpenPullRequest), offered, "{presence:?}");
|
||||
}
|
||||
|
||||
let (mut app, mut engine_rx) = branch_review(PullRequestPresence::None);
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
while app.guided_review_workspace.finish_review_choice
|
||||
!= Some(FinishReviewChoice::OpenPullRequest)
|
||||
{
|
||||
app.guided_review_workspace.move_finish_review_choice(true);
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
assert!(app.guided_review_workspace.finish_review_choice.is_none());
|
||||
assert!(app.guided_review_workspace.pull_request_opening.is_some());
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::PreparePullRequest { .. })));
|
||||
|
||||
// Your own pull request already exists, so it answers its threads instead
|
||||
let (mut app, _) = own_pull_request();
|
||||
let mut snapshot = app.workspace.clone().unwrap_or_else(|| {
|
||||
luxe_core::workspace::WorkspaceSnapshot::empty(
|
||||
luxe_core::workspace::WorkspaceScopeId::new("scope-a"),
|
||||
luxe_core::workspace::ProjectIdentity::non_git(
|
||||
"/project".into(),
|
||||
"project",
|
||||
"/project",
|
||||
),
|
||||
)
|
||||
});
|
||||
snapshot.pull_request = PullRequestPresence::None;
|
||||
app.workspace = Some(snapshot);
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
assert!(!app.guided_review_workspace.finish_offers_opening);
|
||||
}
|
||||
|
||||
pub(super) fn prepared_event(
|
||||
request_id: luxe_core::guided_review::PullRequestOpenId,
|
||||
commits: &[&str],
|
||||
) -> crate::app::Msg {
|
||||
crate::app::Msg::Engine(luxe_core::event::Event::PullRequestPrepared {
|
||||
request_id,
|
||||
pull_request: luxe_core::github::NewPullRequest {
|
||||
head: "7-fix".into(),
|
||||
base: "main".into(),
|
||||
title: "Fix the total".into(),
|
||||
body: "### Sum every element\n\nWhy.\n\nCloses #7".into(),
|
||||
draft: false,
|
||||
},
|
||||
publication: luxe_core::github::Publication::Unpublished,
|
||||
uncommitted: 1,
|
||||
commits: commits.iter().map(|subject| (*subject).to_owned()).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
/// What opens is the draft with the reader's edits, typed with real keys, and the reviewed work is
|
||||
/// committed first when the preview said so. Nothing is sent while typing.
|
||||
#[test]
|
||||
fn the_pull_request_opens_as_the_reader_edited_it() {
|
||||
let (mut app, mut engine_rx) = branch_review(luxe_core::workspace::PullRequestPresence::None);
|
||||
app.update(crate::app::Msg::GuidedReviewOpenPullRequest);
|
||||
let Ok(Action::PreparePullRequest { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
app.update(prepared_event(request_id, &["Sum every element"]));
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
for character in " at last".chars() {
|
||||
app.update(key(crossterm::event::KeyCode::Char(character)));
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
app.update(key(crossterm::event::KeyCode::Char('e')));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
for character in "Tested by hand.".chars() {
|
||||
app.update(key(crossterm::event::KeyCode::Char(character)));
|
||||
}
|
||||
assert!(engine_rx.try_recv().is_err(), "typing sends nothing");
|
||||
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
)));
|
||||
// A field dropped with Esc keeps what was there before
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
app.update(key(crossterm::event::KeyCode::Char('!')));
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
app.update(key(crossterm::event::KeyCode::Char('d')));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
|
||||
// What the reader could change goes back; the engine kept the rest, commits included
|
||||
let Ok(Action::OpenPullRequest { request_id, title, body, draft }) = engine_rx.try_recv()
|
||||
else {
|
||||
panic!("expected an open");
|
||||
};
|
||||
assert_eq!(title, "Fix the total at last");
|
||||
assert_eq!(
|
||||
body, "### Sum every element\n\nWhy.\n\nCloses #7\nTested by hand.",
|
||||
"the reader's words, as typed"
|
||||
);
|
||||
assert!(draft, "d made it a draft");
|
||||
|
||||
// In flight, the preview cannot be closed or edited
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
let opening = app.guided_review_workspace.pull_request_opening.as_ref().expect("preview");
|
||||
assert!(opening.opening && opening.editing.is_none());
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestOpened {
|
||||
request_id,
|
||||
number: 151,
|
||||
url: "https://github.com/acme/app/pull/151".into(),
|
||||
committed: vec!["0123abcd".into()],
|
||||
}));
|
||||
assert!(app.guided_review_workspace.pull_request_opening.is_none());
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.posted_review_url.as_deref(),
|
||||
Some("https://github.com/acme/app/pull/151"),
|
||||
"o opens it"
|
||||
);
|
||||
assert!(
|
||||
app.convo.iter().any(|item| matches!(item.block(), ConvoBlock::System(text)
|
||||
if text == "[review] Committed the reviewed work and opened #151: https://github.com/acme/app/pull/151")),
|
||||
"says what happened"
|
||||
);
|
||||
}
|
||||
|
||||
/// `E` hands the description to the reader's editor, and what comes back replaces the draft. A
|
||||
/// preview that started opening meanwhile keeps what it sent.
|
||||
#[test]
|
||||
fn the_description_goes_to_your_editor_and_comes_back() {
|
||||
let (mut app, mut engine_rx) = branch_review(luxe_core::workspace::PullRequestPresence::None);
|
||||
app.update(crate::app::Msg::GuidedReviewOpenPullRequest);
|
||||
let Ok(Action::PreparePullRequest { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
app.update(prepared_event(request_id, &[]));
|
||||
let shift = |character| {
|
||||
crate::app::Msg::Key(crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Char(character),
|
||||
crossterm::event::KeyModifiers::SHIFT,
|
||||
))
|
||||
};
|
||||
app.update(shift('E'));
|
||||
let edit = app.outbox.text_edit.take().expect("an edit for the main loop");
|
||||
assert_eq!(edit.text, "### Sum every element\n\nWhy.\n\nCloses #7");
|
||||
assert_eq!(edit.target, crate::launcher::EditTarget::PullRequestBody);
|
||||
|
||||
app.update(crate::app::Msg::TextEdited {
|
||||
target: crate::launcher::EditTarget::PullRequestBody,
|
||||
text: "Rewritten at length.".into(),
|
||||
});
|
||||
let opening = app.guided_review_workspace.pull_request_opening.as_ref().expect("preview");
|
||||
assert_eq!(opening.prepared.as_ref().unwrap().pull_request.body, "Rewritten at length.");
|
||||
|
||||
// While a field is open its keys are its own: E is a letter there
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
app.update(shift('E'));
|
||||
assert!(app.outbox.text_edit.is_none(), "typed, not handed off");
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
assert!(matches!(engine_rx.try_recv(), Ok(Action::OpenPullRequest { .. })));
|
||||
app.update(crate::app::Msg::TextEdited {
|
||||
target: crate::launcher::EditTarget::PullRequestBody,
|
||||
text: "Too late.".into(),
|
||||
});
|
||||
let opening = app.guided_review_workspace.pull_request_opening.as_ref().expect("preview");
|
||||
assert_eq!(opening.prepared.as_ref().unwrap().pull_request.body, "Rewritten at length.");
|
||||
}
|
||||
|
||||
/// With nothing to commit, nothing is; a failure keeps the preview open saying why, an answer for
|
||||
/// an attempt no longer waiting is ignored, and an empty title is refused.
|
||||
#[test]
|
||||
fn a_failed_opening_says_why_and_a_stale_answer_is_ignored() {
|
||||
let (mut app, mut engine_rx) = branch_review(luxe_core::workspace::PullRequestPresence::None);
|
||||
app.update(crate::app::Msg::GuidedReviewOpenPullRequest);
|
||||
let Ok(Action::PreparePullRequest { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
app.update(prepared_event(luxe_core::guided_review::PullRequestOpenId::new(), &[]));
|
||||
assert!(
|
||||
app.guided_review_workspace.pull_request_opening.as_ref().unwrap().prepared.is_none(),
|
||||
"not the attempt it waits on"
|
||||
);
|
||||
app.update(prepared_event(request_id, &[]));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmPullRequest);
|
||||
let Ok(Action::OpenPullRequest { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected an open");
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestOpenFailed {
|
||||
request_id,
|
||||
message: "GitHub refused it: No commits between main and 7-fix".into(),
|
||||
}));
|
||||
let opening = app.guided_review_workspace.pull_request_opening.as_ref().expect("still open");
|
||||
assert!(!opening.opening);
|
||||
assert_eq!(
|
||||
opening.error.as_deref(),
|
||||
Some("GitHub refused it: No commits between main and 7-fix")
|
||||
);
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Char('t')));
|
||||
for _ in 0.."Fix the total".len() {
|
||||
app.update(key(crossterm::event::KeyCode::Backspace));
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmPullRequest);
|
||||
assert!(engine_rx.try_recv().is_err(), "no title, nothing opens");
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
assert!(app.guided_review_workspace.pull_request_opening.is_none(), "closes when idle");
|
||||
}
|
||||
|
||||
/// Someone else's pull request with three unsent comments, the post preview closed.
|
||||
pub(super) fn their_pull_request() -> (App, mpsc::Receiver<Action>) {
|
||||
let mut app =
|
||||
seeded_app("nord", FixtureScenario::GuidedReviewPullRequestPost).expect("fixture");
|
||||
app.guided_review_workspace.github_post = None;
|
||||
let (engine_tx, engine_rx) = mpsc::channel(8);
|
||||
app.engine_tx = engine_tx;
|
||||
(app, engine_rx)
|
||||
}
|
||||
|
||||
pub(super) fn fix_checked(
|
||||
number: u64,
|
||||
branch: Option<&str>,
|
||||
refusal: Option<&str>,
|
||||
) -> crate::app::Msg {
|
||||
crate::app::Msg::Engine(luxe_core::event::Event::PullRequestFixChecked {
|
||||
number,
|
||||
branch: branch.map(str::to_string),
|
||||
refusal: refusal.map(str::to_string),
|
||||
})
|
||||
}
|
||||
|
||||
/// Alt+U on someone else's pull request offers to fix it in a worktree instead of refusing, asks
|
||||
/// GitHub first, and on Enter leaves with the unsent comments — not one already posted.
|
||||
#[test]
|
||||
fn sending_to_the_agent_on_their_pull_request_offers_a_worktree() {
|
||||
let (mut app, mut engine_rx) = their_pull_request();
|
||||
let posted = luxe_core::guided_review::PostedComment { review_id: 9, url: String::new() };
|
||||
let session = app.review.session_mut().expect("session");
|
||||
session.findings[0].posted = Some(posted);
|
||||
let unsent: Vec<_> = session.findings[1..].iter().map(|f| f.id.clone()).collect();
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewOpenSendPreview);
|
||||
assert!(app.guided_review_workspace.send_preview.is_none(), "not the local send");
|
||||
let Ok(Action::CheckPullRequestFix { number, repository }) = engine_rx.try_recv() else {
|
||||
panic!("expected a check");
|
||||
};
|
||||
assert_eq!((number, repository), (42, None));
|
||||
let fix = app.guided_review_workspace.pull_request_fix.clone().expect("the offer");
|
||||
assert_eq!((fix.comments, fix.branch), (2, None));
|
||||
|
||||
// Nothing leaves before GitHub has answered, nor for another pull request's answer
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
app.update(fix_checked(7, Some("other"), None));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
assert!(app.outbox.pull_request_fix.is_none());
|
||||
|
||||
app.update(fix_checked(42, Some("fix-redirects"), None));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
let launch = app.outbox.pull_request_fix.clone().expect("leaving to fix it");
|
||||
assert_eq!(launch.number, 42);
|
||||
assert_eq!(launch.carried.iter().map(|f| f.id.clone()).collect::<Vec<_>>(), unsent);
|
||||
assert!(app.guided_review_workspace.pull_request_fix.is_none());
|
||||
|
||||
let mut exit = crate::main_loop::TuiExit::Quit;
|
||||
crate::main_loop::collect_exit_for_tests(&mut app, &mut exit);
|
||||
assert_eq!(exit, crate::main_loop::TuiExit::FixPullRequest(launch));
|
||||
}
|
||||
|
||||
/// From the post preview, `w` makes the same offer; a refusal says why and Enter does nothing.
|
||||
#[test]
|
||||
fn a_refused_fix_says_why_and_goes_nowhere() {
|
||||
let (mut app, mut engine_rx) = their_pull_request();
|
||||
// Read from another repository than the checkout's, which the engine has to be told
|
||||
app.guided_review.as_mut().expect("review").target =
|
||||
luxe_core::guided_review::ReviewTarget::PullRequest {
|
||||
number: 42,
|
||||
repository: Some("upstream/notify".into()),
|
||||
};
|
||||
app.update(crate::app::Msg::GuidedReviewOpenGithubPost);
|
||||
let _ = engine_rx.try_recv();
|
||||
app.update(key(crossterm::event::KeyCode::Char('w')));
|
||||
assert!(app.guided_review_workspace.github_post.is_none(), "the post preview gives way");
|
||||
let Ok(Action::CheckPullRequestFix { number: 42, repository }) = engine_rx.try_recv() else {
|
||||
panic!("expected a check");
|
||||
};
|
||||
assert_eq!(repository.as_deref(), Some("upstream/notify"));
|
||||
app.update(fix_checked(42, None, Some("The author did not allow edits by maintainers.")));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
assert!(app.outbox.pull_request_fix.is_none());
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
assert!(app.guided_review_workspace.pull_request_fix.is_none());
|
||||
}
|
||||
|
||||
/// With no engine to ask, `w` leaves the post preview where it was and says it could not ask,
|
||||
/// rather than closing it on nothing.
|
||||
#[test]
|
||||
fn a_fix_that_cannot_be_asked_about_leaves_the_post_preview() {
|
||||
let (mut app, mut engine_rx) = their_pull_request();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenGithubPost);
|
||||
let _ = engine_rx.try_recv();
|
||||
drop(engine_rx);
|
||||
app.update(key(crossterm::event::KeyCode::Char('w')));
|
||||
assert!(app.guided_review_workspace.github_post.is_some(), "the post preview stays");
|
||||
assert!(app.guided_review_workspace.pull_request_fix.is_none());
|
||||
assert_eq!(app.status.toast(), Some("Could not ask whether #42 can be fixed here"));
|
||||
}
|
||||
|
||||
/// A new session on the checked-out pull request opens its review, and the comments carried to
|
||||
/// it join that review once its session is here, and go to the agent in the same save.
|
||||
#[test]
|
||||
fn carried_comments_join_the_checked_out_review() {
|
||||
let (from, _) = their_pull_request();
|
||||
let carried = from.review.session().expect("session").findings.clone();
|
||||
let launch = crate::main_loop::FixLaunch { number: 42, carried: carried.clone() };
|
||||
|
||||
let (tx, mut engine_rx) = mpsc::channel(16);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.open_pull_request_fix(launch);
|
||||
let request_id = loop {
|
||||
match engine_rx.try_recv() {
|
||||
Ok(Action::LoadGuidedReview { request_id, target, .. }) => {
|
||||
assert_eq!(
|
||||
target,
|
||||
luxe_core::guided_review::ReviewTarget::OwnPullRequest { number: 42 }
|
||||
);
|
||||
break request_id;
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(error) => panic!("no review asked for: {error:?}"),
|
||||
}
|
||||
};
|
||||
let mut review = crate::fixture::fixture_pull_request_review();
|
||||
review.target = luxe_core::guided_review::ReviewTarget::OwnPullRequest { number: 42 };
|
||||
// Checked out, a pull request is reviewed from where it branched, like any branch
|
||||
review.source.base = luxe_core::guided_review::ReviewBase::MergeBase {
|
||||
reference: "main".into(),
|
||||
oid: "4b825dc642cb6eb9a060e54bf8d69288fbee4904".into(),
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GuidedReviewLoaded {
|
||||
request_id: request_id.clone(),
|
||||
review: Box::new(review),
|
||||
}));
|
||||
let bound = app.review.session.clone().expect("a session for the review");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ReviewSessionRestored {
|
||||
session: Box::new(bound.clone()),
|
||||
}));
|
||||
|
||||
let adopted =
|
||||
std::iter::from_fn(|| engine_rx.try_recv().ok()).find_map(|action| match action {
|
||||
Action::EditReview {
|
||||
request_id,
|
||||
edit: luxe_core::engine::ReviewEdit::AdoptCarried { findings, send },
|
||||
..
|
||||
} => Some((request_id, findings, send)),
|
||||
_ => None,
|
||||
});
|
||||
let (save, findings, send) = adopted.expect("the carried comments are sent to the desk");
|
||||
assert_eq!(findings, carried);
|
||||
assert!(send, "choosing to fix them was the instruction");
|
||||
assert!(app.carried_findings.is_none(), "adopted once");
|
||||
|
||||
// The desk adopts them and queues the unsent ones in the same save
|
||||
let mut stored = bound;
|
||||
stored.adopt_carried_findings(carried.clone(), |_| {
|
||||
luxe_core::guided_review::FindingAnchorRefresh::Exact
|
||||
});
|
||||
let unsent = stored.unsent_finding_ids();
|
||||
stored
|
||||
.queue_submission(
|
||||
luxe_core::guided_review::SubmissionId::new(),
|
||||
luxe_core::guided_review::ReviewFeedbackMode::RequestFixes,
|
||||
&unsent,
|
||||
&[],
|
||||
0,
|
||||
)
|
||||
.expect("queued");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ReviewSessionSaved {
|
||||
request_id: save,
|
||||
session: Box::new(stored),
|
||||
}));
|
||||
|
||||
// The agent is at work on them, so the transcript stays up and the review waits on Ctrl+G
|
||||
assert!(!app.review.open_when_ready);
|
||||
let review = app.guided_review.clone().expect("loaded");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GuidedReviewGuideUpdated {
|
||||
request_id,
|
||||
review_id: review.id.clone(),
|
||||
revision_id: review.revision_id.clone(),
|
||||
chapters: review.chapters.clone(),
|
||||
provenance: luxe_core::guided_review::GuideProvenance::Model { batches: 1 },
|
||||
brief: None,
|
||||
}));
|
||||
assert_ne!(app.current_view, crate::app::ViewMode::GuidedReview);
|
||||
assert_eq!(
|
||||
app.status.toast(),
|
||||
Some("Your comments went to the agent · ctrl+g opens the review")
|
||||
);
|
||||
}
|
||||
|
||||
/// Carried comments wait for their own pull request's review, not whichever loads first.
|
||||
#[test]
|
||||
fn carried_comments_wait_for_their_own_pull_request() {
|
||||
let (from, _) = their_pull_request();
|
||||
let carried = from.review.session().expect("session").findings.clone();
|
||||
let (tx, mut engine_rx) = mpsc::channel(16);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let ids: Vec<_> = carried.iter().map(|finding| finding.id.clone()).collect();
|
||||
app.open_pull_request_fix(crate::main_loop::FixLaunch { number: 7, carried });
|
||||
let request_id = std::iter::from_fn(|| engine_rx.try_recv().ok())
|
||||
.find_map(|action| match action {
|
||||
Action::LoadGuidedReview { request_id, .. } => Some(request_id),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a review asked for");
|
||||
let mut review = crate::fixture::fixture_pull_request_review();
|
||||
review.target = luxe_core::guided_review::ReviewTarget::OwnPullRequest { number: 42 };
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GuidedReviewLoaded {
|
||||
request_id,
|
||||
review: Box::new(review),
|
||||
}));
|
||||
let session = app.review.session.clone().expect("the review's own session");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ReviewSessionRestored {
|
||||
session: Box::new(session.clone()),
|
||||
}));
|
||||
assert!(app.carried_findings.is_some(), "still waiting for #7");
|
||||
assert!(session.findings.iter().all(|finding| !ids.contains(&finding.id)), "none adopted");
|
||||
assert!(
|
||||
std::iter::from_fn(|| engine_rx.try_recv().ok())
|
||||
.all(|action| !matches!(action, Action::EditReview { .. })),
|
||||
"nothing is sent"
|
||||
);
|
||||
}
|
||||
|
||||
/// Checked out with no comments to carry, nothing is sent to the agent.
|
||||
#[test]
|
||||
fn a_fix_with_no_comments_says_nothing_came() {
|
||||
let (tx, mut engine_rx) = mpsc::channel(16);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.open_pull_request_fix(crate::main_loop::FixLaunch { number: 42, carried: Vec::new() });
|
||||
let request_id = std::iter::from_fn(|| engine_rx.try_recv().ok())
|
||||
.find_map(|action| match action {
|
||||
Action::LoadGuidedReview { request_id, .. } => Some(request_id),
|
||||
_ => None,
|
||||
})
|
||||
.expect("a review asked for");
|
||||
let mut review = crate::fixture::fixture_pull_request_review();
|
||||
review.target = luxe_core::guided_review::ReviewTarget::OwnPullRequest { number: 42 };
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GuidedReviewLoaded {
|
||||
request_id,
|
||||
review: Box::new(review),
|
||||
}));
|
||||
let session = app.review.session.clone().expect("the review's own session");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::ReviewSessionRestored {
|
||||
session: Box::new(session),
|
||||
}));
|
||||
assert!(app.carried_findings.is_none());
|
||||
assert!(
|
||||
std::iter::from_fn(|| engine_rx.try_recv().ok())
|
||||
.all(|action| !matches!(action, Action::EditReview { .. })),
|
||||
"nothing to send"
|
||||
);
|
||||
}
|
||||
|
||||
/// A branch's review with two chapters worth a pull request each.
|
||||
pub(super) fn two_chapter_review() -> (App, mpsc::Receiver<Action>) {
|
||||
let (mut app, engine_rx) = branch_review(luxe_core::workspace::PullRequestPresence::None);
|
||||
let review = app.guided_review.as_mut().expect("review");
|
||||
let mut second = review.chapters[0].clone();
|
||||
second.title = "Cover the edge".into();
|
||||
second.kind = luxe_core::guided_review::ChapterKind::Test;
|
||||
review.chapters.push(second);
|
||||
(app, engine_rx)
|
||||
}
|
||||
|
||||
pub(super) fn layer(head: &str, base: &str, title: &str) -> luxe_core::github::NewPullRequest {
|
||||
luxe_core::github::NewPullRequest {
|
||||
head: head.into(),
|
||||
base: base.into(),
|
||||
title: title.into(),
|
||||
body: String::new(),
|
||||
draft: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Offered beside a single pull request when there are two chapters to split, not with one; the
|
||||
/// preview opens exactly its layers, drafts when asked.
|
||||
#[test]
|
||||
fn a_review_with_two_chapters_opens_as_a_stack_as_shown() {
|
||||
use crate::guided_review::FinishReviewChoice;
|
||||
let (mut one, _) = branch_review(luxe_core::workspace::PullRequestPresence::None);
|
||||
assert!(dispatch_action(&mut one, UiAction::ReviewFinish));
|
||||
assert!(!one.guided_review_workspace.finish_offers_stack, "one chapter: one pull request");
|
||||
|
||||
let (mut app, mut engine_rx) = two_chapter_review();
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFinish));
|
||||
assert!(app.guided_review_workspace.finish_offers_stack);
|
||||
while app.guided_review_workspace.finish_review_choice != Some(FinishReviewChoice::OpenStack) {
|
||||
app.guided_review_workspace.move_finish_review_choice(true);
|
||||
}
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
let Ok(Action::PrepareStack { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
let layers = vec![layer("fix-part-1", "main", "Sum"), layer("fix", "fix-part-1", "Cover")];
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::StackPrepared {
|
||||
request_id: luxe_core::guided_review::PullRequestOpenId::new(),
|
||||
layers: Some(Vec::new()),
|
||||
refusal: None,
|
||||
}));
|
||||
assert!(app.guided_review_workspace.stack_opening.as_ref().unwrap().layers.is_none(), "stale");
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::StackPrepared {
|
||||
request_id,
|
||||
layers: Some(layers.clone()),
|
||||
refusal: None,
|
||||
}));
|
||||
app.update(key(crossterm::event::KeyCode::Char('d')));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
// The engine kept the layers; whether they are drafts is the reader's one choice
|
||||
let Ok(Action::OpenStack { request_id, draft }) = engine_rx.try_recv() else {
|
||||
panic!("expected an open");
|
||||
};
|
||||
assert!(draft, "d made them drafts");
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
assert!(app.guided_review_workspace.stack_opening.is_some(), "not closed mid-open");
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::StackOpened {
|
||||
request_id,
|
||||
numbers: vec![170, 171],
|
||||
urls: vec!["u170".into(), "u171".into()],
|
||||
failed: None,
|
||||
}));
|
||||
assert!(app.guided_review_workspace.stack_opening.is_none());
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.posted_review_url.as_deref(),
|
||||
Some("u171"),
|
||||
"o: the top"
|
||||
);
|
||||
assert!(app.convo.iter().any(|item| matches!(item.block(), ConvoBlock::System(text)
|
||||
if text.ends_with("opened it as a stack of 2: #170, #171"))));
|
||||
}
|
||||
|
||||
/// When the stack stops partway, the preview says which opened and offers nothing to open again.
|
||||
#[test]
|
||||
fn a_stack_that_stopped_partway_says_what_opened() {
|
||||
let (mut app, mut engine_rx) = two_chapter_review();
|
||||
app.update(crate::app::Msg::GuidedReviewOpenStack);
|
||||
let Ok(Action::PrepareStack { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected a prepare");
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::StackPrepared {
|
||||
request_id,
|
||||
layers: Some(vec![layer("a", "main", "A"), layer("b", "a", "B")]),
|
||||
refusal: None,
|
||||
}));
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmStack);
|
||||
let Ok(Action::OpenStack { request_id, .. }) = engine_rx.try_recv() else {
|
||||
panic!("expected an open");
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::StackOpened {
|
||||
request_id,
|
||||
numbers: vec![170],
|
||||
urls: vec!["u170".into()],
|
||||
failed: Some(
|
||||
"`b` was pushed, but its pull request did not open: GitHub refused it.".into(),
|
||||
),
|
||||
}));
|
||||
let stack = app.guided_review_workspace.stack_opening.as_ref().expect("still open");
|
||||
assert!(!stack.opening && stack.layers.is_none());
|
||||
assert!(stack.error.as_deref().unwrap().ends_with("Opened so far: #170."), "{:?}", stack.error);
|
||||
app.update(crate::app::Msg::GuidedReviewConfirmStack);
|
||||
assert!(engine_rx.try_recv().is_err(), "nothing opens twice");
|
||||
app.update(key(crossterm::event::KeyCode::Esc));
|
||||
assert!(app.guided_review_workspace.stack_opening.is_none(), "closes when idle");
|
||||
}
|
||||
484
crates/luxe-tui/src/app/commands/tests/palette.rs
Normal file
484
crates/luxe-tui/src/app/commands/tests/palette.rs
Normal file
@@ -0,0 +1,484 @@
|
||||
//! Palette — the command list, what it promises, and what refuses to run.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A place a palette opens, named, and how to build an app standing there.
|
||||
pub(super) type Place = (&'static str, fn() -> App);
|
||||
|
||||
/// The places a palette opens, built the way a reader gets there.
|
||||
pub(super) fn places() -> Vec<Place> {
|
||||
fn fresh() -> App {
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
App::new(tx, KeyMap::defaults(), Config::default())
|
||||
}
|
||||
fn seeded(scenario: FixtureScenario) -> App {
|
||||
let mut app = seeded_app("nord", scenario).expect("fixture app");
|
||||
// Room for everything a command may send, so a full channel cannot pass for a refusal
|
||||
let (tx, rx) = mpsc::channel(64);
|
||||
std::mem::forget(rx);
|
||||
app.engine_tx = tx;
|
||||
app
|
||||
}
|
||||
vec![
|
||||
("a fresh session", fresh),
|
||||
("a conversation", || seeded(FixtureScenario::ChatIdle)),
|
||||
("a conversation with an image", || seeded(FixtureScenario::ChatScreenshot)),
|
||||
("messages waiting", || seeded(FixtureScenario::ChatPending)),
|
||||
("the preview", || seeded(FixtureScenario::ChangesWide)),
|
||||
("a review", || seeded(FixtureScenario::GuidedReviewReady)),
|
||||
("a pull request's review", || seeded(FixtureScenario::GuidedReviewPullRequest)),
|
||||
]
|
||||
}
|
||||
|
||||
/// Every command a menu lists is one its dispatch handles, wherever it is listed.
|
||||
///
|
||||
/// The palette used to list 36 commands an idle session could not run, and picking one closed it
|
||||
/// on nothing. A command cannot be added to the list now without being wired where it is listed:
|
||||
/// each place builds the app fresh for each action, so one command's effect cannot mask another's.
|
||||
#[test]
|
||||
fn every_listed_command_runs_where_it_is_listed() {
|
||||
let mut listed_anywhere = std::collections::HashSet::new();
|
||||
for (place, build) in places() {
|
||||
let menu = command_menu(&build());
|
||||
assert!(!menu.entries.is_empty(), "{place} lists nothing");
|
||||
for entry in menu.entries {
|
||||
listed_anywhere.insert(entry.command.id.to_string());
|
||||
if let crate::commands::CommandKind::Action(action) = entry.command.kind {
|
||||
let mut app = build();
|
||||
assert!(
|
||||
dispatch_action(&mut app, action),
|
||||
"{place} lists {:?}, and running it does nothing",
|
||||
entry.command.name
|
||||
);
|
||||
// What would leave Luxe is recorded, never launched: this loop runs every command
|
||||
// on every run of the suite, and it once opened a browser tab each time
|
||||
let crate::app::ExternalOpener::Recorded(opened) = &app.opener else {
|
||||
panic!("{place}: a test app must not be able to launch anything");
|
||||
};
|
||||
if action == UiAction::ReviewOpenInBrowser {
|
||||
assert_eq!(opened.len(), 1, "{place}: Open on GitHub asks to open one page");
|
||||
assert!(opened[0].contains("/pull/"), "{place}: {opened:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for command in crate::commands::CommandRegistry::all().iter() {
|
||||
assert!(
|
||||
listed_anywhere.contains(command.id.as_ref()),
|
||||
"{:?} is listed nowhere a reader can reach",
|
||||
command.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The places report themselves the way the list needs them to.
|
||||
#[test]
|
||||
fn each_place_reports_what_it_offers() {
|
||||
use crate::commands::Surface;
|
||||
let context_of = |scenario| command_context(&seeded_app("nord", scenario).expect("fixture"));
|
||||
let fresh = {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
command_context(&App::new(tx, KeyMap::defaults(), Config::default()))
|
||||
};
|
||||
assert_eq!(fresh, crate::commands::CommandContext::default(), "a fresh session offers nothing");
|
||||
assert!(context_of(FixtureScenario::ChatIdle).has_turn);
|
||||
assert!(context_of(FixtureScenario::ChatScreenshot).has_image);
|
||||
assert!(context_of(FixtureScenario::ChatPending).messages_waiting);
|
||||
assert!(context_of(FixtureScenario::ChangesWide).changes_pane);
|
||||
assert_eq!(context_of(FixtureScenario::GuidedReviewReady).surface, Surface::Review);
|
||||
assert!(!context_of(FixtureScenario::GuidedReviewReady).pull_request_review);
|
||||
assert!(context_of(FixtureScenario::GuidedReviewPullRequest).pull_request_review);
|
||||
}
|
||||
|
||||
pub(super) fn command(slash_or_id: &str) -> crate::commands::Command {
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
registry
|
||||
.parse_slash(slash_or_id)
|
||||
.or_else(|| registry.iter().find(|command| command.id == slash_or_id).cloned())
|
||||
.unwrap_or_else(|| panic!("{slash_or_id} is a command"))
|
||||
}
|
||||
|
||||
pub(super) fn toast(app: &App) -> Option<&str> {
|
||||
app.status.toast.as_ref().map(|(said, _)| said.as_str())
|
||||
}
|
||||
|
||||
/// A command that cannot run here says what it needs, runs nothing, and is not remembered as
|
||||
/// used; one that ran leads the next menu.
|
||||
#[test]
|
||||
fn a_command_that_cannot_run_says_why_and_one_that_ran_is_remembered() {
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
|
||||
dispatch(&mut app, command("/pr"));
|
||||
assert_eq!(toast(&app), Some("Pull request needs a git checkout"));
|
||||
assert!(rx.try_recv().is_err(), "nothing was asked of the engine");
|
||||
assert!(app.recent_commands.ids().is_empty(), "a refusal is not a use");
|
||||
|
||||
dispatch(&mut app, command("tui.preview.toggle_word_wrap"));
|
||||
assert_eq!(toast(&app), Some("Wrap long lines needs the preview open"));
|
||||
|
||||
dispatch(&mut app, command("/theme"));
|
||||
assert!(app.overlays.theme_picker.is_some());
|
||||
dispatch(&mut app, command("/cost"));
|
||||
assert_eq!(app.recent_commands.ids(), ["cmd.cost", "cmd.theme"]);
|
||||
let menu = command_menu(&app);
|
||||
assert_eq!(menu.recent, 2);
|
||||
assert_eq!(menu.entries[0].command.name, "Session cost");
|
||||
}
|
||||
|
||||
/// The safety net under the list: an action that refuses when it is run says so, rather than
|
||||
/// closing the palette on nothing.
|
||||
#[test]
|
||||
fn an_action_that_refuses_says_so() {
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let mut motion = command("tui.review.finish");
|
||||
motion.needs = std::borrow::Cow::Borrowed(&[]);
|
||||
dispatch(&mut app, motion);
|
||||
assert_eq!(toast(&app), Some("Finish review did nothing here"));
|
||||
assert!(app.recent_commands.ids().is_empty());
|
||||
}
|
||||
|
||||
/// `/help` is the key card: the chat's in the conversation, the review's in a review. Esc or a
|
||||
/// click puts the chat's away, it swallows what is typed or pasted while it is up, and a key
|
||||
/// someone binds to help opens and closes it too.
|
||||
#[test]
|
||||
fn help_opens_the_key_card_for_what_is_on_screen() {
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let keymap = KeyMap::defaults().with_overrides(std::collections::HashMap::from([(
|
||||
"tui.app.toggle_help".to_string(),
|
||||
vec!["f1".to_string()],
|
||||
)]));
|
||||
let mut app = App::new(tx, keymap, Config::default());
|
||||
|
||||
dispatch(&mut app, command("/help"));
|
||||
assert!(app.overlays.keys_card);
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)));
|
||||
app.update(crate::app::Msg::PasteText("sk-not-a-real-key".into()));
|
||||
assert!(app.overlays.keys_card, "a stray key does not close it");
|
||||
assert_eq!(app.editor.current_input(), "", "and nothing reaches the composer behind it");
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)));
|
||||
assert!(!app.overlays.keys_card);
|
||||
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::F(1), KeyModifiers::NONE)));
|
||||
assert!(app.overlays.keys_card, "a bound help key opens it");
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::F(1), KeyModifiers::NONE)));
|
||||
assert!(!app.overlays.keys_card, "and closes it");
|
||||
|
||||
app.overlays.keys_card = true;
|
||||
let click = crossterm::event::MouseEvent {
|
||||
kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
|
||||
column: 0,
|
||||
row: 0,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
};
|
||||
if let crate::main_loop::RouteAction::Msg(message) =
|
||||
crate::main_loop::route_mouse(&mut app, &click)
|
||||
{
|
||||
app.update(*message);
|
||||
}
|
||||
assert!(!app.overlays.keys_card, "a click puts it away");
|
||||
|
||||
let mut review = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
dispatch(&mut review, command("cmd.help"));
|
||||
assert!(!review.overlays.keys_card, "a review has its own card");
|
||||
assert!(review.guided_review_workspace.help_visible);
|
||||
}
|
||||
|
||||
/// The ten commands the old `/help` text never mentioned are what motivated generating help from
|
||||
/// the registry. It is a card of keys now, and the text that drifted is gone.
|
||||
#[test]
|
||||
fn help_is_no_longer_a_hand_written_list() {
|
||||
let (tx, _rx) = mpsc::channel(8);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
dispatch(&mut app, command("/help"));
|
||||
assert!(
|
||||
!app.convo.iter().any(|item| matches!(
|
||||
item.block(),
|
||||
ConvoBlock::System(text) if text.contains("Available commands")
|
||||
)),
|
||||
"no hand-written command list lands in the transcript"
|
||||
);
|
||||
}
|
||||
|
||||
/// Bare `/diff` is the same verb as its key: it opens the review already pinned rather than
|
||||
/// creating another, which is what `Ctrl+G` does and what one row for both has to mean.
|
||||
#[test]
|
||||
fn bare_diff_opens_the_pinned_review_like_its_key() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let (tx, mut rx) = mpsc::channel(8);
|
||||
app.engine_tx = tx;
|
||||
crate::app::navigation::exit_guided_review(&mut app);
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
// Leaving records what was read; what matters below is what `/diff` sends
|
||||
while rx.try_recv().is_ok() {}
|
||||
|
||||
dispatch(&mut app, command("/diff"));
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::GuidedReview, "straight back to it");
|
||||
assert!(rx.try_recv().is_err(), "without taking another");
|
||||
}
|
||||
|
||||
/// The palette opens from anywhere, a review included, and draws there.
|
||||
///
|
||||
/// The review claims every key it does not know so nothing reaches the composer hidden behind it,
|
||||
/// and that swallowed `Ctrl+K`; the view also returned before drawing any overlay. So the review's
|
||||
/// own commands were listed and could not be reached.
|
||||
#[test]
|
||||
fn the_palette_opens_and_draws_in_a_review() {
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
use ratatui::{backend::TestBackend, Terminal};
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Char('k'), KeyModifiers::CONTROL)));
|
||||
assert!(app.overlays.palette.is_some(), "ctrl+k opens it over the review");
|
||||
|
||||
let mut terminal = Terminal::new(TestBackend::new(140, 40)).expect("terminal");
|
||||
terminal.draw(|frame| crate::view::render(frame, &mut app)).expect("draw");
|
||||
let buffer = terminal.backend().buffer().clone();
|
||||
let text: String = (0..40)
|
||||
.map(|y| (0..140).map(|x| buffer[(x, y)].symbol()).collect::<String>() + "\n")
|
||||
.collect();
|
||||
assert!(text.contains("Command palette"), "and draws there");
|
||||
assert!(text.contains("Finish review"), "listing the review's commands: {text}");
|
||||
|
||||
for character in "finish".chars() {
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(
|
||||
KeyCode::Char(character),
|
||||
KeyModifiers::NONE,
|
||||
)));
|
||||
}
|
||||
assert_eq!(app.overlays.palette.as_ref().map(|palette| palette.query()), Some("finish"));
|
||||
app.update(crate::app::Msg::Key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)));
|
||||
assert!(app.overlays.palette.is_none());
|
||||
assert!(
|
||||
app.guided_review_workspace.finish_review_choice.is_some()
|
||||
|| app.guided_review_workspace.github_post.is_some(),
|
||||
"and runs what it picks"
|
||||
);
|
||||
}
|
||||
|
||||
/// An app nobody installed the desktop opener into cannot start a browser or a viewer, whatever
|
||||
/// asks it to: it records the request instead, which is also what lets a test check one was made.
|
||||
#[test]
|
||||
fn an_app_opens_nothing_outside_luxe_unless_a_launch_says_so() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
assert_eq!(app.opener, crate::app::ExternalOpener::Recorded(Vec::new()));
|
||||
app.open_externally(std::ffi::OsStr::new("https://example.test/pull/1"), "the page");
|
||||
assert_eq!(app.opener, crate::app::ExternalOpener::Recorded(vec!["the page".into()]));
|
||||
assert!(app.convo.is_empty(), "nothing failed, so nothing is said");
|
||||
}
|
||||
|
||||
/// The round trip in `/pr`'s Conversation: the tab asks for it, `r` writes a reply in the thread,
|
||||
/// Enter sends it, and what lands closes the card and asks for the conversation again to show it.
|
||||
#[test]
|
||||
fn a_reply_written_in_pr_is_posted_and_the_conversation_read_again() {
|
||||
use luxe_core::github::overview::{ConversationEntry, Overview};
|
||||
use luxe_core::github::{ReviewThread, ThreadComment, ThreadSide};
|
||||
use luxe_core::workspace::PullRequestPresence;
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
let mut app = seeded_app("nord", FixtureScenario::DockWide).expect("fixture app");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(16);
|
||||
app.engine_tx = engine_tx;
|
||||
let status = luxe_core::github::PullRequestStatus {
|
||||
number: 146,
|
||||
title: "Round trip".into(),
|
||||
url: "https://github.com/acme/app/pull/146".into(),
|
||||
state: luxe_core::github::PullRequestState::Open,
|
||||
draft: false,
|
||||
review_decision: None,
|
||||
checks: luxe_core::github::CheckRollup::default(),
|
||||
unresolved_threads: 1,
|
||||
head_oid: "f6195af".into(),
|
||||
stack: None,
|
||||
};
|
||||
app.workspace.as_mut().expect("workspace").pull_request = PullRequestPresence::Found(status);
|
||||
run(&mut app, ®istry.parse_slash("/pr").expect("/pr parses"));
|
||||
let overview = luxe_core::github::overview::PullRequestOverview {
|
||||
number: 146,
|
||||
..crate::fixture::pull_request_overview()
|
||||
};
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GithubOverviewRead {
|
||||
repository: None,
|
||||
number: 146,
|
||||
overview: Some(Overview::PullRequest(Box::new(overview))),
|
||||
error: None,
|
||||
local: None,
|
||||
}));
|
||||
let drain = |rx: &mut mpsc::Receiver<Action>| {
|
||||
std::iter::from_fn(|| rx.try_recv().ok()).collect::<Vec<_>>()
|
||||
};
|
||||
drain(&mut engine_rx);
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Tab));
|
||||
assert!(drain(&mut engine_rx).iter().any(|action| matches!(
|
||||
action,
|
||||
Action::ReadGithubConversation { repository: None, number: 146, pull_request: true }
|
||||
)));
|
||||
let thread = ConversationEntry::Thread(ReviewThread {
|
||||
id: "PRRT_9".into(),
|
||||
path: "src/lib.rs".into(),
|
||||
line: Some(3),
|
||||
start_line: None,
|
||||
side: ThreadSide::Right,
|
||||
outdated: false,
|
||||
resolved: false,
|
||||
file_level: false,
|
||||
comments: vec![ThreadComment {
|
||||
author: "jon".into(),
|
||||
body: "Why twice?".into(),
|
||||
created_at: String::new(),
|
||||
url: String::new(),
|
||||
}],
|
||||
total_comments: 1,
|
||||
anchor_text: None,
|
||||
can_reply: true,
|
||||
can_resolve: true,
|
||||
});
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GithubConversationRead {
|
||||
repository: None,
|
||||
number: 146,
|
||||
entries: Some(vec![thread]),
|
||||
error: None,
|
||||
}));
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Char('r')));
|
||||
for character in "Once now.".chars() {
|
||||
app.update(key(crossterm::event::KeyCode::Char(character)));
|
||||
}
|
||||
app.update(crate::app::Msg::Key(crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
)));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
let sent = drain(&mut engine_rx);
|
||||
let posted = sent.iter().find_map(|action| match action {
|
||||
Action::PostGithubComment(post) => Some(post.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(
|
||||
posted,
|
||||
Some(luxe_core::engine::GithubPost {
|
||||
repository: None,
|
||||
number: 146,
|
||||
thread: Some("PRRT_9".into()),
|
||||
answering: Some("Why twice?".into()),
|
||||
body: "Once now.".into(),
|
||||
})
|
||||
);
|
||||
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::GithubCommentPosted {
|
||||
repository: None,
|
||||
number: 146,
|
||||
thread: Some("PRRT_9".into()),
|
||||
url: Some("https://github.com/acme/app/pull/146#discussion_r9".into()),
|
||||
error: None,
|
||||
}));
|
||||
let card = app.overlays.pull_request_card.as_ref().expect("the card stays");
|
||||
let crate::github_detail::CardState::Ready(detail) = &card.state else { panic!("ready") };
|
||||
assert!(detail.composing.is_none(), "the draft card closed");
|
||||
assert!(
|
||||
drain(&mut engine_rx)
|
||||
.iter()
|
||||
.any(|action| matches!(action, Action::ReadGithubConversation { number: 146, .. })),
|
||||
"read again to show what was posted"
|
||||
);
|
||||
}
|
||||
|
||||
/// `/pr` with a card on the branch's own pull request, its overview `overview`.
|
||||
pub(super) fn pr_card(
|
||||
overview: luxe_core::github::overview::PullRequestOverview,
|
||||
) -> (App, mpsc::Receiver<Action>) {
|
||||
let mut app = seeded_app("nord", FixtureScenario::DockWide).expect("fixture app");
|
||||
let (engine_tx, engine_rx) = mpsc::channel(32);
|
||||
app.engine_tx = engine_tx;
|
||||
let mut card = crate::github_detail::PullRequestCard::reading(overview.number, None);
|
||||
card.land(Some(luxe_core::github::overview::Overview::PullRequest(Box::new(overview))), None);
|
||||
app.overlays.pull_request_card = Some(card);
|
||||
(app, engine_rx)
|
||||
}
|
||||
|
||||
/// `f` on failing checks writes the request into the composer, naming them, and leaves the card:
|
||||
/// what the agent is asked is still the reader's to send.
|
||||
#[test]
|
||||
fn fix_with_agent_writes_the_request_for_the_reader_to_send() {
|
||||
let (mut app, mut engine_rx) = pr_card(crate::fixture::pull_request_overview());
|
||||
app.update(key(crossterm::event::KeyCode::Char('f')));
|
||||
assert!(app.overlays.pull_request_card.is_none());
|
||||
assert!(app.editor.current_input().contains("failing checks on pull request #142"));
|
||||
assert!(
|
||||
!std::iter::from_fn(|| engine_rx.try_recv().ok())
|
||||
.any(|action| matches!(action, Action::SubmitUserMessage { .. })),
|
||||
"nothing is sent on the reader's behalf"
|
||||
);
|
||||
}
|
||||
|
||||
/// Enter on Ready opens the confirmation; Enter there sends exactly the merge left — the method
|
||||
/// first in GitHub's order, the head read, the branch to delete. A refusal shows in the confirmation;
|
||||
/// a merge that lands closes it and reads the overview and the workspace again.
|
||||
#[test]
|
||||
fn a_merge_is_confirmed_sent_as_left_and_its_answer_lands() {
|
||||
use luxe_core::engine::{PullRequestChange, PullRequestWrite};
|
||||
use luxe_core::github::overview::{MergeMethod, MergeRequest, MergeStatus};
|
||||
use luxe_core::github::{CheckRollup, ReviewDecision};
|
||||
let ready = luxe_core::github::overview::PullRequestOverview {
|
||||
merge_status: MergeStatus::Clean,
|
||||
review_decision: Some(ReviewDecision::Approved),
|
||||
reviewers: Vec::new(),
|
||||
checks: CheckRollup { passed: 12, ..CheckRollup::default() },
|
||||
failing: Vec::new(),
|
||||
unresolved_threads: 0,
|
||||
merge_methods: vec![MergeMethod::Squash, MergeMethod::Merge],
|
||||
..crate::fixture::pull_request_overview()
|
||||
};
|
||||
let (mut app, mut engine_rx) = pr_card(ready.clone());
|
||||
let drain = |rx: &mut mpsc::Receiver<Action>| {
|
||||
std::iter::from_fn(|| rx.try_recv().ok()).collect::<Vec<_>>()
|
||||
};
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
let sent = drain(&mut engine_rx);
|
||||
let asked = sent.iter().find_map(|action| match action {
|
||||
Action::ChangePullRequest {
|
||||
number: 142, write: PullRequestWrite::Merge(request), ..
|
||||
} => Some(request.clone()),
|
||||
_ => None,
|
||||
});
|
||||
assert_eq!(
|
||||
asked,
|
||||
Some(MergeRequest {
|
||||
method: MergeMethod::Merge,
|
||||
head_oid: ready.head_oid.clone(),
|
||||
delete_branch: Some("digest-routing".into()),
|
||||
})
|
||||
);
|
||||
|
||||
let refused =
|
||||
"GitHub refused the merge: Head branch was modified. Review and try the merge again.";
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestChanged {
|
||||
repository: None,
|
||||
number: 142,
|
||||
change: None,
|
||||
error: Some(refused.into()),
|
||||
}));
|
||||
let dialog = |app: &App| match app.overlays.pull_request_card.as_ref().map(|card| &card.state) {
|
||||
Some(crate::github_detail::CardState::Ready(detail)) => detail.merging.clone(),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(dialog(&app).and_then(|d| d.error), Some(refused.to_string()));
|
||||
|
||||
app.update(key(crossterm::event::KeyCode::Enter));
|
||||
drain(&mut engine_rx);
|
||||
app.update(crate::app::Msg::Engine(luxe_core::event::Event::PullRequestChanged {
|
||||
repository: None,
|
||||
number: 142,
|
||||
change: Some(PullRequestChange::Merged { sha: "abc".into(), branch_deleted: true }),
|
||||
error: None,
|
||||
}));
|
||||
assert!(dialog(&app).is_none(), "the confirmation closed");
|
||||
let after = drain(&mut engine_rx);
|
||||
assert!(after
|
||||
.iter()
|
||||
.any(|action| matches!(action, Action::ReadGithubOverview { number: 142, .. })));
|
||||
assert!(after.iter().any(|action| matches!(action, Action::RefreshWorkspace)));
|
||||
}
|
||||
624
crates/luxe-tui/src/app/commands/tests/review_target.rs
Normal file
624
crates/luxe-tui/src/app/commands/tests/review_target.rs
Normal file
@@ -0,0 +1,624 @@
|
||||
//! Review targets — which review a command asks for, and the keys inside it.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Ctrl+G asks for a review; it does not arrive on one.
|
||||
///
|
||||
/// The chord used to switch surface immediately and leave the reader watching a capture that had
|
||||
/// not finished — and then a guide rewriting the prose under them. It now starts the work and says
|
||||
/// so in the tray; a second press, once that row offers, is what opens it.
|
||||
#[test]
|
||||
fn ctrl_g_asks_for_a_review_and_a_second_press_opens_the_ready_one() {
|
||||
use luxe_core::keymap::KeyName;
|
||||
// The confirmed default chord: Ctrl+G opens Guided Review.
|
||||
assert_eq!(
|
||||
KeyMap::defaults().resolve(true, false, false, &KeyName::Char('g')),
|
||||
Some(UiAction::ReviewOpen)
|
||||
);
|
||||
|
||||
// The receiver is kept alive: a dropped one turns the capture request into "engine
|
||||
// unavailable" and the tray row is cleared, which is right and is not what this is about.
|
||||
let (mut app, _engine_rx) =
|
||||
crate::fixture::seeded_session("nord", FixtureScenario::ChatIdle).expect("chat fixture");
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewOpen));
|
||||
assert_eq!(
|
||||
app.current_view,
|
||||
crate::app::ViewMode::Chat,
|
||||
"the conversation is where the waiting is visible"
|
||||
);
|
||||
assert_eq!(
|
||||
app.review.queued.as_ref().map(|queued| queued.state),
|
||||
Some(crate::app::QueuedReviewState::Capturing)
|
||||
);
|
||||
|
||||
app.review.queued.as_mut().expect("queued").state = crate::app::QueuedReviewState::Ready;
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewOpen));
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::GuidedReview, "and now it opens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_target_parser_accepts_only_bounded_source_forms() {
|
||||
assert_eq!(parse_review_target(None, None), Ok(ReviewTarget::WorkingTree));
|
||||
assert_eq!(
|
||||
parse_review_target(Some("base origin/main"), None),
|
||||
Ok(ReviewTarget::Base { reference: "origin/main".into() })
|
||||
);
|
||||
assert_eq!(
|
||||
parse_review_target(Some("commit deadbeef"), None),
|
||||
Ok(ReviewTarget::Commit { oid: "deadbeef".into() })
|
||||
);
|
||||
let last_turn = ("session-1".into(), "turn-1".into());
|
||||
assert_eq!(
|
||||
parse_review_target(Some("turn"), Some(&last_turn)),
|
||||
Ok(ReviewTarget::LastTurn { session_id: "session-1".into(), turn_id: "turn-1".into() })
|
||||
);
|
||||
assert_eq!(parse_review_target(Some("turn"), None), Err(LAST_TURN_UNAVAILABLE));
|
||||
for invalid in ["base", "patch @@ -1", "base ref extra", "base \u{0007}"] {
|
||||
assert_eq!(parse_review_target(Some(invalid), None), Err(REVIEW_TARGET_USAGE));
|
||||
}
|
||||
}
|
||||
|
||||
/// A pull request by number, by `#number`, or by the address a browser shows, including GitHub
|
||||
/// Enterprise and the tail a copied URL tends to carry.
|
||||
#[test]
|
||||
fn a_pull_request_is_named_the_way_a_reader_would() {
|
||||
let checkout = |number| Ok(ReviewTarget::PullRequest { number, repository: None });
|
||||
let upstream = |number, slug: &str| {
|
||||
Ok(ReviewTarget::PullRequest { number, repository: Some(slug.into()) })
|
||||
};
|
||||
assert_eq!(parse_review_target(Some("pr 123"), None), checkout(123));
|
||||
assert_eq!(parse_review_target(Some("pr #7"), None), checkout(7));
|
||||
for (url, number, slug) in [
|
||||
("https://github.com/acme/app/pull/42", 42, "acme/app"),
|
||||
("github.com/acme/app/pull/42/files", 42, "acme/app"),
|
||||
("https://github.com/acme/app/pull/42?w=1#discussion_r1", 42, "acme/app"),
|
||||
("https://ghe.example.com/Platform/Tools/pull/9/commits", 9, "Platform/Tools"),
|
||||
] {
|
||||
assert_eq!(parse_review_target(Some(&format!("pr {url}")), None), upstream(number, slug));
|
||||
}
|
||||
for invalid in [
|
||||
"pr",
|
||||
"pr 0",
|
||||
"pr -3",
|
||||
"pr #",
|
||||
"pr abc",
|
||||
"pr 12 34",
|
||||
"pr https://github.com/acme/app/issues/42",
|
||||
"pr https://github.com/acme/app/pull/",
|
||||
"pr https://github.com/acme/app/pull/x",
|
||||
"pr 99999999999999999999999",
|
||||
] {
|
||||
assert_eq!(parse_review_target(Some(invalid), None), Err(REVIEW_TARGET_USAGE), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A failed refresh must not lose where the reading had got to.
|
||||
#[test]
|
||||
fn refresh_command_preserves_walked_chapters_after_a_delivery_failure() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let chapter_id = app.guided_review.as_ref().expect("fixture review").chapters[0].id.clone();
|
||||
app.guided_review_workspace.walked_chapters.insert(chapter_id.clone());
|
||||
|
||||
refresh_guided_review(&mut app);
|
||||
|
||||
assert!(app.guided_review_workspace.is_chapter_walked(&chapter_id));
|
||||
assert!(matches!(app.guided_review_workspace.load_state, GuidedReviewLoadState::Failed { .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn diff_without_arguments_loads_the_working_tree_target() {
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let command = crate::commands::CommandRegistry::all()
|
||||
.parse_slash("/diff")
|
||||
.expect("diff command should parse");
|
||||
|
||||
run(&mut app, &command);
|
||||
|
||||
let Some(Action::LoadGuidedReview { request_id, target }) = rx.recv().await else {
|
||||
panic!("diff should send a guided review request");
|
||||
};
|
||||
assert_eq!(target, ReviewTarget::WorkingTree);
|
||||
assert_eq!(app.active_guided_review_request, Some(request_id));
|
||||
// `/diff` is the same request the key makes, so it waits the same way: the capture starts, the
|
||||
// tray says so, and the surface opens when there is a whole review to open.
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
assert_eq!(
|
||||
app.review.queued.as_ref().map(|queued| queued.state),
|
||||
Some(crate::app::QueuedReviewState::Capturing)
|
||||
);
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.load_state,
|
||||
GuidedReviewLoadState::Loading { target: ReviewTarget::WorkingTree }
|
||||
);
|
||||
}
|
||||
|
||||
/// A review asked for mid-turn waits where the reader can see it waiting.
|
||||
///
|
||||
/// The engine will not capture one while a turn is running — `turn.rs` re-queues anything it
|
||||
/// cannot act on — so switching to the review surface here put the reader in front of a
|
||||
/// full-screen "Capturing the working tree" that had not started, with the agent still producing
|
||||
/// the change they wanted to read and no way to watch it. Nothing about the surface said so.
|
||||
#[tokio::test]
|
||||
async fn a_review_asked_for_mid_turn_waits_in_the_tray_instead_of_taking_the_screen() {
|
||||
use crate::app::{AppState, QueuedReviewState};
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.status.state = AppState::Streaming;
|
||||
assert!(app.turn_in_flight());
|
||||
|
||||
super::start_guided_review(&mut app, ReviewTarget::WorkingTree);
|
||||
assert_eq!(
|
||||
app.current_view,
|
||||
crate::app::ViewMode::Chat,
|
||||
"the conversation is where the turn it is waiting on is visible"
|
||||
);
|
||||
assert!(rx.try_recv().is_err(), "and nothing was asked of the engine yet");
|
||||
assert_eq!(
|
||||
app.review.queued.as_ref().map(|queued| queued.state),
|
||||
Some(QueuedReviewState::Waiting)
|
||||
);
|
||||
|
||||
// The turn ends: now there is a revision worth pinning, so the capture goes out — and still
|
||||
// does not take the screen, because the reader has been in the conversation the whole time.
|
||||
app.status.state = AppState::Idle;
|
||||
super::flush_queued_review(&mut app);
|
||||
assert!(matches!(rx.try_recv(), Ok(Action::LoadGuidedReview { .. })), "the capture starts");
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
assert_eq!(
|
||||
app.review.queued.as_ref().map(|queued| queued.state),
|
||||
Some(QueuedReviewState::Capturing)
|
||||
);
|
||||
|
||||
// Captured. The row turns into an offer, and only the reader takes it up.
|
||||
app.review.queued.as_mut().expect("queued").state = QueuedReviewState::Ready;
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
super::start_guided_review(&mut app, ReviewTarget::WorkingTree);
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::GuidedReview, "now it opens");
|
||||
assert!(app.review.queued.is_none(), "and the row has done its job");
|
||||
assert!(rx.try_recv().is_err(), "without capturing a second time");
|
||||
}
|
||||
|
||||
/// Idle only changes when the work starts, never whether the reader is dropped into it.
|
||||
#[tokio::test]
|
||||
async fn a_review_asked_for_while_idle_captures_at_once_but_still_does_not_open() {
|
||||
use crate::app::QueuedReviewState;
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
assert!(!app.turn_in_flight());
|
||||
|
||||
super::start_guided_review(&mut app, ReviewTarget::WorkingTree);
|
||||
assert!(
|
||||
matches!(rx.try_recv(), Ok(Action::LoadGuidedReview { .. })),
|
||||
"nothing to wait for, so the capture goes out immediately"
|
||||
);
|
||||
assert_eq!(
|
||||
app.current_view,
|
||||
crate::app::ViewMode::Chat,
|
||||
"but a half-built review is no better to arrive on for having been quick"
|
||||
);
|
||||
assert_eq!(
|
||||
app.review.queued.as_ref().map(|queued| queued.state),
|
||||
Some(QueuedReviewState::Capturing)
|
||||
);
|
||||
}
|
||||
|
||||
/// The wait after a capture is the model writing the guide, which is most of it. The row moves from
|
||||
/// capturing to writing when the review arrives, and to ready when the guide does.
|
||||
#[tokio::test]
|
||||
async fn the_review_row_follows_the_capture_then_the_guide() {
|
||||
use crate::app::QueuedReviewState;
|
||||
use luxe_core::event::Event;
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let config = Config {
|
||||
notifications: Some(luxe_core::config::Notifications::All(true)),
|
||||
..Config::default()
|
||||
};
|
||||
let mut app = App::new(tx, KeyMap::defaults(), config);
|
||||
let notifier = crate::notify::MockNotifier::new();
|
||||
let calls = notifier.calls.clone();
|
||||
app.notifier = Box::new(notifier);
|
||||
super::start_guided_review(&mut app, ReviewTarget::WorkingTree);
|
||||
let Ok(Action::LoadGuidedReview { request_id, .. }) = rx.try_recv() else {
|
||||
panic!("the capture goes out");
|
||||
};
|
||||
assert_eq!(app.review.queued.as_ref().map(|q| q.state), Some(QueuedReviewState::Capturing));
|
||||
assert_eq!(app.agent_state(), crate::herdr::AgentState::Working, "herdr hears it as work");
|
||||
|
||||
let review = crate::fixture::fixture_demo_guided_review();
|
||||
let (review_id, revision_id, chapters) =
|
||||
(review.id.clone(), review.revision_id.clone(), review.chapters.clone());
|
||||
app.update(crate::app::Msg::Engine(Event::GuidedReviewLoaded {
|
||||
request_id: request_id.clone(),
|
||||
review: Box::new(review),
|
||||
}));
|
||||
assert!(
|
||||
matches!(
|
||||
app.review.queued.as_ref().map(|q| q.state),
|
||||
Some(QueuedReviewState::Writing { .. })
|
||||
),
|
||||
"captured, and now the guide is being written"
|
||||
);
|
||||
|
||||
app.update(crate::app::Msg::Engine(Event::GuidedReviewGuideUpdated {
|
||||
request_id,
|
||||
review_id,
|
||||
revision_id,
|
||||
chapters,
|
||||
provenance: luxe_core::guided_review::GuideProvenance::Model { batches: 1 },
|
||||
brief: None,
|
||||
}));
|
||||
assert_eq!(app.review.queued.as_ref().map(|q| q.state), Some(QueuedReviewState::Ready));
|
||||
// Minutes after it was asked for, which is the point of saying so
|
||||
let bodies: Vec<String> = calls.lock().unwrap().iter().map(|(_, body)| body.clone()).collect();
|
||||
assert_eq!(bodies, ["Review ready"]);
|
||||
// And the conversation keeps a line saying so, the way it keeps one for a posted review
|
||||
let said: Vec<&str> = app
|
||||
.convo
|
||||
.iter()
|
||||
.filter_map(|item| match item.block() {
|
||||
crate::app::ConvoBlock::System(line) => Some(line.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(said.len(), 1, "{said:?}");
|
||||
assert!(said[0].starts_with("[review] Review of working tree is ready · "), "{said:?}");
|
||||
assert_eq!(app.agent_state(), crate::herdr::AgentState::Idle, "and done");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn diff_turn_uses_only_the_retained_baseline_target() {
|
||||
let (tx, mut rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let command = crate::commands::CommandRegistry::all()
|
||||
.parse_slash("/diff turn")
|
||||
.expect("diff turn command should parse");
|
||||
|
||||
run(&mut app, &command);
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(message)) if message == LAST_TURN_UNAVAILABLE
|
||||
));
|
||||
|
||||
app.review.last_turn = Some(("session-1".into(), "turn-1".into()));
|
||||
run(&mut app, &command);
|
||||
let Some(Action::LoadGuidedReview { target, .. }) = rx.recv().await else {
|
||||
panic!("retained turn should send a guided review request");
|
||||
};
|
||||
assert_eq!(
|
||||
target,
|
||||
ReviewTarget::LastTurn { session_id: "session-1".into(), turn_id: "turn-1".into() }
|
||||
);
|
||||
}
|
||||
|
||||
/// The review key on an emptied working tree opens the change, not a review of nothing.
|
||||
///
|
||||
/// A commit takes the diff against `HEAD` to zero at the exact moment there is most to read. The
|
||||
/// turn's own baseline is retained content rather than a Git range, so it still holds the whole
|
||||
/// change — and this is the key the dock's affordance routes to.
|
||||
#[tokio::test]
|
||||
async fn the_review_key_falls_back_to_the_retained_turn_once_the_work_is_committed() {
|
||||
use luxe_core::workspace::{ProjectIdentity, WorkspaceScopeId, WorkspaceSnapshot};
|
||||
|
||||
let (tx, mut rx) = mpsc::channel(2);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.workspace = Some(WorkspaceSnapshot::empty(
|
||||
WorkspaceScopeId::new("scope-a"),
|
||||
ProjectIdentity::non_git("/project".into(), "project", "/project"),
|
||||
));
|
||||
app.review.last_turn = Some(("session-1".into(), "turn-1".into()));
|
||||
|
||||
// A project that was clean all along still means the working tree — there is no committed
|
||||
// work of this session's to fall back to.
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewOpen));
|
||||
let Some(Action::LoadGuidedReview { target, .. }) = rx.recv().await else {
|
||||
panic!("expected a review request")
|
||||
};
|
||||
assert_eq!(target, ReviewTarget::WorkingTree);
|
||||
|
||||
app.current_view = crate::app::ViewMode::Chat;
|
||||
app.worktree_emptied = true;
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewOpen));
|
||||
let Some(Action::LoadGuidedReview { target, .. }) = rx.recv().await else {
|
||||
panic!("expected a review request")
|
||||
};
|
||||
assert_eq!(
|
||||
target,
|
||||
ReviewTarget::LastTurn { session_id: "session-1".into(), turn_id: "turn-1".into() },
|
||||
"the committed change is what there is to review"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn review_navigation_actions_dispatch_only_inside_the_review_surface() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(1);
|
||||
app.engine_tx = engine_tx;
|
||||
let first_hunk = app.guided_review_workspace.position.hunk_id.clone();
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewHunkNext));
|
||||
assert_ne!(app.guided_review_workspace.position.hunk_id, first_hunk);
|
||||
|
||||
let line_offset = app.guided_review_workspace.position.line_offset;
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewLineNext));
|
||||
assert!(app.guided_review_workspace.position.line_offset > line_offset);
|
||||
|
||||
app.guided_review_workspace.diff_column_offset = 12;
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewLineStart));
|
||||
assert_eq!(app.guided_review_workspace.diff_column_offset, 0);
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFileNext));
|
||||
|
||||
assert!(app.guided_review_workspace.guide_visible);
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewToggleGuide));
|
||||
assert!(!app.guided_review_workspace.guide_visible, "the guide pane can be put away");
|
||||
|
||||
// Walking the section records where the reading got to; drain it so the assertions below are
|
||||
// about the comment save.
|
||||
while engine_rx.try_recv().is_ok() {}
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewAddFinding));
|
||||
// One field: everything printable lands in the comment, `Tab` included, and the durable title
|
||||
// is derived from it.
|
||||
for character in ['R', 'e'] {
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Char(character),
|
||||
crossterm::event::KeyModifiers::NONE,
|
||||
),
|
||||
);
|
||||
}
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("open draft");
|
||||
assert_eq!(draft.body(), "Re");
|
||||
assert_eq!(draft.resolved_title(), "Re", "the title comes from the comment's first line");
|
||||
// The verb picked it and nothing in the composer can change it: `c` asks for work.
|
||||
assert_eq!(draft.severity, luxe_core::guided_review::FindingSeverity::Issue);
|
||||
assert!(app.editor.current_input().is_empty());
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
),
|
||||
);
|
||||
assert!(app.guided_review_workspace.finding_draft.is_some());
|
||||
assert_eq!(app.review.session().expect("review session").findings.len(), 0);
|
||||
let Some(Action::EditReview {
|
||||
edit: luxe_core::engine::ReviewEdit::Comment { draft, send: false },
|
||||
..
|
||||
}) = engine_rx.try_recv().ok()
|
||||
else {
|
||||
panic!("expected the comment to be sent to the review desk");
|
||||
};
|
||||
assert_eq!(draft.body, "Re");
|
||||
assert!(app.review_edit_pending(|purpose| *purpose == crate::app::ReviewEditPurpose::Draft));
|
||||
app.update(crate::app::Msg::GuidedReviewSaveFinding);
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Esc,
|
||||
crossterm::event::KeyModifiers::NONE,
|
||||
),
|
||||
);
|
||||
assert!(app.guided_review_workspace.finding_draft.is_none());
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewAddFinding));
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
),
|
||||
);
|
||||
assert!(app.guided_review_workspace.finding_draft.is_some());
|
||||
assert_eq!(app.review.session().expect("review session").findings.len(), 0);
|
||||
assert!(engine_rx.try_recv().is_err());
|
||||
// A save that cannot proceed says why instead of doing nothing at all (here: the previous
|
||||
// save from this test is still in flight).
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.finding_draft.as_ref().and_then(|draft| draft.error.as_deref()),
|
||||
Some("Still saving the last change \u{2014} press again in a moment.")
|
||||
);
|
||||
// Pasting into the composer stays in the composer instead of reaching the chat editor.
|
||||
app.update(crate::app::Msg::PasteText("bound the retry\nloop".into()));
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("open draft");
|
||||
assert_eq!(draft.body(), "bound the retry\nloop");
|
||||
assert!(draft.error.is_none(), "editing clears the rejection reason");
|
||||
assert!(app.editor.current_input().is_empty(), "the chat composer never saw the paste");
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Esc,
|
||||
crossterm::event::KeyModifiers::NONE,
|
||||
),
|
||||
);
|
||||
assert!(app.guided_review_workspace.finding_draft.is_none());
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewFindings));
|
||||
assert!(app.guided_review_workspace.findings_visible);
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Esc,
|
||||
crossterm::event::KeyModifiers::NONE,
|
||||
),
|
||||
);
|
||||
assert!(!app.guided_review_workspace.findings_visible);
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::GuidedReview);
|
||||
|
||||
let layout = app.guided_review_workspace.layout;
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewToggleSplit));
|
||||
assert_ne!(app.guided_review_workspace.layout, layout);
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewExit));
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::Chat);
|
||||
// Going back to a review already captured is immediate: it is pinned and complete, and there
|
||||
// is nothing to wait for.
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewOpen));
|
||||
assert_eq!(app.current_view, crate::app::ViewMode::GuidedReview);
|
||||
assert!(app.review.queued.is_none(), "and nothing is re-captured to get there");
|
||||
assert_eq!(
|
||||
app.guided_review_workspace.load_state,
|
||||
crate::guided_review::GuidedReviewLoadState::Ready,
|
||||
"the review it returns to is the one it left, still ready"
|
||||
);
|
||||
|
||||
app.current_view = crate::app::ViewMode::Chat;
|
||||
assert!(!dispatch_action(&mut app, UiAction::ReviewHunkPrev));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolving_the_selected_finding_asks_the_desk() {
|
||||
let mut app =
|
||||
seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("findings fixture app");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(1);
|
||||
app.engine_tx = engine_tx;
|
||||
let finding_id =
|
||||
app.guided_review_workspace.selected_finding_id.clone().expect("selected finding");
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewToggleSelectedFindingResolved);
|
||||
|
||||
assert!(matches!(
|
||||
engine_rx.try_recv(),
|
||||
Ok(Action::EditReview { edit: luxe_core::engine::ReviewEdit::Resolve { finding_id: resolved }, .. })
|
||||
if resolved == finding_id
|
||||
));
|
||||
assert!(app.review_edit_pending(|_| true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_selected_draft_asks_the_desk() {
|
||||
let mut app =
|
||||
seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("findings fixture app");
|
||||
let draft_id = app
|
||||
.review
|
||||
.session()
|
||||
.expect("review session")
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.state == luxe_core::guided_review::FindingState::Draft)
|
||||
.expect("draft finding")
|
||||
.id
|
||||
.clone();
|
||||
app.guided_review_workspace.selected_finding_id = Some(draft_id.clone());
|
||||
let original_len = app.review.session().expect("review session").findings.len();
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(1);
|
||||
app.engine_tx = engine_tx;
|
||||
|
||||
app.update(crate::app::Msg::GuidedReviewDeleteSelectedFindingDraft);
|
||||
|
||||
assert!(matches!(
|
||||
engine_rx.try_recv(),
|
||||
Ok(Action::EditReview {
|
||||
edit: luxe_core::engine::ReviewEdit::DeleteComment { finding_id },
|
||||
..
|
||||
}) if finding_id == draft_id
|
||||
));
|
||||
assert_eq!(
|
||||
app.review.session().expect("review session").findings.len(),
|
||||
original_len,
|
||||
"gone only once the desk says so"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edited_draft_ctrl_enter_sends_the_new_wording() {
|
||||
let mut app =
|
||||
seeded_app("nord", FixtureScenario::GuidedReviewFindings).expect("findings fixture app");
|
||||
let finding = app
|
||||
.review
|
||||
.session()
|
||||
.expect("review session")
|
||||
.findings
|
||||
.iter()
|
||||
.find(|finding| finding.state == luxe_core::guided_review::FindingState::Draft)
|
||||
.expect("draft finding")
|
||||
.clone();
|
||||
let original_len = app.review.session().expect("review session").findings.len();
|
||||
let original_title = finding.title.clone();
|
||||
assert!(app.guided_review_workspace.begin_edit_finding_draft(&finding));
|
||||
app.guided_review_workspace
|
||||
.finding_draft
|
||||
.as_mut()
|
||||
.expect("local editor")
|
||||
.set_body("Keep bounded retry handling");
|
||||
let (engine_tx, mut engine_rx) = mpsc::channel(1);
|
||||
app.engine_tx = engine_tx;
|
||||
|
||||
crate::app::input::handle_key(
|
||||
&mut app,
|
||||
crossterm::event::KeyEvent::new(
|
||||
crossterm::event::KeyCode::Enter,
|
||||
crossterm::event::KeyModifiers::CONTROL,
|
||||
),
|
||||
);
|
||||
|
||||
let Some(Action::EditReview {
|
||||
edit: luxe_core::engine::ReviewEdit::EditComment { finding_id, title, body, .. },
|
||||
..
|
||||
}) = engine_rx.try_recv().ok()
|
||||
else {
|
||||
panic!("expected the edit to be sent to the review desk");
|
||||
};
|
||||
assert_eq!(finding_id, finding.id, "the same comment, not a second one");
|
||||
assert_eq!(title, "Keep bounded retry handling");
|
||||
assert_eq!(body, "Keep bounded retry handling");
|
||||
assert_eq!(app.review.session().expect("review session").findings.len(), original_len);
|
||||
assert_eq!(
|
||||
app.review
|
||||
.session()
|
||||
.expect("review session")
|
||||
.findings
|
||||
.iter()
|
||||
.find(|candidate| candidate.id == finding.id)
|
||||
.expect("local draft")
|
||||
.title,
|
||||
original_title,
|
||||
"the mirror changes only when the desk answers"
|
||||
);
|
||||
}
|
||||
|
||||
/// The composer is the one place a reviewer writes prose, and it was push/pop-char only. It now
|
||||
/// runs on Luxe's real editor: a cursor you can move, word operations, and Unicode safety.
|
||||
#[test]
|
||||
fn the_comment_composer_supports_real_editing() {
|
||||
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
|
||||
|
||||
let mut app = seeded_app("nord", FixtureScenario::GuidedReviewReady).expect("fixture app");
|
||||
assert!(dispatch_action(&mut app, UiAction::ReviewAddFinding));
|
||||
let key = KeyEvent::new;
|
||||
|
||||
for character in "bound retries".chars() {
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Char(character), KeyModifiers::NONE));
|
||||
}
|
||||
// Home, then type: the insertion lands at the cursor, not blindly at the end.
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Home, KeyModifiers::NONE));
|
||||
for character in "please ".chars() {
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Char(character), KeyModifiers::NONE));
|
||||
}
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("open draft");
|
||||
assert_eq!(draft.body(), "please bound retries");
|
||||
|
||||
// Enter inserts a newline rather than firing the chat submit behind the review.
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::End, KeyModifiers::CONTROL));
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Enter, KeyModifiers::NONE));
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Char('x'), KeyModifiers::NONE));
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("open draft");
|
||||
assert_eq!(draft.body(), "please bound retries\nx");
|
||||
assert!(app.editor.current_input().is_empty(), "the chat composer stayed untouched");
|
||||
|
||||
// Backspace and arrow movement work over multi-byte text.
|
||||
for character in "é→".chars() {
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Char(character), KeyModifiers::NONE));
|
||||
}
|
||||
crate::app::input::handle_key(&mut app, key(KeyCode::Backspace, KeyModifiers::NONE));
|
||||
let draft = app.guided_review_workspace.finding_draft.as_ref().expect("open draft");
|
||||
assert_eq!(draft.body(), "please bound retries\nxé", "backspace removes one whole character");
|
||||
}
|
||||
283
crates/luxe-tui/src/app/commands/tests/slash.rs
Normal file
283
crates/luxe-tui/src/app/commands/tests/slash.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! Slash — the commands that flip a switch, and the config they re-read.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mouse_toggle_action_and_slash_command_flip_capture_state() {
|
||||
let mut app = seeded_app("nord", FixtureScenario::ChatIdle).expect("chat fixture");
|
||||
assert!(app.mouse_enabled, "mouse defaults on");
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ToggleMouse));
|
||||
assert!(!app.mouse_enabled, "ToggleMouse turns it off");
|
||||
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
run(&mut app, ®istry.parse_slash("/mouse on").expect("/mouse on parses"));
|
||||
assert!(app.mouse_enabled, "/mouse on enables");
|
||||
run(&mut app, ®istry.parse_slash("/mouse off").expect("/mouse off parses"));
|
||||
assert!(!app.mouse_enabled, "/mouse off disables");
|
||||
run(&mut app, ®istry.parse_slash("/mouse").expect("bare /mouse parses"));
|
||||
assert!(app.mouse_enabled, "bare /mouse toggles back on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_slash_toggles_auto_approve() {
|
||||
let (mut app, _engine) = seeded_session("nord", FixtureScenario::ChatIdle).expect("fixture");
|
||||
assert!(!app.permission_auto_approve, "auto-approve defaults off in the TUI");
|
||||
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
run(&mut app, ®istry.parse_slash("/permissions on").expect("parses"));
|
||||
assert!(app.permission_auto_approve, "/permissions on enables auto-approve");
|
||||
run(&mut app, ®istry.parse_slash("/permissions off").expect("parses"));
|
||||
assert!(!app.permission_auto_approve, "/permissions off disables");
|
||||
run(&mut app, ®istry.parse_slash("/permissions").expect("bare parses"));
|
||||
assert!(app.permission_auto_approve, "bare /permissions toggles back on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lsp_and_debug_slash_render_the_tooling_summary() {
|
||||
use luxe_core::{
|
||||
DebugAdapterStatus, LanguageServerStatus, ProjectIdentity, ToolingSummary,
|
||||
WorkspaceScopeId, WorkspaceSnapshot,
|
||||
};
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let mut snapshot = WorkspaceSnapshot::empty(
|
||||
WorkspaceScopeId::new("scope"),
|
||||
ProjectIdentity::non_git("/project".into(), "project", "/project"),
|
||||
);
|
||||
snapshot.tooling = ToolingSummary {
|
||||
servers: vec![LanguageServerStatus {
|
||||
language: "rust".into(),
|
||||
command: "rust-analyzer".into(),
|
||||
extensions: vec!["rs".into()],
|
||||
from_config: false,
|
||||
install_hint: Some("rustup component add rust-analyzer".into()),
|
||||
installed: true,
|
||||
running: true,
|
||||
}],
|
||||
adapters: vec![DebugAdapterStatus {
|
||||
id: "debugpy".into(),
|
||||
command: "python3 -m debugpy.adapter".into(),
|
||||
extensions: vec!["py".into()],
|
||||
from_config: false,
|
||||
installed: true,
|
||||
}],
|
||||
debug_sessions: Vec::new(),
|
||||
mcp_servers: vec![luxe_core::McpServerStatus {
|
||||
id: "demo".into(),
|
||||
transport: "stdio".into(),
|
||||
auth: "none".into(),
|
||||
tool_count: Some(3),
|
||||
enabled: true,
|
||||
..Default::default()
|
||||
}],
|
||||
lsp_config_path: None,
|
||||
adapters_config_path: None,
|
||||
tools: Vec::new(),
|
||||
};
|
||||
app.workspace = Some(snapshot);
|
||||
|
||||
let reg = crate::commands::CommandRegistry::all();
|
||||
run(&mut app, ®.parse_slash("/lsp").expect("/lsp parses"));
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text)) if text.contains("rust") && text.contains("running")
|
||||
));
|
||||
|
||||
run(&mut app, ®.parse_slash("/debug").expect("/debug parses"));
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text)) if text.contains("debugpy")
|
||||
));
|
||||
|
||||
run(&mut app, ®.parse_slash("/mcp").expect("/mcp parses"));
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text)) if text.contains("demo") && text.contains("stdio")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lsp_slash_is_graceful_before_the_first_snapshot() {
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let reg = crate::commands::CommandRegistry::all();
|
||||
run(&mut app, ®.parse_slash("/lsp").expect("/lsp parses"));
|
||||
assert!(matches!(
|
||||
app.convo.last().map(|item| item.block()),
|
||||
Some(ConvoBlock::System(text)) if text.contains("isn't ready yet")
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn palette_slash_backed_action_preserves_a_half_typed_prompt() {
|
||||
// Picking "Search conversation" from the palette while a draft is in the
|
||||
// composer must NOT clear it — the slash-backed action dispatches through the
|
||||
// editor-preserving action path, not the old composer-clearing slash handler.
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.editor.insert_text("draft prompt");
|
||||
let search = crate::commands::CommandRegistry::all()
|
||||
.commands
|
||||
.into_iter()
|
||||
.find(|command| command.id == "tui.convo.search")
|
||||
.expect("search should be a palette command");
|
||||
|
||||
dispatch(&mut app, search);
|
||||
|
||||
assert!(app.search_state.is_active());
|
||||
assert_eq!(app.editor.current_input(), "draft prompt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_session_slash_asks_the_engine_for_a_fresh_session() {
|
||||
// `/new` must dispatch `Action::NewSession` (not just clear the transcript locally) so the
|
||||
// engine switches sessions and the sidebar stops showing the prior session's title.
|
||||
let (tx, mut rx) = mpsc::channel(4);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.session_id = Some("prior-session".into());
|
||||
app.push_convo(ConvoBlock::User { text: "hi".into(), attached: vec![], chips: Vec::new() });
|
||||
let command = crate::commands::CommandRegistry::all().parse_slash("/new").expect("/new parses");
|
||||
|
||||
run(&mut app, &command);
|
||||
|
||||
assert!(app.convo.is_empty(), "/new should clear the transcript");
|
||||
assert!(app.session_id.is_none(), "/new should drop the active session id");
|
||||
assert!(matches!(rx.try_recv(), Ok(Action::NewSession)), "/new must dispatch NewSession");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quit_works_from_the_palette_and_from_a_typed_slash() {
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
|
||||
// Palette selection of the "Quit" row.
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let quit = registry
|
||||
.commands
|
||||
.iter()
|
||||
.find(|command| command.id == "tui.app.quit")
|
||||
.expect("quit should be a palette command")
|
||||
.clone();
|
||||
dispatch(&mut app, quit);
|
||||
assert!(app.should_quit, "palette Quit should quit");
|
||||
|
||||
// Typed `/quit` resolves to the same action.
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let typed = registry.parse_slash("/quit").expect("/quit should parse");
|
||||
run(&mut app, &typed);
|
||||
assert!(app.should_quit, "/quit should quit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_slash_forms_dispatch_visibility_actions() {
|
||||
use crate::workspace_dock::DockRuntimeOverride;
|
||||
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
|
||||
for (input, expected) in [
|
||||
("/dock", DockRuntimeOverride::Shown),
|
||||
("/dock hide", DockRuntimeOverride::Hidden),
|
||||
("/dock show", DockRuntimeOverride::Shown),
|
||||
("/dock auto", DockRuntimeOverride::None),
|
||||
] {
|
||||
let command = registry.parse_slash(input).expect("dock form should parse");
|
||||
run(&mut app, &command);
|
||||
assert_eq!(app.dock.runtime_override, expected, "{input}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dock_position_action_and_slash_forms_move_the_sidebar() {
|
||||
use luxe_core::config::DockPosition;
|
||||
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
assert_eq!(app.dock.position, DockPosition::Left);
|
||||
|
||||
assert!(dispatch_action(&mut app, UiAction::ToggleDockPosition));
|
||||
assert_eq!(app.dock.position, DockPosition::Right);
|
||||
|
||||
run(&mut app, ®istry.parse_slash("/dock left").expect("/dock left parses"));
|
||||
assert_eq!(app.dock.position, DockPosition::Left);
|
||||
run(&mut app, ®istry.parse_slash("/dock right").expect("/dock right parses"));
|
||||
assert_eq!(app.dock.position, DockPosition::Right);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statusline_visibility_actions_and_slash_forms_toggle_the_override() {
|
||||
use crate::statusline_state::StatuslineOverride;
|
||||
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.workspace_layout = crate::workspace_layout::WorkspaceLayout::Wide;
|
||||
let registry = crate::commands::CommandRegistry::all();
|
||||
|
||||
// Auto would hide beside the side-by-side dock, so a bare toggle forces it shown.
|
||||
app.dock.show();
|
||||
assert!(dispatch_action(&mut app, UiAction::ToggleStatusline));
|
||||
assert_eq!(app.statusline_state.runtime_override, StatuslineOverride::Shown);
|
||||
|
||||
for (input, expected) in [
|
||||
("/statusline hide", StatuslineOverride::Hidden),
|
||||
("/statusline show", StatuslineOverride::Shown),
|
||||
("/statusline auto", StatuslineOverride::None),
|
||||
] {
|
||||
let command = registry.parse_slash(input).expect("statusline form should parse");
|
||||
run(&mut app, &command);
|
||||
assert_eq!(app.statusline_state.runtime_override, expected, "{input}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_config_refreshes_conversation_preferences() {
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let luxe = repo.path().join(".luxe");
|
||||
std::fs::create_dir(&luxe).unwrap();
|
||||
std::fs::write(
|
||||
luxe.join("config.json"),
|
||||
r#"{"conversation":{"prose_max_width":72,"wide_block_max_width":120,"tool_details":"all"},"dock":{"mode":"shown"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
app.dock.hide();
|
||||
|
||||
reload_config(&mut app, repo.path());
|
||||
|
||||
assert_eq!(app.config.conversation.prose_max_width(), 72);
|
||||
assert_eq!(app.config.conversation.wide_block_max_width(), 120);
|
||||
assert_eq!(
|
||||
app.config.conversation.tool_details(),
|
||||
luxe_core::config::ToolDetailsPreference::All
|
||||
);
|
||||
assert_eq!(app.dock.configured, luxe_core::config::DockMode::Shown);
|
||||
assert_eq!(app.dock.runtime_override, crate::workspace_dock::DockRuntimeOverride::Hidden);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_config_refreshes_dock_position_and_statusline_visibility() {
|
||||
use luxe_core::config::{DockPosition, StatuslineVisibility};
|
||||
|
||||
let repo = tempfile::tempdir().unwrap();
|
||||
let luxe = repo.path().join(".luxe");
|
||||
std::fs::create_dir(&luxe).unwrap();
|
||||
std::fs::write(
|
||||
luxe.join("config.json"),
|
||||
r#"{"dock":{"position":"right"},"statusline":{"visibility":"hidden"}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (tx, _rx) = mpsc::channel(1);
|
||||
let mut app = App::new(tx, KeyMap::defaults(), Config::default());
|
||||
assert_eq!(app.dock.position, DockPosition::Left);
|
||||
assert_eq!(app.statusline_state.configured, StatuslineVisibility::Auto);
|
||||
|
||||
reload_config(&mut app, repo.path());
|
||||
|
||||
assert_eq!(app.dock.position, DockPosition::Right);
|
||||
assert_eq!(app.statusline_state.configured, StatuslineVisibility::Hidden);
|
||||
}
|
||||
Reference in New Issue
Block a user