From 731a354f6c2a1ffe7b6f8356dab1ed256eb6f391 Mon Sep 17 00:00:00 2001 From: jimmyfraiture Date: Mon, 8 Sep 2025 10:07:57 -0700 Subject: [PATCH] V1 --- codex-rs/core/src/codex.rs | 114 ++++++++++++++++++++----- codex-rs/core/src/turn_diff_tracker.rs | 59 +++++++++++++ codex-rs/protocol/src/protocol.rs | 4 + codex-rs/tui/src/chatwidget.rs | 4 + codex-rs/tui/src/slash_command.rs | 3 + 5 files changed, 161 insertions(+), 23 deletions(-) diff --git a/codex-rs/core/src/codex.rs b/codex-rs/core/src/codex.rs index 639493b427..13b49b1c09 100644 --- a/codex-rs/core/src/codex.rs +++ b/codex-rs/core/src/codex.rs @@ -267,6 +267,12 @@ struct State { pending_input: Vec, history: ConversationHistory, token_info: Option, + last_undo_patch: Option, +} + +#[derive(Clone)] +struct StoredUndoPatch { + patch: String, } /// Context for an initialized model agent @@ -660,6 +666,19 @@ impl Session { state.approved_commands.insert(cmd); } + fn store_last_undo_patch(&self, patch: String) { + let mut state = self.state.lock_unchecked(); + state.last_undo_patch = Some(StoredUndoPatch { patch }); + } + + fn last_undo_patch(&self) -> Option { + self.state.lock_unchecked().last_undo_patch.clone() + } + + fn clear_last_undo_patch(&self) { + self.state.lock_unchecked().last_undo_patch = None; + } + /// Records items to both the rollout and the chat completions/ZDR /// transcript, if enabled. async fn record_conversation_items(&self, items: &[ResponseItem]) { @@ -732,8 +751,7 @@ impl Session { async fn on_exec_command_end( &self, turn_diff_tracker: &mut TurnDiffTracker, - sub_id: &str, - call_id: &str, + context: &ExecCommandContext, output: &ExecToolCallOutput, is_apply_patch: bool, ) { @@ -752,14 +770,14 @@ impl Session { let msg = if is_apply_patch { EventMsg::PatchApplyEnd(PatchApplyEndEvent { - call_id: call_id.to_string(), + call_id: context.call_id.clone(), stdout, stderr, success: *exit_code == 0, }) } else { EventMsg::ExecCommandEnd(ExecCommandEndEvent { - call_id: call_id.to_string(), + call_id: context.call_id.clone(), stdout, stderr, aggregated_output, @@ -770,7 +788,7 @@ impl Session { }; let event = Event { - id: sub_id.to_string(), + id: context.sub_id.clone(), msg, }; let _ = self.tx_event.send(event).await; @@ -778,14 +796,38 @@ impl Session { // If this is an apply_patch, after we emit the end patch, emit a second event // with the full turn diff if there is one. if is_apply_patch { - let unified_diff = turn_diff_tracker.get_unified_diff(); - if let Ok(Some(unified_diff)) = unified_diff { - let msg = EventMsg::TurnDiff(TurnDiffEvent { unified_diff }); - let event = Event { - id: sub_id.into(), - msg, - }; - let _ = self.tx_event.send(event).await; + match turn_diff_tracker.get_unified_diff() { + Ok(Some(unified_diff)) => { + let msg = EventMsg::TurnDiff(TurnDiffEvent { + unified_diff: unified_diff.clone(), + }); + let event = Event { + id: context.sub_id.clone(), + msg, + }; + let _ = self.tx_event.send(event).await; + if *exit_code == 0 { + match turn_diff_tracker.build_undo_patch() { + Ok(Some(patch)) => { + self.store_last_undo_patch(patch); + } + Ok(None) => { + self.clear_last_undo_patch(); + } + Err(error) => { + warn!("failed to prepare undo patch: {error:#}"); + } + } + } + } + Ok(None) => { + if *exit_code == 0 { + self.clear_last_undo_patch(); + } + } + Err(error) => { + warn!("failed to compute unified diff: {error:#}"); + } } } } @@ -800,8 +842,6 @@ impl Session { exec_args: ExecInvokeArgs<'a>, ) -> crate::error::Result { let is_apply_patch = begin_ctx.apply_patch.is_some(); - let sub_id = begin_ctx.sub_id.clone(); - let call_id = begin_ctx.call_id.clone(); self.on_exec_command_begin(turn_diff_tracker, begin_ctx.clone()) .await; @@ -829,14 +869,8 @@ impl Session { &output_stderr } }; - self.on_exec_command_end( - turn_diff_tracker, - &sub_id, - &call_id, - borrowed, - is_apply_patch, - ) - .await; + self.on_exec_command_end(turn_diff_tracker, &begin_ctx, borrowed, is_apply_patch) + .await; result } @@ -864,6 +898,37 @@ impl Session { let _ = self.tx_event.send(event).await; } + async fn undo_last_turn_diff(&self, sub_id: &str) { + let Some(stored_patch) = self.last_undo_patch() else { + self.notify_background_event(sub_id, "No turn diff available to undo.") + .await; + return; + }; + + let mut stdout = Vec::new(); + let mut stderr = Vec::new(); + match codex_apply_patch::apply_patch(&stored_patch.patch, &mut stdout, &mut stderr) { + Ok(()) => { + self.clear_last_undo_patch(); + if stdout.is_empty() { + self.notify_background_event(sub_id, "Reverted last turn diff.") + .await; + } else if let Ok(output) = String::from_utf8(stdout) { + self.notify_background_event(sub_id, output).await; + } + } + Err(error) => { + let mut message = format!("failed to undo turn diff: {error:#}"); + if let Ok(stderr_text) = String::from_utf8(stderr) + && !stderr_text.is_empty() + { + message = format!("{message}\n{stderr_text}"); + } + self.notify_stream_error(sub_id, message).await; + } + } + } + /// Build the full turn input by concatenating the current conversation /// history with additional items for this turn. pub fn turn_input_with_history(&self, extra: Vec) -> Vec { @@ -1141,6 +1206,9 @@ async fn submission_loop( sess.set_task(task); } } + Op::UndoLastTurnDiff => { + sess.undo_last_turn_diff(&sub.id).await; + } Op::UserTurn { items, cwd, diff --git a/codex-rs/core/src/turn_diff_tracker.rs b/codex-rs/core/src/turn_diff_tracker.rs index 2157ed1784..aa94f71030 100644 --- a/codex-rs/core/src/turn_diff_tracker.rs +++ b/codex-rs/core/src/turn_diff_tracker.rs @@ -1,3 +1,4 @@ +use std::collections::BTreeSet; use std::collections::HashMap; use std::fs; use std::path::Path; @@ -249,6 +250,64 @@ impl TurnDiffTracker { } } + pub fn build_undo_patch(&mut self) -> Result> { + let mut delete_paths: BTreeSet = BTreeSet::new(); + let mut add_entries: Vec<(PathBuf, String)> = Vec::new(); + + let mut baseline_file_names: Vec = + self.baseline_file_info.keys().cloned().collect(); + baseline_file_names.sort(); + + for internal in baseline_file_names { + let Some(info) = self.baseline_file_info.get(&internal) else { + continue; + }; + let current_path = self + .get_path_for_internal(&internal) + .unwrap_or(info.path.clone()); + if current_path.exists() { + delete_paths.insert(current_path); + } + + if info.oid.as_str() != ZERO_OID { + let content = String::from_utf8(info.content.clone()).map_err(|_| { + anyhow!( + "undo is not supported for non-UTF8 baseline file {}", + info.path.display() + ) + })?; + add_entries.push((info.path.clone(), content)); + } + } + + if delete_paths.is_empty() && add_entries.is_empty() { + return Ok(None); + } + + add_entries.sort_by(|(left_path, _), (right_path, _)| left_path.cmp(right_path)); + + let mut patch = String::from("*** Begin Patch\n"); + for path in delete_paths { + patch.push_str(&format!("*** Delete File: {}\n", path.display())); + } + + for (path, content) in add_entries { + patch.push_str(&format!("*** Add File: {}\n", path.display())); + if !content.is_empty() { + for line in content.split_terminator('\n') { + patch.push('+'); + patch.push_str(line); + patch.push('\n'); + } + if !content.ends_with('\n') { + patch.push_str("+\n"); + } + } + } + patch.push_str("*** End Patch\n"); + Ok(Some(patch)) + } + fn get_file_diff(&mut self, internal_file_name: &str) -> String { let mut aggregated = String::new(); diff --git a/codex-rs/protocol/src/protocol.rs b/codex-rs/protocol/src/protocol.rs index 6aa9d136bc..386a7477d2 100644 --- a/codex-rs/protocol/src/protocol.rs +++ b/codex-rs/protocol/src/protocol.rs @@ -58,6 +58,9 @@ pub enum Op { items: Vec, }, + /// Undo the most recently applied turn diff using the local git repo. + UndoLastTurnDiff, + /// Similar to [`Op::UserInput`], but contains additional context required /// for a turn of a [`crate::codex_conversation::CodexConversation`]. UserTurn { @@ -1008,6 +1011,7 @@ pub enum TurnAbortReason { #[cfg(test)] mod tests { use super::*; + use pretty_assertions::assert_eq; /// Serialize Event to verify that its JSON representation has the expected /// amount of nesting. diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index dca821f255..627e71b945 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -862,6 +862,10 @@ impl ChatWidget { tx.send(AppEvent::DiffResult(text)); }); } + SlashCommand::Undo => { + self.app_event_tx + .send(AppEvent::CodexOp(Op::UndoLastTurnDiff)); + } SlashCommand::Mention => { self.insert_str("@"); } diff --git a/codex-rs/tui/src/slash_command.rs b/codex-rs/tui/src/slash_command.rs index 3268a92a2d..7c21ab2d47 100644 --- a/codex-rs/tui/src/slash_command.rs +++ b/codex-rs/tui/src/slash_command.rs @@ -18,6 +18,7 @@ pub enum SlashCommand { Init, Compact, Diff, + Undo, Mention, Status, Mcp, @@ -36,6 +37,7 @@ impl SlashCommand { SlashCommand::Compact => "summarize conversation to prevent hitting the context limit", SlashCommand::Quit => "exit Codex", SlashCommand::Diff => "show git diff (including untracked files)", + SlashCommand::Undo => "undo the last turn diff applied by Codex", SlashCommand::Mention => "mention a file", SlashCommand::Status => "show current session configuration and token usage", SlashCommand::Model => "choose what model and reasoning effort to use", @@ -63,6 +65,7 @@ impl SlashCommand { | SlashCommand::Approvals | SlashCommand::Logout => false, SlashCommand::Diff + | SlashCommand::Undo | SlashCommand::Mention | SlashCommand::Status | SlashCommand::Mcp