diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 3196176823..2a04d43164 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -1765,7 +1765,12 @@ async fn spawn_review_thread( text: review_prompt, }]; let tc = Arc::new(review_turn_context); - sess.spawn_task(tc.clone(), input, ReviewTask).await; + sess.spawn_task( + tc.clone(), + input, + ReviewTask::new(review_request.append_to_original_thread), + ) + .await; // Announce entering review mode so UIs can switch modes. sess.send_event(&tc, EventMsg::EnteredReviewMode(review_request)) @@ -2753,7 +2758,8 @@ mod tests { let input = vec![UserInput::Text { text: "start review".to_string(), }]; - sess.spawn_task(Arc::clone(&tc), input, ReviewTask).await; + sess.spawn_task(Arc::clone(&tc), input, ReviewTask::new(true)) + .await; sess.abort_all_tasks(TurnAbortReason::Interrupted).await; diff --git a/codex-rs/core/src/review_prompts.rs b/codex-rs/core/src/review_prompts.rs index 9c033dfd70..7122b55697 100644 --- a/codex-rs/core/src/review_prompts.rs +++ b/codex-rs/core/src/review_prompts.rs @@ -1,5 +1,44 @@ +use codex_protocol::protocol::ReviewRequest; use std::cmp::min; +/// Target to review against. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ReviewTarget { + /// Review the working tree: staged, unstaged, and untracked files. + UncommittedChanges, + + /// Review changes between the current branch and the given base branch. + BaseBranch { branch: String }, + + /// Review the changes introduced by a specific commit. + Commit { + sha: String, + /// Optional human-readable label (e.g., commit subject) for UIs. + title: Option, + }, + + /// Arbitrary instructions, equivalent to the old free-form prompt. + Custom { instructions: String }, +} + +/// Validation errors for review targets. +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum ReviewTargetError { + #[error("branch must not be empty")] + EmptyBranch, + #[error("sha must not be empty")] + EmptySha, + #[error("instructions must not be empty")] + EmptyInstructions, +} + +/// Built review request plus a user-visible description of the target. +#[derive(Clone, Debug, PartialEq)] +pub struct BuiltReviewRequest { + pub review_request: ReviewRequest, + pub display_text: String, +} + /// Build the review prompt and user-facing hint for uncommitted changes. pub fn review_uncommitted_prompt() -> (String, String) { let prompt = "Review the current code changes (staged, unstaged, and untracked files) and provide prioritized findings.".to_string(); @@ -19,7 +58,7 @@ pub fn review_branch_prompt(branch: &str) -> (String, String) { /// Build the review prompt and hint for a specific commit. /// If `subject_opt` is provided, it will be included in the prompt; otherwise it is omitted. pub fn review_commit_prompt(sha: &str, subject_opt: Option<&str>) -> (String, String) { - let short = &sha[..min(7, sha.len())]; + let short: String = sha.chars().take(min(7, sha.len())).collect(); let prompt = if let Some(subject) = subject_opt { format!( "Review the code changes introduced by commit {sha} (\"{subject}\"). Provide prioritized, actionable findings." @@ -36,17 +75,133 @@ pub fn review_commit_prompt(sha: &str, subject_opt: Option<&str>) -> (String, St /// Build the review prompt and hint for custom free-form instructions. pub fn review_custom_prompt(custom: &str) -> (String, String) { let prompt = custom.trim().to_string(); - let trimmed = prompt.clone(); - let hint = if trimmed.is_empty() { - "custom review".to_string() - } else { - let s = trimmed.replace('\n', " "); - let max = 80usize; - if s.len() > max { - format!("{}…", &s[..max]) - } else { - s - } - }; - (prompt, hint) + (prompt.clone(), prompt) +} + +pub fn review_request_from_target( + target: ReviewTarget, + append_to_original_thread: bool, +) -> Result { + match target { + ReviewTarget::UncommittedChanges => { + let (prompt, hint) = review_uncommitted_prompt(); + Ok(BuiltReviewRequest { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + append_to_original_thread, + }, + display_text: "Review uncommitted changes".to_string(), + }) + } + ReviewTarget::BaseBranch { branch } => { + let branch = branch.trim().to_string(); + if branch.is_empty() { + return Err(ReviewTargetError::EmptyBranch); + } + let (prompt, hint) = review_branch_prompt(&branch); + Ok(BuiltReviewRequest { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + append_to_original_thread, + }, + display_text: format!("Review changes against base branch '{branch}'"), + }) + } + ReviewTarget::Commit { sha, title } => { + let sha = sha.trim().to_string(); + if sha.is_empty() { + return Err(ReviewTargetError::EmptySha); + } + let title = title.map(|t| t.trim().to_string()).filter(|t| !t.is_empty()); + let (prompt, hint) = review_commit_prompt(&sha, title.as_deref()); + let short_sha: String = sha.chars().take(min(7, sha.len())).collect(); + let display_text = if let Some(title) = title { + format!("Review commit {short_sha}: {title}") + } else { + format!("Review commit {short_sha}") + }; + Ok(BuiltReviewRequest { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + append_to_original_thread, + }, + display_text, + }) + } + ReviewTarget::Custom { instructions } => { + let trimmed = instructions.trim().to_string(); + if trimmed.is_empty() { + return Err(ReviewTargetError::EmptyInstructions); + } + let (prompt, hint) = review_custom_prompt(&trimmed); + Ok(BuiltReviewRequest { + review_request: ReviewRequest { + prompt, + user_facing_hint: hint, + append_to_original_thread, + }, + display_text: trimmed, + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn commit_target_includes_title_and_short_sha() { + let built = review_request_from_target( + ReviewTarget::Commit { + sha: "123456789".to_string(), + title: Some("Refactor colors".to_string()), + }, + true, + ) + .expect("valid commit target"); + + assert!(built.display_text.contains("1234567")); + assert!(built.display_text.contains("Refactor colors")); + assert_eq!(built.review_request.user_facing_hint, "commit 1234567"); + assert!(built.review_request.append_to_original_thread); + } + + #[test] + fn empty_inputs_reject() { + assert_eq!( + review_request_from_target( + ReviewTarget::BaseBranch { + branch: " ".to_string() + }, + false + ) + .unwrap_err(), + ReviewTargetError::EmptyBranch + ); + assert_eq!( + review_request_from_target( + ReviewTarget::Commit { + sha: "".to_string(), + title: None + }, + false + ) + .unwrap_err(), + ReviewTargetError::EmptySha + ); + assert_eq!( + review_request_from_target( + ReviewTarget::Custom { + instructions: "\n".to_string() + }, + false + ) + .unwrap_err(), + ReviewTargetError::EmptyInstructions + ); + } } diff --git a/codex-rs/core/src/tasks/review.rs b/codex-rs/core/src/tasks/review.rs index e0bb7d4e93..14a95dba5c 100644 --- a/codex-rs/core/src/tasks/review.rs +++ b/codex-rs/core/src/tasks/review.rs @@ -23,8 +23,18 @@ use codex_protocol::user_input::UserInput; use super::SessionTask; use super::SessionTaskContext; -#[derive(Clone, Copy, Default)] -pub(crate) struct ReviewTask; +#[derive(Clone, Copy)] +pub(crate) struct ReviewTask { + append_to_original_thread: bool, +} + +impl ReviewTask { + pub(crate) fn new(append_to_original_thread: bool) -> Self { + Self { + append_to_original_thread, + } + } +} #[async_trait] impl SessionTask for ReviewTask { @@ -52,13 +62,25 @@ impl SessionTask for ReviewTask { None => None, }; if !cancellation_token.is_cancelled() { - exit_review_mode(session.clone_session(), output.clone(), ctx.clone()).await; + exit_review_mode( + session.clone_session(), + output.clone(), + ctx.clone(), + self.append_to_original_thread, + ) + .await; } None } async fn abort(&self, session: Arc, ctx: Arc) { - exit_review_mode(session.clone_session(), None, ctx).await; + exit_review_mode( + session.clone_session(), + None, + ctx, + self.append_to_original_thread, + ) + .await; } } @@ -175,32 +197,35 @@ pub(crate) async fn exit_review_mode( session: Arc, review_output: Option, ctx: Arc, + append_to_original_thread: bool, ) { - let user_message = if let Some(out) = review_output.clone() { - let mut findings_str = String::new(); - let text = out.overall_explanation.trim(); - if !text.is_empty() { - findings_str.push_str(text); - } - if !out.findings.is_empty() { - let block = format_review_findings_block(&out.findings, None); - findings_str.push_str(&format!("\n{block}")); - } - crate::client_common::REVIEW_EXIT_SUCCESS_TMPL.replace("{results}", &findings_str) - } else { - crate::client_common::REVIEW_EXIT_INTERRUPTED_TMPL.to_string() - }; + if append_to_original_thread { + let user_message = if let Some(out) = review_output.clone() { + let mut findings_str = String::new(); + let text = out.overall_explanation.trim(); + if !text.is_empty() { + findings_str.push_str(text); + } + if !out.findings.is_empty() { + let block = format_review_findings_block(&out.findings, None); + findings_str.push_str(&format!("\n{block}")); + } + crate::client_common::REVIEW_EXIT_SUCCESS_TMPL.replace("{results}", &findings_str) + } else { + crate::client_common::REVIEW_EXIT_INTERRUPTED_TMPL.to_string() + }; - session - .record_conversation_items( - &ctx, - &[ResponseItem::Message { - id: None, - role: "user".to_string(), - content: vec![ContentItem::InputText { text: user_message }], - }], - ) - .await; + session + .record_conversation_items( + &ctx, + &[ResponseItem::Message { + id: None, + role: "user".to_string(), + content: vec![ContentItem::InputText { text: user_message }], + }], + ) + .await; + } session .send_event( ctx.as_ref(), diff --git a/codex-rs/core/tests/suite/codex_delegate.rs b/codex-rs/core/tests/suite/codex_delegate.rs index c6ece7fe56..6339bfa71a 100644 --- a/codex-rs/core/tests/suite/codex_delegate.rs +++ b/codex-rs/core/tests/suite/codex_delegate.rs @@ -70,6 +70,7 @@ async fn codex_delegate_forwards_exec_approval_and_proceeds_on_approval() { review_request: ReviewRequest { prompt: "Please review".to_string(), user_facing_hint: "review".to_string(), + append_to_original_thread: true, }, }) .await @@ -145,6 +146,7 @@ async fn codex_delegate_forwards_patch_approval_and_proceeds_on_decision() { review_request: ReviewRequest { prompt: "Please review".to_string(), user_facing_hint: "review".to_string(), + append_to_original_thread: true, }, }) .await @@ -199,6 +201,7 @@ async fn codex_delegate_ignores_legacy_deltas() { review_request: ReviewRequest { prompt: "Please review".to_string(), user_facing_hint: "review".to_string(), + append_to_original_thread: true, }, }) .await diff --git a/codex-rs/core/tests/suite/review.rs b/codex-rs/core/tests/suite/review.rs index 9c3f812c29..3904f18f8e 100644 --- a/codex-rs/core/tests/suite/review.rs +++ b/codex-rs/core/tests/suite/review.rs @@ -82,6 +82,7 @@ async fn review_op_emits_lifecycle_and_review_output() { review_request: ReviewRequest { prompt: "Please review my changes".to_string(), user_facing_hint: "my changes".to_string(), + append_to_original_thread: true, }, }) .await @@ -178,6 +179,7 @@ async fn review_op_with_plain_text_emits_review_fallback() { review_request: ReviewRequest { prompt: "Plain text review".to_string(), user_facing_hint: "plain text review".to_string(), + append_to_original_thread: true, }, }) .await @@ -236,6 +238,7 @@ async fn review_filters_agent_message_related_events() { review_request: ReviewRequest { prompt: "Filter streaming events".to_string(), user_facing_hint: "Filter streaming events".to_string(), + append_to_original_thread: true, }, }) .await @@ -320,6 +323,7 @@ async fn review_does_not_emit_agent_message_on_structured_output() { review_request: ReviewRequest { prompt: "check structured".to_string(), user_facing_hint: "check structured".to_string(), + append_to_original_thread: true, }, }) .await @@ -373,6 +377,7 @@ async fn review_uses_custom_review_model_from_config() { review_request: ReviewRequest { prompt: "use custom model".to_string(), user_facing_hint: "use custom model".to_string(), + append_to_original_thread: true, }, }) .await @@ -490,6 +495,7 @@ async fn review_input_isolated_from_parent_history() { review_request: ReviewRequest { prompt: review_prompt.clone(), user_facing_hint: review_prompt.clone(), + append_to_original_thread: true, }, }) .await @@ -602,6 +608,7 @@ async fn review_history_does_not_leak_into_parent_session() { review_request: ReviewRequest { prompt: "Start a review".to_string(), user_facing_hint: "Start a review".to_string(), + append_to_original_thread: true, }, }) .await diff --git a/codex-rs/exec/src/lib.rs b/codex-rs/exec/src/lib.rs index 8749f91f3c..46a0df362d 100644 --- a/codex-rs/exec/src/lib.rs +++ b/codex-rs/exec/src/lib.rs @@ -30,6 +30,8 @@ use codex_core::protocol::Event; use codex_core::protocol::EventMsg; use codex_core::protocol::Op; use codex_core::protocol::SessionSource; +use codex_core::review_prompts::review_request_from_target; +use codex_core::review_prompts::ReviewTarget; use codex_protocol::config_types::SandboxMode; use codex_protocol::user_input::UserInput; use event_processor_with_human_output::EventProcessorWithHumanOutput; @@ -393,45 +395,55 @@ pub async fn run_main(cli: Cli, codex_linux_sandbox_exe: Option) -> any let _initial_prompt_task_id = match &command { Some(ExecCommand::Review(args)) => { - use codex_core::protocol::ReviewRequest; - - // Compute prompt + hint. - let (review_prompt, mut review_hint) = if let Some(custom) = args.prompt.as_deref() { + let append_to_original_thread = true; + let target = if let Some(custom) = args.prompt.as_deref() { let text = if custom == "-" { read_prompt_from_stdin_or_exit(true) } else { custom.to_string() }; - codex_core::review_prompts::review_custom_prompt(&text) + ReviewTarget::Custom { + instructions: text, + } } else if let Some(branch) = &args.branch { - codex_core::review_prompts::review_branch_prompt(branch) + ReviewTarget::BaseBranch { + branch: branch.clone(), + } } else if let Some(sha) = &args.commit { // Try to enrich with subject; fall back gracefully. - let mut subject: Option = None; + let mut title: Option = None; let entries = codex_core::git_info::recent_commits(&default_cwd, 200).await; - for e in entries { - if e.sha.starts_with(sha) { - if !e.subject.trim().is_empty() { - subject = Some(e.subject); + for entry in entries { + if entry.sha.starts_with(sha) { + if !entry.subject.trim().is_empty() { + title = Some(entry.subject); } break; } } - codex_core::review_prompts::review_commit_prompt(sha, subject.as_deref()) + ReviewTarget::Commit { + sha: sha.clone(), + title, + } } else { // Default to reviewing uncommitted changes if nothing else specified. - codex_core::review_prompts::review_uncommitted_prompt() + ReviewTarget::UncommittedChanges }; + let mut built_request = + review_request_from_target(target, append_to_original_thread).map_err(|err| { + anyhow::anyhow!("invalid review target: {err}") + })?; + if let Some(hint_override) = &args.hint { - review_hint = hint_override.clone(); + built_request.review_request.user_facing_hint = hint_override.clone(); } - let review_request = ReviewRequest { - prompt: review_prompt, - user_facing_hint: review_hint, - }; - let id = conversation.submit(Op::Review { review_request }).await?; + let id = conversation + .submit(Op::Review { + review_request: built_request.review_request, + }) + .await?; info!("Sent review request with event ID: {id}"); id } diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 553f6437a6..3e25d72c59 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -1176,6 +1176,8 @@ pub struct GitInfo { pub struct ReviewRequest { pub prompt: String, pub user_facing_hint: String, + #[serde(default)] + pub append_to_original_thread: bool, } /// Structured review result produced by a child review session. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index ca565d2a89..3b9b955d53 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -52,6 +52,7 @@ use codex_core::protocol::ViewImageToolCallEvent; use codex_core::protocol::WarningEvent; use codex_core::protocol::WebSearchBeginEvent; use codex_core::protocol::WebSearchEndEvent; +use codex_core::review_prompts::ReviewTarget; use codex_protocol::ConversationId; use codex_protocol::parse_command::ParsedCommand; use codex_protocol::user_input::UserInput; @@ -145,6 +146,15 @@ const RATE_LIMIT_WARNING_THRESHOLDS: [f64; 3] = [75.0, 90.0, 95.0]; const NUDGE_MODEL_SLUG: &str = "gpt-5.1-codex-mini"; const RATE_LIMIT_SWITCH_PROMPT_THRESHOLD: f64 = 90.0; +fn build_review_request(target: ReviewTarget) -> Option { + codex_core::review_prompts::review_request_from_target(target, true) + .map(|built| built.review_request) + .map_err(|err| { + debug!(?err, "invalid review target"); + }) + .ok() +} + #[derive(Default)] struct RateLimitWarningState { secondary_index: usize, @@ -2713,16 +2723,13 @@ impl ChatWidget { ..Default::default() }); + let uncommitted_request = build_review_request(ReviewTarget::UncommittedChanges); items.push(SelectionItem { name: "Review uncommitted changes".to_string(), actions: vec![Box::new(move |tx: &AppEventSender| { - let (prompt, hint) = codex_core::review_prompts::review_uncommitted_prompt(); - tx.send(AppEvent::CodexOp(Op::Review { - review_request: ReviewRequest { - prompt, - user_facing_hint: hint, - }, - })); + if let Some(review_request) = uncommitted_request.clone() { + tx.send(AppEvent::CodexOp(Op::Review { review_request })); + } })], dismiss_on_select: true, ..Default::default() @@ -2770,13 +2777,11 @@ impl ChatWidget { items.push(SelectionItem { name: format!("{current_branch} -> {branch}"), actions: vec![Box::new(move |tx3: &AppEventSender| { - let (prompt, hint) = codex_core::review_prompts::review_branch_prompt(&branch); - tx3.send(AppEvent::CodexOp(Op::Review { - review_request: ReviewRequest { - prompt, - user_facing_hint: hint, - }, - })); + if let Some(review_request) = + build_review_request(ReviewTarget::BaseBranch { branch: branch.clone() }) + { + tx3.send(AppEvent::CodexOp(Op::Review { review_request })); + } })], dismiss_on_select: true, search_value: Some(option), @@ -2806,14 +2811,12 @@ impl ChatWidget { items.push(SelectionItem { name: subject.clone(), actions: vec![Box::new(move |tx3: &AppEventSender| { - let (prompt, hint) = - codex_core::review_prompts::review_commit_prompt(&sha, Some(&subject)); - tx3.send(AppEvent::CodexOp(Op::Review { - review_request: ReviewRequest { - prompt, - user_facing_hint: hint, - }, - })); + if let Some(review_request) = build_review_request(ReviewTarget::Commit { + sha: sha.clone(), + title: Some(subject.clone()), + }) { + tx3.send(AppEvent::CodexOp(Op::Review { review_request })); + } })], dismiss_on_select: true, search_value: Some(search_val), @@ -2838,21 +2841,19 @@ impl ChatWidget { "Type instructions and press Enter".to_string(), None, Box::new(move |prompt: String| { - let trimmed = prompt.trim().to_string(); - if trimmed.is_empty() { - return; - } - let (prompt, hint) = codex_core::review_prompts::review_custom_prompt(&trimmed); - tx.send(AppEvent::CodexOp(Op::Review { - review_request: ReviewRequest { - prompt, - user_facing_hint: hint, - }, - })); - }), - ); - self.bottom_pane.show_view(Box::new(view)); - } + let trimmed = prompt.trim().to_string(); + if trimmed.is_empty() { + return; + } + if let Some(review_request) = + build_review_request(ReviewTarget::Custom { instructions: trimmed }) + { + tx.send(AppEvent::CodexOp(Op::Review { review_request })); + } + }), + ); + self.bottom_pane.show_view(Box::new(view)); +} pub(crate) fn token_usage(&self) -> TokenUsage { self.token_info @@ -3043,22 +3044,17 @@ pub(crate) fn show_review_commit_picker_with_entries( for entry in entries { let subject = entry.subject.clone(); let sha = entry.sha.clone(); - let short = sha.chars().take(7).collect::(); let search_val = format!("{subject} {sha}"); items.push(SelectionItem { name: subject.clone(), actions: vec![Box::new(move |tx3: &AppEventSender| { - let hint = format!("commit {short}"); - let prompt = format!( - "Review the code changes introduced by commit {sha} (\"{subject}\"). Provide prioritized, actionable findings." - ); - tx3.send(AppEvent::CodexOp(Op::Review { - review_request: ReviewRequest { - prompt, - user_facing_hint: hint, - }, - })); + if let Some(review_request) = build_review_request(ReviewTarget::Commit { + sha: sha.clone(), + title: Some(subject.clone()), + }) { + tx3.send(AppEvent::CodexOp(Op::Review { review_request })); + } })], dismiss_on_select: true, search_value: Some(search_val), diff --git a/codex-rs/tui/src/chatwidget/tests.rs b/codex-rs/tui/src/chatwidget/tests.rs index abd9a61238..8f2a7925ad 100644 --- a/codex-rs/tui/src/chatwidget/tests.rs +++ b/codex-rs/tui/src/chatwidget/tests.rs @@ -140,6 +140,7 @@ fn entered_review_mode_uses_request_hint() { msg: EventMsg::EnteredReviewMode(ReviewRequest { prompt: "Review the latest changes".to_string(), user_facing_hint: "feature branch".to_string(), + append_to_original_thread: true, }), }); @@ -159,6 +160,7 @@ fn entered_review_mode_defaults_to_current_changes_banner() { msg: EventMsg::EnteredReviewMode(ReviewRequest { prompt: "Review the current changes".to_string(), user_facing_hint: "current changes".to_string(), + append_to_original_thread: true, }), });