diff --git a/corgi.toml b/corgi.toml index b2050713d2d..5f14791580a 100644 --- a/corgi.toml +++ b/corgi.toml @@ -69,7 +69,6 @@ gpui = [ "../../assets/fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf", "../../assets/fonts/lilex/Lilex-Regular.ttf", ] -git = ["src/checkpoint.gitignore"] git_ui = ["src/commit_message_prompt.txt"] editor = ["../grammars/src/**"] edit_prediction = ["license_patterns/**"] diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index b57ad43eb0b..bf7d2d25c8c 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -36,10 +36,7 @@ use language::{ use markdown::{Markdown, MarkdownOptions}; pub use mention::*; use project::lsp_store::{FormatTrigger, LspFormatTarget}; -use project::{ - AgentLocation, Project, - git_store::{GitStoreCheckpoint, GitStoreEvent, RepositoryEvent}, -}; +use project::{AgentLocation, Project}; use serde::{Deserialize, Serialize}; use serde_json::to_string_pretty; use settings::{Settings, SettingsStore}; @@ -342,7 +339,6 @@ pub struct UserMessage { pub client_id: Option, pub is_optimistic: bool, pub content: MessageContent, - pub checkpoint: Option, pub indented: bool, } @@ -362,24 +358,10 @@ pub enum MessageKind { Session, } -#[derive(Debug)] -pub struct Checkpoint { - git_checkpoint: GitStoreCheckpoint, - pub show: bool, -} - impl UserMessage { fn to_markdown(&self, cx: &App) -> String { let mut markdown = String::new(); - if self - .checkpoint - .as_ref() - .is_some_and(|checkpoint| checkpoint.show) - { - writeln!(markdown, "## User (checkpoint)").unwrap(); - } else { - writeln!(markdown, "## User").unwrap(); - } + writeln!(markdown, "## User").unwrap(); writeln!(markdown).unwrap(); writeln!(markdown, "{}", self.content.to_markdown(cx)).unwrap(); writeln!(markdown).unwrap(); @@ -3544,8 +3526,6 @@ pub struct AcpThread { visible_plan: Option, project: Entity, action_log: Entity, - _git_store_subscription: Subscription, - update_last_checkpoint_if_changed_task: Option>>, shared_buffers: HashMap, BufferSnapshot>, turn_id: u32, running_turn: Option, @@ -3881,21 +3861,6 @@ impl AcpThread { | AcpThreadEvent::WorkingDirectoriesUpdated => {} }); - let git_store = project.read(cx).git_store().clone(); - let _git_store_subscription = cx.subscribe(&git_store, |this, _, event, cx| { - if matches!( - event, - GitStoreEvent::RepositoryUpdated( - _, - RepositoryEvent::StatusesChanged | RepositoryEvent::HeadChanged, - _ - ) - ) { - this.update_last_checkpoint_if_changed_task = - Some(this.update_last_checkpoint_if_changed(cx)); - } - }); - let receipt_submissions = connection.receipt_submissions(&session_id, cx); Self { parent_session_id, @@ -3908,8 +3873,6 @@ impl AcpThread { meta: None, }, action_log, - _git_store_subscription, - update_last_checkpoint_if_changed_task: None, shared_buffers: Default::default(), entries: Default::default(), notices: Vec::new(), @@ -4166,8 +4129,7 @@ impl AcpThread { self.connection.truncate(self.session_id(), cx).is_some() } - /// Gates editing and restoring user messages, and whether sending one takes - /// a git checkpoint, which only the "Restore Checkpoint" button consumes. + /// Gates editing user messages and rewinding the thread to them. pub fn can_rewind_to(&self, client_id: Option<&ClientUserMessageId>, cx: &App) -> bool { client_id.is_some() && self.parent_session_id.is_none() && self.supports_truncate(cx) } @@ -5206,7 +5168,6 @@ impl AcpThread { client_id: None, is_optimistic: false, content: MessageContent::default(), - checkpoint: None, indented: false, })); Ok(MessageLocation::User { entry_index }) @@ -5368,7 +5329,6 @@ impl AcpThread { client_id: incoming_client_id, is_optimistic, content, - checkpoint: None, indented, }), cx, @@ -7008,61 +6968,9 @@ impl AcpThread { Ok(()) } - pub fn prepare_local_prompt( - &mut self, - id: ClientUserMessageId, - content: Vec, - cx: &mut Context, - ) -> Result> { - let should_checkpoint = !content.is_empty() && self.can_rewind_to(Some(&id), cx); - self.upsert_local_user_message(id.clone(), content, cx)?; - if !should_checkpoint { - return Ok(Task::ready(())); - } - - let git_store = self.project.read(cx).git_store().clone(); - let checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx)); - Ok(cx.spawn(async move |this, cx| { - let checkpoint = checkpoint - .await - .context("failed to get old checkpoint") - .log_err(); - this.update(cx, |this, cx| { - let identity = MessageIdentity::Keyed(id.message_id()); - if let Some((index, message)) = - this.entries - .iter_mut() - .enumerate() - .find_map(|(index, entry)| match entry { - AgentThreadEntry::UserMessage(message) - if message.identity == identity => - { - Some((index, message)) - } - _ => None, - }) - { - message.checkpoint = checkpoint.map(|git_checkpoint| Checkpoint { - git_checkpoint, - show: false, - }); - cx.emit(AcpThreadEvent::EntryUpdated(index)); - } - }) - .log_err(); - })) - } - - pub fn finish_local_turn( - &mut self, - reason: acp_v2::StopReason, - cx: &mut Context, - ) -> Task> { - // Capture the checkpoint target before refusal cleanup can remove its message. - let checkpoint = self.update_last_checkpoint(cx); + pub fn finish_local_turn(&mut self, reason: acp_v2::StopReason, cx: &mut Context) { self.flush_streaming_text(cx); self.cleanup_local_turn(&reason, true, cx); - checkpoint } pub fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> { @@ -7086,13 +6994,10 @@ impl AcpThread { for chunk in &request.prompt { block.append_prompt(chunk.clone(), &language_registry, path_style, cx); } - let git_store = self.project.read(cx).git_store().clone(); - let client_user_message_ids = self.connection.client_user_message_ids(cx); let client_id = client_user_message_ids .as_ref() .map(|client_user_message_ids| client_user_message_ids.new_id()); - let should_checkpoint = self.can_rewind_to(client_id.as_ref(), cx); self.run_turn(id, cx, async move |this, cx| { if push_user_message { @@ -7104,30 +7009,12 @@ impl AcpThread { client_id: client_id.clone(), is_optimistic: true, content: block, - checkpoint: None, indented: false, }), cx, ); }) .ok(); - - if should_checkpoint { - let old_checkpoint = git_store - .update(cx, |git, cx| git.checkpoint(cx)) - .await - .context("failed to get old checkpoint") - .log_err(); - this.update(cx, |this, _cx| { - if let Some((_ix, message)) = this.last_user_message() { - message.checkpoint = old_checkpoint.map(|git_checkpoint| Checkpoint { - git_checkpoint, - show: false, - }); - } - }) - .ok(); - } } this.update(cx, |this, cx| { @@ -7233,16 +7120,6 @@ impl AcpThread { let completion = async move |thread: WeakEntity, cx: &mut AsyncApp| { let response = rx.await; - thread - .update(cx, |this, cx| { - if this.turn_id == turn_id { - this.update_last_checkpoint(cx) - } else { - Task::ready(Ok(())) - } - })? - .await?; - thread.update(cx, |this, cx| { if this.turn_id == turn_id && this.parent_session_id.is_none() { this.project @@ -7589,42 +7466,8 @@ impl AcpThread { } } - /// Restores the git working tree to the state at the given checkpoint (if one exists) - pub fn restore_checkpoint( - &mut self, - client_id: ClientUserMessageId, - cx: &mut Context, - ) -> Task> { - let Some((_, message)) = self.user_message_mut(&client_id) else { - return Task::ready(Err(anyhow!("message not found"))); - }; - - let checkpoint = message - .checkpoint - .as_ref() - .map(|c| c.git_checkpoint.clone()); - - // Cancel any in-progress generation before restoring - let cancel_task = self.cancel(cx); - let git_store = self.project.read(cx).git_store().clone(); - - cx.spawn(async move |this, cx| { - cancel_task.await?; - this.update(cx, |this, cx| this.rewind(client_id, cx))? - .await?; - if let Some(checkpoint) = checkpoint { - git_store - .update(cx, |git, cx| git.restore_checkpoint(checkpoint, cx)) - .await?; - } - - Ok(()) - }) - } - /// Rewinds this thread to before the entry at `index`, removing it and all /// subsequent entries while rejecting any action_log changes made from that point. - /// Unlike `restore_checkpoint`, this method does not restore from git. pub fn rewind( &mut self, client_id: ClientUserMessageId, @@ -7670,124 +7513,6 @@ impl AcpThread { }) } - fn update_last_checkpoint_if_changed(&mut self, cx: &mut Context) -> Task> { - if !self.foreground_activity().is_active() { - return Task::ready(Ok(())); - } - let activity_generation = self.activity_generation(); - - let git_store = self.project.read(cx).git_store().clone(); - - let Some((client_id, checkpoint)) = self.last_user_message().and_then(|(_, message)| { - let id = message.client_id.clone()?; - let checkpoint = message.checkpoint.as_ref()?; - Some((id, checkpoint)) - }) else { - return Task::ready(Ok(())); - }; - if checkpoint.show { - return Task::ready(Ok(())); - } - let old_checkpoint = checkpoint.git_checkpoint.clone(); - - let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx)); - cx.spawn(async move |this, cx| { - let Some(new_checkpoint) = new_checkpoint - .await - .context("failed to get new checkpoint") - .log_err() - else { - return Ok(()); - }; - - let Some(equal) = git_store - .update(cx, |git, cx| { - git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx) - }) - .await - .context("failed to compare checkpoints") - .log_err() - else { - return Ok(()); - }; - - if equal { - return Ok(()); - } - - this.update(cx, |this, cx| { - if !this.foreground_activity().is_active() - || this.activity_generation() != activity_generation - { - return; - } - - let Some((ix, message)) = this.last_user_message() else { - return; - }; - if message.client_id.as_ref() != Some(&client_id) { - return; - } - if let Some(checkpoint) = message.checkpoint.as_mut() - && !checkpoint.show - { - checkpoint.show = true; - cx.emit(AcpThreadEvent::EntryUpdated(ix)); - } - })?; - - Ok(()) - }) - } - - fn update_last_checkpoint(&mut self, cx: &mut Context) -> Task> { - let git_store = self.project.read(cx).git_store().clone(); - - let Some((_, message)) = self.last_user_message() else { - return Task::ready(Ok(())); - }; - let Some(client_id) = message.client_id.clone() else { - return Task::ready(Ok(())); - }; - let Some(checkpoint) = message.checkpoint.as_ref() else { - return Task::ready(Ok(())); - }; - let old_checkpoint = checkpoint.git_checkpoint.clone(); - - let new_checkpoint = git_store.update(cx, |git, cx| git.checkpoint(cx)); - cx.spawn(async move |this, cx| { - let Some(new_checkpoint) = new_checkpoint - .await - .context("failed to get new checkpoint") - .log_err() - else { - return Ok(()); - }; - - let Some(equal) = git_store - .update(cx, |git, cx| { - git.compare_checkpoints(old_checkpoint.clone(), new_checkpoint, cx) - }) - .await - .context("failed to compare checkpoints") - .log_err() - else { - return Ok(()); - }; - - this.update(cx, |this, cx| { - if let Some((ix, message)) = this.user_message_mut(&client_id) { - if let Some(checkpoint) = message.checkpoint.as_mut() { - checkpoint.show = !equal; - cx.emit(AcpThreadEvent::EntryUpdated(ix)); - } - } - })?; - - Ok(()) - }) - } - fn last_user_message(&mut self) -> Option<(usize, &mut UserMessage)> { self.entries .iter_mut() @@ -8456,7 +8181,7 @@ mod tests { use gpui::UpdateGlobal as _; use gpui::{App, AsyncApp, TaskExt as _, TestAppContext, WeakEntity}; use indoc::indoc; - use project::{AgentId, FakeFs, Fs, RemoveOptions}; + use project::{AgentId, FakeFs}; use rand::{distr, prelude::*}; use serde_json::json; use settings::SettingsStore; @@ -8465,7 +8190,7 @@ mod tests { cell::RefCell, path::Path, rc::Rc, - sync::atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst}, + sync::atomic::{AtomicBool, Ordering::SeqCst}, time::Duration, }; use util::{path, path_list::PathList}; @@ -12258,10 +11983,9 @@ mod tests { let source = vec!["local prompt".into()]; thread .update(cx, |thread, cx| { - thread.prepare_local_prompt(id.clone(), vec!["initial".into()], cx) + thread.upsert_local_user_message(id.clone(), vec!["initial".into()], cx) }) - .expect("synchronous local insertion") - .await; + .expect("synchronous local insertion"); thread.update(cx, |thread, cx| { thread .upsert_assistant_message( @@ -12272,16 +11996,14 @@ mod tests { }); thread .update(cx, |thread, cx| { - thread.prepare_local_prompt(ClientUserMessageId::new(), Vec::new(), cx) + thread.upsert_local_user_message(ClientUserMessageId::new(), Vec::new(), cx) }) - .expect("empty command marker") - .await; + .expect("empty command marker"); thread .update(cx, |thread, cx| { - thread.prepare_local_prompt(id.clone(), source.clone(), cx) + thread.upsert_local_user_message(id.clone(), source.clone(), cx) }) - .expect("replace exact keyed local message") - .await; + .expect("replace exact keyed local message"); let submission = thread.update(cx, |thread, cx| { thread.submit_receipt( source.clone(), @@ -12355,15 +12077,12 @@ mod tests { .expect("generic permission before local failure") }); let original_error = Arc::new(anyhow!(MaxOutputTokensError)); - thread - .update(cx, |thread, cx| { - thread.finish_local_turn( - acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new()), - cx, - ) - }) - .await - .expect("local cleanup"); + thread.update(cx, |thread, cx| { + thread.finish_local_turn( + acp_v2::StopReason::Error(acp_v2::ErrorStopReason::new()), + cx, + ) + }); assert!(stops.borrow().is_empty()); assert!(matches!( permission.await, @@ -12486,134 +12205,6 @@ mod tests { }); } - #[gpui::test] - async fn test_local_checkpoints_target_exact_message_and_activity_generation( - cx: &mut TestAppContext, - ) { - init_test(cx); - let fs = FakeFs::new(cx.executor()); - fs.insert_tree(path!("/test"), json!({".git": {}})).await; - let project = Project::test(fs, [Path::new(path!("/test"))], cx).await; - let connection = Rc::new(StubAgentConnection::new().with_receipt_submissions(true)); - let thread = cx - .update(|cx| { - connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx) - }) - .await - .expect("local checkpoint thread"); - cx.run_until_parked(); - let id = ClientUserMessageId::new(); - let marker_id = ClientUserMessageId::new(); - let preparation = thread - .update(cx, |thread, cx| { - thread.prepare_local_prompt(id.clone(), vec!["source".into()], cx) - }) - .expect("prepare source"); - thread - .update(cx, |thread, cx| { - thread.prepare_local_prompt(marker_id.clone(), Vec::new(), cx) - }) - .expect("interleaved hidden marker") - .await; - preparation.await; - thread.update(cx, |thread, cx| { - assert!( - thread - .user_message_mut(&id) - .expect("source") - .1 - .checkpoint - .is_some() - ); - assert!( - thread - .user_message_mut(&marker_id) - .expect("marker") - .1 - .checkpoint - .is_none() - ); - thread.truncate_entries(1, cx); - thread - .update_session_state( - acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()), - cx, - ) - .expect("reported running without legacy turn"); - assert!(thread.running_turn.is_none()); - }); - thread - .update(cx, |thread, cx| { - thread.write_text_file(PathBuf::from(path!("/test/file.txt")), "after".into(), cx) - }) - .await - .expect("local edit"); - cx.run_until_parked(); - let stale_checkpoint = thread.update(cx, |thread, cx| { - let checkpoint = thread - .user_message_mut(&id) - .expect("source") - .1 - .checkpoint - .as_mut() - .expect("checkpoint"); - assert!(checkpoint.show, "reported edit must reveal checkpoint"); - checkpoint.show = false; - let stale_checkpoint = thread.update_last_checkpoint_if_changed(cx); - thread - .update_session_state( - acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()), - cx, - ) - .expect("old activity ends"); - thread - .update_session_state( - acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()), - cx, - ) - .expect("successor activity"); - stale_checkpoint - }); - stale_checkpoint.await.expect("stale checkpoint completes"); - thread.update(cx, |thread, _| { - assert!( - !thread - .user_message_mut(&id) - .expect("source") - .1 - .checkpoint - .as_ref() - .expect("checkpoint") - .show - ); - }); - thread - .update(cx, |thread, cx| { - thread.finish_local_turn(acp_v2::StopReason::EndTurn, cx) - }) - .await - .expect("local final checkpoint"); - thread.update(cx, |thread, cx| { - assert!( - thread - .user_message_mut(&id) - .expect("source") - .1 - .checkpoint - .as_ref() - .expect("checkpoint") - .show - ); - assert_eq!(thread.foreground_activity(), ForegroundActivity::Running); - thread - .update_session_state( - acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()), - cx, - ) - .expect("driver finishes"); - }); - } - #[gpui::test] async fn test_local_refusal_reports_one_stop(cx: &mut TestAppContext) { init_test(cx); @@ -12632,7 +12223,7 @@ mod tests { } }) }); - let finish = thread.update(cx, |thread, cx| { + thread.update(cx, |thread, cx| { thread .upsert_local_user_message(ClientUserMessageId::new(), vec!["prompt".into()], cx) .expect("accepted local message"); @@ -12644,7 +12235,6 @@ mod tests { .expect("running"); thread.finish_local_turn(acp_v2::StopReason::Refusal, cx) }); - finish.await.expect("local cleanup"); assert!(events.borrow().is_empty()); thread.update(cx, |thread, cx| { assert!(thread.entries().is_empty()); @@ -19231,449 +18821,6 @@ mod tests { assert!(cx.read(|cx| !thread.read(cx).has_pending_edit_tool_calls())); } - #[gpui::test(iterations = 10)] - async fn test_checkpoints(cx: &mut TestAppContext) { - init_test(cx); - let fs = FakeFs::new(cx.background_executor.clone()); - fs.insert_tree( - path!("/test"), - json!({ - ".git": {} - }), - ) - .await; - let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await; - - let simulate_changes = Arc::new(AtomicBool::new(true)); - let next_filename = Arc::new(AtomicUsize::new(0)); - let connection = Rc::new(FakeAgentConnection::new().on_user_message({ - let simulate_changes = simulate_changes.clone(); - let next_filename = next_filename.clone(); - let fs = fs.clone(); - move |request, thread, mut cx| { - let fs = fs.clone(); - let simulate_changes = simulate_changes.clone(); - let next_filename = next_filename.clone(); - async move { - if simulate_changes.load(SeqCst) { - let filename = format!("/test/file-{}", next_filename.fetch_add(1, SeqCst)); - fs.write(Path::new(&filename), b"").await?; - } - - let acp_v2::ContentBlock::Text(content) = &request.prompt[0] else { - panic!("expected text content block"); - }; - thread.update(&mut cx, |thread, cx| { - thread - .handle_session_update( - acp_v1::SessionUpdate::AgentMessageChunk( - acp_v1::ContentChunk::new(content.text.to_uppercase().into()), - ), - cx, - ) - .unwrap(); - })?; - Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) - } - .boxed_local() - } - })); - let thread = cx - .update(|cx| { - connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx) - }) - .await - .unwrap(); - - cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["Lorem".into()], cx))) - .await - .unwrap(); - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User (checkpoint) - - Lorem - - ## Assistant - - LOREM - - "} - ); - }); - assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]); - - cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["ipsum".into()], cx))) - .await - .unwrap(); - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User (checkpoint) - - Lorem - - ## Assistant - - LOREM - - ## User (checkpoint) - - ipsum - - ## Assistant - - IPSUM - - "} - ); - }); - assert_eq!( - fs.files(), - vec![ - Path::new(path!("/test/file-0")), - Path::new(path!("/test/file-1")) - ] - ); - - // Checkpoint isn't stored when there are no changes. - simulate_changes.store(false, SeqCst); - cx.update(|cx| thread.update(cx, |thread, cx| thread.send(vec!["dolor".into()], cx))) - .await - .unwrap(); - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User (checkpoint) - - Lorem - - ## Assistant - - LOREM - - ## User (checkpoint) - - ipsum - - ## Assistant - - IPSUM - - ## User - - dolor - - ## Assistant - - DOLOR - - "} - ); - }); - assert_eq!( - fs.files(), - vec![ - Path::new(path!("/test/file-0")), - Path::new(path!("/test/file-1")) - ] - ); - - // Rewinding the conversation truncates the history and restores the checkpoint. - thread - .update(cx, |thread, cx| { - let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else { - panic!("unexpected entries {:?}", thread.entries) - }; - thread.restore_checkpoint(message.client_id.clone().unwrap(), cx) - }) - .await - .unwrap(); - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User (checkpoint) - - Lorem - - ## Assistant - - LOREM - - "} - ); - }); - assert_eq!(fs.files(), vec![Path::new(path!("/test/file-0"))]); - } - - #[gpui::test(iterations = 10)] - async fn test_checkpoint_shows_when_file_changes_during_pending_message( - cx: &mut TestAppContext, - ) { - init_test(cx); - let fs = FakeFs::new(cx.background_executor.clone()); - fs.insert_tree( - path!("/test"), - json!({ - ".git": {} - }), - ) - .await; - let project = Project::test(fs, [path!("/test").as_ref()], cx).await; - - let (request_started_tx, request_started_rx) = oneshot::channel::<()>(); - let request_started_tx = Rc::new(RefCell::new(Some(request_started_tx))); - let (write_file_tx, write_file_rx) = oneshot::channel::<()>(); - let write_file_rx = Rc::new(RefCell::new(Some(write_file_rx))); - let (file_written_tx, file_written_rx) = oneshot::channel::<()>(); - let file_written_tx = Rc::new(RefCell::new(Some(file_written_tx))); - let (finish_response_tx, finish_response_rx) = oneshot::channel::<()>(); - let finish_response_tx = Rc::new(RefCell::new(Some(finish_response_tx))); - let finish_response_rx = Rc::new(RefCell::new(Some(finish_response_rx))); - let connection = Rc::new(FakeAgentConnection::new().on_user_message({ - let request_started_tx = request_started_tx.clone(); - let write_file_rx = write_file_rx.clone(); - let file_written_tx = file_written_tx.clone(); - let finish_response_rx = finish_response_rx.clone(); - move |_request, thread, mut cx| { - let write_file_rx = write_file_rx.borrow_mut().take(); - let finish_response_rx = finish_response_rx.borrow_mut().take(); - let request_started_tx = request_started_tx.borrow_mut().take(); - let file_written_tx = file_written_tx.borrow_mut().take(); - async move { - if let Some(request_started_tx) = request_started_tx { - request_started_tx.send(()).ok(); - } - if let Some(write_file_rx) = write_file_rx { - write_file_rx.await.ok(); - } - - thread - .update(&mut cx, |thread, cx| { - thread.write_text_file( - PathBuf::from(path!("/test/file")), - String::new(), - cx, - ) - })? - .await?; - - if let Some(file_written_tx) = file_written_tx { - file_written_tx.send(()).ok(); - } - if let Some(finish_response_rx) = finish_response_rx { - finish_response_rx.await.ok(); - } - - Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) - } - .boxed_local() - } - })); - let thread = cx - .update(|cx| { - connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx) - }) - .await - .unwrap(); - - let send = thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)); - let send_task = cx.background_executor.spawn(send); - request_started_rx.await.unwrap(); - cx.run_until_parked(); - - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User - - hello - - "} - ); - }); - - write_file_tx.send(()).ok(); - file_written_rx.await.unwrap(); - cx.run_until_parked(); - - thread.read_with(cx, |thread, cx| { - assert_eq!( - thread.to_markdown(cx), - indoc! {" - ## User (checkpoint) - - hello - - "} - ); - }); - - finish_response_tx - .borrow_mut() - .take() - .unwrap() - .send(()) - .ok(); - send_task.await.unwrap(); - } - - #[gpui::test] - async fn test_no_checkpoints_when_restore_is_unavailable(cx: &mut TestAppContext) { - init_test(cx); - let fs = FakeFs::new(cx.background_executor.clone()); - fs.insert_tree( - path!("/test"), - json!({ - ".git": {} - }), - ) - .await; - let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await; - let checkpoint_jobs = |cx: &mut TestAppContext| { - project.read_with(cx, |project, cx| { - let repository = project.git_store().read(cx).active_repository().unwrap(); - let queue = repository.read(cx).job_debug_queue().to_debug_value(); - queue["entries"] - .as_array() - .unwrap() - .iter() - .filter(|job| job["description"] == "checkpoint") - .count() - }) - }; - - let next_filename = Arc::new(AtomicUsize::new(0)); - let finish_turn_rx_slot = Rc::new(RefCell::new(None::>)); - let write_file_on_prompt = { - let fs = fs.clone(); - let finish_turn_rx_slot = finish_turn_rx_slot.clone(); - move |_request: acp_v2::PromptRequest, - _thread: WeakEntity, - _cx: AsyncApp| - -> LocalBoxFuture<'static, Result> { - let fs = fs.clone(); - let path = Path::new(path!("/test")) - .join(format!("file-{}", next_filename.fetch_add(1, SeqCst))); - let finish_turn_rx = finish_turn_rx_slot.borrow_mut().take(); - async move { - fs.write(&path, b"").await?; - if let Some(finish_turn_rx) = finish_turn_rx { - finish_turn_rx.await.ok(); - } - Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) - } - .boxed_local() - } - }; - - let connection = Rc::new( - FakeAgentConnection::new() - .without_truncate_support() - .on_user_message(write_file_on_prompt.clone()), - ); - let thread_without_truncate = cx - .update(|cx| { - connection.new_session( - project.clone(), - PathList::new(&[Path::new(path!("/test"))]), - cx, - ) - }) - .await - .unwrap(); - - let connection = Rc::new(FakeAgentConnection::new().on_user_message(write_file_on_prompt)); - let parent = cx - .update(|cx| { - connection.clone().new_session( - project.clone(), - PathList::new(&[Path::new(path!("/test"))]), - cx, - ) - }) - .await - .unwrap(); - let subagent_session_id = acp_v2::SessionId::new("subagent"); - let subagent = cx.update(|cx| { - let action_log = cx.new(|_| ActionLog::new(project.clone())); - cx.new(|cx| { - AcpThread::new( - Some(parent.read(cx).session_id().clone()), - None, - None, - connection.clone(), - project.clone(), - action_log, - subagent_session_id.clone(), - watch::Receiver::constant(acp_v2::PromptCapabilities::new()), - cx, - ) - }) - }); - connection - .sessions - .lock() - .insert(subagent_session_id, subagent.downgrade()); - - // The parent shows that sending, repository updates during the turn, and - // turn completion each take checkpoints, so zero counts elsewhere mean - // those paths ran without taking any. - for (thread, can_rewind) in [ - (thread_without_truncate, false), - (subagent, false), - (parent, true), - ] { - assert_eq!( - thread.read_with(cx, |thread, cx| { - thread.can_rewind_to(Some(&ClientUserMessageId::new()), cx) - }), - can_rewind - ); - let jobs_before_send = checkpoint_jobs(cx); - let (finish_turn_tx, finish_turn_rx) = oneshot::channel(); - finish_turn_rx_slot.replace(Some(finish_turn_rx)); - let send = thread.update(cx, |thread, cx| thread.send(vec!["hello".into()], cx)); - let send_task = cx.background_executor.spawn(send); - cx.run_until_parked(); - - assert!(thread.read_with(cx, |thread, _| thread.running_turn.is_some())); - let jobs_while_running = checkpoint_jobs(cx); - finish_turn_tx.send(()).ok(); - send_task.await.unwrap(); - cx.run_until_parked(); - let jobs_after_turn = checkpoint_jobs(cx); - - if can_rewind { - assert_eq!(jobs_while_running, jobs_before_send + 2); - assert_eq!(jobs_after_turn, jobs_while_running + 1); - } else { - assert_eq!(jobs_while_running, jobs_before_send); - assert_eq!(jobs_after_turn, jobs_before_send); - } - thread.read_with(cx, |thread, _| { - let AgentThreadEntry::UserMessage(message) = &thread.entries[0] else { - panic!("unexpected entries {:?}", thread.entries) - }; - assert_eq!(message.checkpoint.is_some(), can_rewind); - }); - } - assert_eq!( - fs.files(), - vec![ - Path::new(path!("/test/file-0")), - Path::new(path!("/test/file-1")), - Path::new(path!("/test/file-2")) - ] - ); - } - #[gpui::test] async fn test_tool_result_refusal(cx: &mut TestAppContext) { use std::sync::atomic::AtomicUsize; @@ -21628,14 +20775,13 @@ mod tests { }); } - /// Tests that restoring a checkpoint properly cleans up terminals that were - /// created after that checkpoint, and cancels any in-progress generation. + /// Tests that rewinding properly cleans up terminals that were created after + /// the message being rewound to. /// - /// Reproduces issue #35142: When a checkpoint is restored, any terminal processes - /// that were started after that checkpoint should be terminated, and any in-progress - /// AI generation should be canceled. + /// Reproduces issue #35142: When the thread is rewound, any terminal processes + /// that were started after that message should be terminated. #[gpui::test] - async fn test_restore_checkpoint_kills_terminal(cx: &mut TestAppContext) { + async fn test_rewind_kills_terminal(cx: &mut TestAppContext) { init_test(cx); let fs = FakeFs::new(cx.executor()); @@ -21648,7 +20794,7 @@ mod tests { .await .unwrap(); - // Send first user message to create a checkpoint + // Send first user message cx.update(|cx| { thread.update(cx, |thread, cx| { thread.send(vec!["first message".into()], cx) @@ -21657,7 +20803,7 @@ mod tests { .await .unwrap(); - // Send second message (creates another checkpoint) - we'll restore to this one + // Send second message - we'll rewind to this one cx.update(|cx| { thread.update(cx, |thread, cx| { thread.send(vec!["second message".into()], cx) @@ -21666,7 +20812,7 @@ mod tests { .await .unwrap(); - // Create 2 terminals BEFORE the checkpoint that have completed running + // Create 2 terminals BEFORE the second message that have completed running let terminal_id_1 = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string()); let mock_terminal_1 = cx.new(|cx| { let builder = ::terminal::TerminalBuilder::new_display_only( @@ -21759,11 +20905,11 @@ mod tests { ); }); - // Get the second message ID to restore to + // Get the second message ID to rewind to let second_message_id = thread.read_with(cx, |thread, _| { // At this point we have: - // - Index 0: First user message (with checkpoint) - // - Index 1: Second user message (with checkpoint) + // - Index 0: First user message + // - Index 1: Second user message // No assistant responses because FakeAgentConnection just returns EndTurn let AgentThreadEntry::UserMessage(message) = &thread.entries[1] else { panic!("expected user message at index 1"); @@ -21771,7 +20917,7 @@ mod tests { message.client_id.clone().unwrap() }); - // Create a terminal AFTER the checkpoint we'll restore to. + // Create a terminal AFTER the message we'll rewind to. // This simulates the AI agent starting a long-running terminal command. let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string()); let mock_terminal = cx.new(|cx| { @@ -21838,7 +20984,7 @@ mod tests { thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id)); assert!( terminal_exists_before, - "Terminal should exist before checkpoint restore" + "Terminal should exist before rewind" ); // Verify the terminal's underlying task is still running (not completed) @@ -21850,49 +20996,37 @@ mod tests { }); assert!( terminal_running_before, - "Terminal should be running before checkpoint restore" + "Terminal should be running before rewind" ); // Verify we have the expected entries before restore let entry_count_before = thread.read_with(cx, |thread, _| thread.entries.len()); assert!( entry_count_before > 1, - "Should have multiple entries before restore" + "Should have multiple entries before rewind" ); - // Restore the checkpoint to the second message. - // This should: - // 1. Cancel any in-progress generation (via the cancel() call) - // 2. Remove the terminal that was created after that point + // Rewinding to the second message should remove the terminal that was + // created after that point. thread - .update(cx, |thread, cx| { - thread.restore_checkpoint(second_message_id, cx) - }) + .update(cx, |thread, cx| thread.rewind(second_message_id, cx)) .await .unwrap(); - // Verify that no send_task is in progress after restore - // (cancel() clears the send_task) - let has_send_task_after = thread.read_with(cx, |thread, _| thread.running_turn.is_some()); - assert!( - !has_send_task_after, - "Should not have a send_task after restore (cancel should have cleared it)" - ); - - // Verify the entries were truncated (restoring to index 1 truncates at 1, keeping only index 0) + // Verify the entries were truncated (rewinding to index 1 truncates at 1, keeping only index 0) let entry_count = thread.read_with(cx, |thread, _| thread.entries.len()); assert_eq!( entry_count, 1, - "Should have 1 entry after restore (only the first user message)" + "Should have 1 entry after rewind (only the first user message)" ); - // Verify the 2 completed terminals from before the checkpoint still exist + // Verify the 2 completed terminals from before the second message still exist let terminal_1_exists = thread.read_with(cx, |thread, _| { thread.terminals.contains_key(&terminal_id_1) }); assert!( terminal_1_exists, - "Terminal 1 (from before checkpoint) should still exist" + "Terminal 1 (from before the second message) should still exist" ); let terminal_2_exists = thread.read_with(cx, |thread, _| { @@ -21900,7 +21034,7 @@ mod tests { }); assert!( terminal_2_exists, - "Terminal 2 (from before checkpoint) should still exist" + "Terminal 2 (from before the second message) should still exist" ); // Verify they're still in completed state @@ -21916,176 +21050,22 @@ mod tests { }); assert!(terminal_2_completed, "Terminal 2 should still be completed"); - // Verify the running terminal (created after checkpoint) was removed + // Verify the running terminal (created after the second message) was removed let terminal_3_exists = thread.read_with(cx, |thread, _| thread.terminals.contains_key(&terminal_id)); assert!( !terminal_3_exists, - "Terminal 3 (created after checkpoint) should have been removed" + "Terminal 3 (created after the second message) should have been removed" ); - // Verify total count is 2 (the two from before the checkpoint) + // Verify total count is 2 (the two from before the second message) let terminal_count = thread.read_with(cx, |thread, _| thread.terminals.len()); assert_eq!( terminal_count, 2, - "Should have exactly 2 terminals (the completed ones from before checkpoint)" + "Should have exactly 2 terminals (the completed ones from before the second message)" ); } - /// Tests that update_last_checkpoint correctly updates the original message's checkpoint - /// even when a new user message is added while the async checkpoint comparison is in progress. - /// - /// This is a regression test for a bug where update_last_checkpoint would fail with - /// "no checkpoint" if a new user message (without a checkpoint) was added between when - /// update_last_checkpoint started and when its async closure ran. - #[gpui::test] - async fn test_update_last_checkpoint_with_new_message_added(cx: &mut TestAppContext) { - init_test(cx); - - let fs = FakeFs::new(cx.executor()); - fs.insert_tree(path!("/test"), json!({".git": {}, "file.txt": "content"})) - .await; - let project = Project::test(fs.clone(), [Path::new(path!("/test"))], cx).await; - - let handler_done = Arc::new(AtomicBool::new(false)); - let handler_done_clone = handler_done.clone(); - let connection = Rc::new(FakeAgentConnection::new().on_user_message( - move |_, _thread, _cx| { - handler_done_clone.store(true, SeqCst); - async move { Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) } - .boxed_local() - }, - )); - - let thread = cx - .update(|cx| { - connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx) - }) - .await - .unwrap(); - - let send_future = thread.update(cx, |thread, cx| thread.send_raw("First message", cx)); - let send_task = cx.background_executor.spawn(send_future); - - // Tick until handler completes, then a few more to let update_last_checkpoint start - while !handler_done.load(SeqCst) { - cx.executor().tick(); - } - for _ in 0..5 { - cx.executor().tick(); - } - - thread.update(cx, |thread, cx| { - let languages = thread.project.read(cx).languages().clone(); - let path_style = thread.project.read(cx).path_style(cx); - let content = MessageContent::new( - "Injected message (no checkpoint)".into(), - &languages, - path_style, - cx, - ); - thread.push_entry( - AgentThreadEntry::UserMessage(UserMessage { - identity: MessageIdentity::Legacy(None), - meta: None, - client_id: Some(ClientUserMessageId::new()), - is_optimistic: true, - content, - checkpoint: None, - indented: false, - }), - cx, - ); - }); - - cx.run_until_parked(); - let result = send_task.await; - - assert!( - result.is_ok(), - "send should succeed even when new message added during update_last_checkpoint: {:?}", - result.err() - ); - } - - /// This is a regression test for a bug where update_last_checkpoint would - /// swallow a checkpoint comparison error and hide an already-visible - /// "Restore checkpoint" button without logging anything. - #[gpui::test] - async fn test_update_last_checkpoint_compare_error_keeps_checkpoint_visible( - cx: &mut TestAppContext, - ) { - init_test(cx); - - let fs = FakeFs::new(cx.executor()); - fs.insert_tree(path!("/test"), json!({".git": {}, "file.txt": "content"})) - .await; - let project = Project::test(fs.clone(), [Path::new(path!("/test"))], cx).await; - - // The handler waits for this signal so the repository can be swapped - // out while the turn is still running. - let (complete_tx, complete_rx) = futures::channel::oneshot::channel::<()>(); - let complete_rx = RefCell::new(Some(complete_rx)); - let connection = Rc::new(FakeAgentConnection::new().on_user_message( - move |_, _thread, _cx| { - let complete_rx = complete_rx.borrow_mut().take(); - async move { - if let Some(rx) = complete_rx { - rx.await.ok(); - } - Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) - } - .boxed_local() - }, - )); - - let thread = cx - .update(|cx| { - connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx) - }) - .await - .unwrap(); - - let send_future = thread.update(cx, |thread, cx| thread.send_raw("message", cx)); - let send_task = cx.background_executor.spawn(send_future); - cx.run_until_parked(); - - // Show the checkpoint, as update_last_checkpoint_if_changed does when - // files change during the turn. - thread.update(cx, |thread, _| { - let (_, message) = thread.last_user_message().unwrap(); - message.checkpoint.as_mut().unwrap().show = true; - }); - - // Recreate `.git` so the git store reopens the repository. The fresh - // fake repository doesn't contain the checkpoint recorded at send - // time, so the end-of-turn comparison fails. - fs.remove_dir( - Path::new(path!("/test/.git")), - RemoveOptions { - recursive: true, - ignore_if_not_exists: false, - }, - ) - .await - .unwrap(); - cx.run_until_parked(); - fs.create_dir(Path::new(path!("/test/.git"))).await.unwrap(); - cx.run_until_parked(); - - complete_tx.send(()).unwrap(); - send_task.await.unwrap(); - cx.run_until_parked(); - - thread.update(cx, |thread, _| { - let (_, message) = thread.last_user_message().unwrap(); - assert!( - message.checkpoint.as_ref().unwrap().show, - "a checkpoint comparison failure must not hide the restore checkpoint button" - ); - }); - } - /// Tests that when a follow-up message is sent during generation, /// the first turn completing does NOT clear `running_turn` because /// it now belongs to the second turn. @@ -25625,12 +24605,9 @@ mod tests { } turn.await.expect("turn settles"); } else if matches!(lifecycle, "local refusal" | "local refusal after tool") { - thread - .update(cx, |thread, cx| { - thread.finish_local_turn(acp_v2::StopReason::Refusal, cx) - }) - .await - .expect("local refusal cleanup"); + thread.update(cx, |thread, cx| { + thread.finish_local_turn(acp_v2::StopReason::Refusal, cx) + }); thread.update(cx, |thread, cx| { assert_eq!(thread.foreground_activity(), ForegroundActivity::Running); thread diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs index d7f1bb3acf4..7294171617b 100644 --- a/crates/acp_thread/src/connection.rs +++ b/crates/acp_thread/src/connection.rs @@ -998,6 +998,7 @@ mod test_support { close_sessions_on_release: bool, supports_session_additional_directories: bool, supports_set_title: bool, + supports_truncate: bool, agent_id: AgentId, telemetry_id: SharedString, prompt_capabilities_rx: watch::Receiver, @@ -1048,6 +1049,7 @@ mod test_support { close_sessions_on_release: true, supports_session_additional_directories: false, supports_set_title: true, + supports_truncate: true, agent_id: AgentId::new("stub"), telemetry_id: "stub".into(), prompt_capabilities_rx: watch::Receiver::constant( @@ -1224,6 +1226,11 @@ mod test_support { self } + pub fn with_supports_truncate(mut self, supports_truncate: bool) -> Self { + self.supports_truncate = supports_truncate; + self + } + pub fn with_agent_id(mut self, agent_id: AgentId) -> Self { self.agent_id = agent_id; self @@ -1547,9 +1554,11 @@ mod test_support { _cx: &App, ) -> Option> { // Capability checks also call this; only run may consume the gate. - Some(Rc::new(StubAgentSessionEditor { - next_truncate: self.next_truncate.clone(), - })) + self.supports_truncate.then(|| { + Rc::new(StubAgentSessionEditor { + next_truncate: self.next_truncate.clone(), + }) as Rc + }) } fn into_any(self: Rc) -> Rc { diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs index 8ed0fae5968..2511858835d 100644 --- a/crates/agent/src/agent.rs +++ b/crates/agent/src/agent.rs @@ -2525,7 +2525,7 @@ impl NativeAgentConnection { }), )) })??; - let (message_id, preparation, retry_action) = if let Some(content) = content { + let (message_id, retry_action) = if let Some(content) = content { let message_id = ClientUserMessageId::new(); let retry_action = agent.read_with(cx, |agent, cx| { let project_state = agent @@ -2558,10 +2558,10 @@ impl NativeAgentConnection { cx, ) })?; - let preparation = acp_thread.update(cx, |thread, cx| { - thread.prepare_local_prompt(message_id.clone(), source, cx) + acp_thread.update(cx, |thread, cx| { + thread.upsert_local_user_message(message_id.clone(), source, cx) })?; - (message_id, preparation, Some(retry_action)) + (message_id, Some(retry_action)) } else { let previous_execution = previous_execution .filter(|(id, _retry_action)| thread.read(cx).has_user_message(id)); @@ -2573,7 +2573,7 @@ impl NativeAgentConnection { let retry_action = previous_execution.and_then(|(_id, retry_action)| retry_action); thread.update(cx, |thread, cx| thread.prepare_local_turn(cx)); - (message_id, Task::ready(()), retry_action) + (message_id, retry_action) }; let (cancellation_sender, cancellation_receiver) = oneshot::channel(); let driver = Self::drive_execution( @@ -2583,7 +2583,6 @@ impl NativeAgentConnection { acp_thread.downgrade(), message_id.clone(), retry_action.clone(), - preparation, cancellation_receiver, completion_sender, cx, @@ -2630,7 +2629,6 @@ impl NativeAgentConnection { acp_thread: WeakEntity, message_id: ClientUserMessageId, retry_action: Option, - preparation: Task<()>, cancellation: oneshot::Receiver, completion: oneshot::Sender>>, cx: &App, @@ -2639,7 +2637,6 @@ impl NativeAgentConnection { let execution = cx.spawn({ let agent = agent.clone(); async move |cx| { - preparation.await; let task = cx.update(|cx| -> Result<_> { let connection = NativeAgentConnection( agent.upgrade().context("Native agent was released")?, @@ -2685,34 +2682,25 @@ impl NativeAgentConnection { thread.update(cx, |thread, cx| thread.cancel(cx)).detach(); } let result = match result { - Ok(reason) => { - let finish = acp_thread.update(cx, |thread, cx| { - thread.finish_local_turn(reason.clone(), cx) - }); - match finish { - Ok(finish) => match finish.await { - Ok(()) => acp_thread.update(cx, |thread, cx| { - thread.update_session_state( - acp_v2::StateUpdate::Idle( - acp_v2::IdleStateUpdate::new().stop_reason(reason.clone()), - ), - cx, - ) - }).and_then(|result| result).map(|()| reason), - Err(error) => Err(error), - }, - Err(error) => Err(error), - } - } + Ok(reason) => acp_thread + .update(cx, |thread, cx| thread.finish_local_turn(reason.clone(), cx)) + .and_then(|()| { + acp_thread.update(cx, |thread, cx| { + thread.update_session_state( + acp_v2::StateUpdate::Idle( + acp_v2::IdleStateUpdate::new().stop_reason(reason.clone()), + ), + cx, + ) + }) + }) + .and_then(|result| result) + .map(|()| reason), Err(error) => { - let finish = acp_thread.update(cx, |thread, cx| { + if let Err(finish_error) = acp_thread.update(cx, |thread, cx| { thread.finish_local_turn(acp_v2::ErrorStopReason::new().into(), cx) - }); - match finish { - Ok(finish) => { - finish.await.log_err(); - } - Err(finish_error) => log::error!("Native error cleanup: {finish_error:#}"), + }) { + log::error!("Native error cleanup: {finish_error:#}"); } Err(error) } @@ -3594,7 +3582,8 @@ impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate { let thread = self.thread.clone(); let acp_thread = self.acp_thread.clone(); cx.spawn(async move |cx| { - // Preparation is session-owned and may precede the model turn. + // An MCP prompt, skill, or compaction may still be preparing before + // the model turn starts, so cancel it before truncating. cancellation.await?; let usage = thread.update(cx, |thread, cx| { thread.truncate(client_user_message_id, cx)?; @@ -4610,90 +4599,6 @@ mod internal_tests { .collect() } - #[gpui::test] - async fn test_native_rewind_cancels_pending_preparation(cx: &mut TestAppContext) { - let fake = init_test(cx); - let (_connection, agent, _project, acp_thread) = setup_native_agent_session(cx).await; - let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone()); - let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx)); - let message_id = ClientUserMessageId::new(); - let content = vec!["rewound before model startup".into()]; - let (release, preparation) = oneshot::channel::<()>(); - let completion = cx.update(|cx| { - thread.update(cx, |thread, cx| { - thread.set_model(fake.model("fake"), cx); - let path_style = thread.project().read(cx).path_style(cx); - thread - .push_acp_user_block(message_id.clone(), content.clone(), path_style, cx) - .expect("accepted provider message"); - }); - acp_thread.update(cx, |thread, cx| { - thread - .prepare_local_prompt(message_id.clone(), content.clone(), cx) - .expect("accepted display message") - .detach(); - thread - .update_session_state( - acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()), - cx, - ) - .expect("running"); - }); - // The initial Git checkpoint can remain pending after acceptance. - let preparation = cx.spawn(async move |_cx| { - preparation.await.expect("release preparation"); - }); - let (sender, receiver) = oneshot::channel(); - let completion = receiver.shared(); - let (cancellation, cancelled) = oneshot::channel(); - let retry_action = Some(NativeRetryAction::Prompt(content)); - let driver = NativeAgentConnection::drive_execution( - agent.downgrade(), - session_id.clone(), - thread.clone(), - acp_thread.downgrade(), - message_id.clone(), - retry_action.clone(), - preparation, - cancelled, - sender, - cx, - ); - agent.update(cx, |agent, _cx| { - agent - .sessions - .get_mut(&session_id) - .expect("session") - .execution = Some(NativeExecution { - _driver: driver, - message_id: message_id.clone(), - retry_action, - cancellation: Some(cancellation), - completion: completion.clone(), - }); - }); - completion - }); - cx.run_until_parked(); - acp_thread - .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx)) - .await - .expect("rewind accepted message"); - if release.send(()).is_err() { - log::debug!("Rewind already dropped pending preparation"); - } - cx.run_until_parked(); - assert!( - fake.pending_completions().is_empty(), - "rewind must fence startup" - ); - assert!(!thread.read_with(cx, |thread, _| thread.has_user_message(&message_id))); - assert_eq!( - completion.await.expect("settled").expect("cancelled"), - acp_v2::StopReason::Cancelled - ); - } - #[gpui::test] async fn test_native_stop_does_not_wait_for_uncooperative_tool(cx: &mut TestAppContext) { use crate::tests::test_tools::DelayTool; @@ -5394,6 +5299,51 @@ mod internal_tests { assert_failed_native_command_context("/native-prompts.prepare", true, cx).await; } + #[gpui::test] + async fn test_native_rewind_cancels_pending_mcp_prompt(cx: &mut TestAppContext) { + let fake = init_test(cx); + let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await; + let mut requests = setup_native_prompt_server(&project, cx); + let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone()); + let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx)); + thread.update(cx, |thread, cx| thread.set_model(fake.model("fake"), cx)); + let (receipt, completion) = cx.update(|cx| { + connection.submit_native( + session_id.clone(), + Some(vec!["/native-prompts.prepare".into()]), + cx, + ) + }); + receipt.await.expect("command accepted"); + // Holding the prompt response keeps the turn before model startup. + let prompt_response = requests.next().await.expect("fetch prompt"); + let message_id = thread + .read_with(cx, |thread, _| thread.last_user_message_id()) + .expect("accepted command retained"); + acp_thread + .update(cx, |thread, cx| thread.rewind(message_id.clone(), cx)) + .await + .expect("rewind accepted message"); + if prompt_response + .send(json!({ + "messages": [{"role": "user", "content": {"type": "text", "text": "prepared"}}] + })) + .is_err() + { + log::debug!("Rewind already dropped the pending prompt fetch"); + } + cx.run_until_parked(); + assert!( + fake.pending_completions().is_empty(), + "rewind must fence startup" + ); + assert!(!thread.read_with(cx, |thread, _| thread.has_user_message(&message_id))); + assert_eq!( + completion.await.expect("settled").expect("cancelled"), + acp_v2::StopReason::Cancelled + ); + } + #[gpui::test] async fn test_native_failed_skill_follow_up_context(cx: &mut TestAppContext) { assert_failed_native_command_context("/:missing-skill do work", false, cx).await; diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 618f45f0987..2760802e650 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -2793,7 +2793,7 @@ impl Thread { pub(crate) fn prepare_local_turn(&mut self, cx: &mut Context) { // Freeze the old partial before inserting a successor's user message, - // and fence detached cleanup while its checkpoint or command is prepared. + // and fence detached cleanup while its command is prepared. self.flush_pending_message(cx); self.advance_prompt_id(); } diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 31955752cd3..42af4ccc4fb 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -1,10 +1,9 @@ use acp_thread::{ AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk, - AuthRequired, ClientUserMessageId, ElicitationEntryId, ElicitationStatus, ElicitationStore, - ForegroundActivity, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, - PermissionOptions, PermissionPattern, PermissionRequest, PermissionRequestId, - ProtocolErrorInfo, RetryStatus, SelectedPermissionOutcome, ThreadStatus, ToolCall, - ToolCallContent, ToolCallStatus, + AuthRequired, ElicitationEntryId, ElicitationStatus, ElicitationStore, ForegroundActivity, + LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice, PermissionOptions, + PermissionPattern, PermissionRequest, PermissionRequestId, ProtocolErrorInfo, RetryStatus, + SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus, }; use acp_thread::{AgentConnection, Plan}; use action_log::{ActionLog, ActionLogTelemetry, DiffStats}; @@ -4301,7 +4300,7 @@ fn plan_label_markdown_style( #[cfg(test)] pub(crate) mod tests { - use acp_thread::StubAgentConnection; + use acp_thread::{ClientUserMessageId, StubAgentConnection}; use action_log::ActionLog; use agent::{AgentTool, EditFileTool, FetchTool, TerminalTool, ToolPermissionContext}; use agent_client_protocol::schema::v1 as acp_v1; @@ -14477,6 +14476,79 @@ pub(crate) mod tests { }); } + #[gpui::test] + async fn test_user_message_is_editable_when_thread_can_rewind(cx: &mut TestAppContext) { + assert!(user_message_is_editable(StubAgentConnection::new(), false, cx).await); + } + + #[gpui::test] + async fn test_user_message_is_read_only_without_truncate(cx: &mut TestAppContext) { + let connection = StubAgentConnection::new().with_supports_truncate(false); + assert!(!user_message_is_editable(connection, false, cx).await); + } + + #[gpui::test] + async fn test_subagent_user_message_is_read_only(cx: &mut TestAppContext) { + assert!(!user_message_is_editable(StubAgentConnection::new(), true, cx).await); + } + + async fn user_message_is_editable( + connection: StubAgentConnection, + subagent: bool, + cx: &mut TestAppContext, + ) -> bool { + init_test(cx); + let (conversation_view, cx) = + setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await; + let root = + active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone()); + let thread = if subagent { + let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone()); + let child = conversation_view.update(cx, |view, cx| { + create_test_acp_thread( + Some(root_session_id), + "child", + Rc::new(connection.clone()), + view.project.clone(), + cx, + ) + }); + root.update(cx, |root, cx| root.register_subagent(child.clone(), cx)); + child + } else { + root + }; + thread + .update(cx, |thread, cx| { + thread.upsert_local_user_message( + ClientUserMessageId::new(), + vec!["Hello".into()], + cx, + ) + }) + .expect("user message"); + cx.run_until_parked(); + + let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone()); + conversation_view.read_with(cx, |view, cx| { + let thread_view = view.thread_view(&session_id).expect("thread view"); + let thread_view = thread_view.read(cx); + let read_only = thread_view + .entry_view_state + .read(cx) + .entry(0) + .and_then(|entry| entry.message_editor()) + .expect("user message editor") + .read(cx) + .editor() + .read(cx) + .read_only(cx); + let can_edit = thread_view.can_edit_user_message(0, cx); + assert_eq!(can_edit, !read_only); + can_edit + }) + } + #[gpui::test] async fn test_message_doesnt_send_if_empty(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 95426d2e125..b6d1286200f 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -3783,19 +3783,6 @@ impl ThreadView { // thread stuff - pub fn restore_checkpoint(&mut self, client_id: &ClientUserMessageId, cx: &mut Context) { - self.thread - .update(cx, |thread, cx| { - telemetry::event!( - "Agent Checkpoint Restored", - agent = thread.connection().telemetry_id(), - session = thread.session_id().clone(), - ); - thread.restore_checkpoint(client_id.clone(), cx) - }) - .detach_and_log_err(cx); - } - pub fn clear_thread_error(&mut self, cx: &mut Context) { self.thread_error = None; self.thread_error_markdown = None; @@ -7286,13 +7273,8 @@ impl ThreadView { let opaque_window = cx.theme().window_background_appearance() == gpui::WindowBackgroundAppearance::Opaque; - let has_checkpoint_button = message - .checkpoint - .as_ref() - .is_some_and(|checkpoint| checkpoint.show); - let is_subagent = self.is_subagent(); - let can_restore_checkpoint = self + let can_rewind = self .thread .read(cx) .can_rewind_to(message.client_id.as_ref(), cx); @@ -7301,7 +7283,7 @@ impl ThreadView { .source_blocks() .iter() .all(acp_thread::content::can_convert_to_v1); - let is_editable = can_restore_checkpoint && source_is_representable; + let is_editable = can_rewind && source_is_representable; let agent_name = if is_subagent { "subagents".into() } else { @@ -7321,25 +7303,6 @@ impl ThreadView { .px_2() .gap_1p5() .w_full() - .when(can_restore_checkpoint && has_checkpoint_button, |this| { - this.children(message.client_id.clone().map(|client_id| { - h_flex() - .px_3() - .gap_2() - .child(Divider::horizontal()) - .child( - Button::new("restore-checkpoint", "Restore Checkpoint") - .start_icon(Icon::new(IconName::Undo).size(IconSize::XSmall).color(Color::Muted)) - .label_size(LabelSize::XSmall) - .color(Color::Muted) - .tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation.")) - .on_click(cx.listener(move |this, _, _window, cx| { - this.restore_checkpoint(&client_id, cx); - })) - ) - .child(Divider::horizontal()) - })) - }) .child( div() .relative() diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rs index 2f274b95507..58daa4ef368 100644 --- a/crates/fs/src/fake_git_repo.rs +++ b/crates/fs/src/fake_git_repo.rs @@ -14,9 +14,8 @@ use git::{ repository::{ AskPassDelegate, Branch, CommitData, CommitDataReader, CommitDetails, CommitOptions, CreateWorktreeTarget, FetchOptions, FileHistoryChangedFileSets, GRAPH_CHUNK_SIZE, - GitRepository, GitRepositoryCheckpoint, InitialGraphCommitData, LogOrder, LogSource, - PushOptions, RefEdit, Remote, RepoPath, ResetMode, SearchCommitArgs, Worktree, - commit_hash_search_query, + GitRepository, InitialGraphCommitData, LogOrder, LogSource, PushOptions, RefEdit, Remote, + RepoPath, ResetMode, SearchCommitArgs, Worktree, commit_hash_search_query, }, stash::GitStash, status::{ @@ -1479,38 +1478,6 @@ impl GitRepository for FakeGitRepository { .boxed() } - fn checkpoint(&self) -> BoxFuture<'static, Result> { - let executor = self.executor.clone(); - let fs = self.fs.clone(); - let checkpoints = self.checkpoints.clone(); - let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf(); - async move { - executor.simulate_random_delay().await; - let oid = git::Oid::random(&mut *executor.rng().lock()); - let entry = fs.entry(&repository_dir_path)?; - checkpoints.lock().insert(oid, entry); - Ok(GitRepositoryCheckpoint { commit_sha: oid }) - } - .boxed() - } - - fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> { - let executor = self.executor.clone(); - let fs = self.fs.clone(); - let checkpoints = self.checkpoints.clone(); - let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf(); - async move { - executor.simulate_random_delay().await; - let checkpoints = checkpoints.lock(); - let entry = checkpoints - .get(&checkpoint.commit_sha) - .context(format!("invalid checkpoint: {}", checkpoint.commit_sha))?; - fs.insert_entry(&repository_dir_path, entry.clone())?; - Ok(()) - } - .boxed() - } - fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>> { let executor = self.executor.clone(); let fs = self.fs.clone(); @@ -1535,119 +1502,21 @@ impl GitRepository for FakeGitRepository { _staged_sha: String, unstaged_sha: String, ) -> BoxFuture<'_, Result<()>> { - match unstaged_sha.parse() { - Ok(commit_sha) => self.restore_checkpoint(GitRepositoryCheckpoint { commit_sha }), - Err(error) => async move { - Err(anyhow::anyhow!(error).context("failed to parse unstaged SHA as Oid")) - } - .boxed(), - } - } - - fn compare_checkpoints( - &self, - left: GitRepositoryCheckpoint, - right: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result> { let executor = self.executor.clone(); + let fs = self.fs.clone(); let checkpoints = self.checkpoints.clone(); + let repository_dir_path = self.repository_dir_path.parent().unwrap().to_path_buf(); async move { + let commit_sha: Oid = unstaged_sha + .parse() + .context("failed to parse unstaged SHA as Oid")?; executor.simulate_random_delay().await; let checkpoints = checkpoints.lock(); - let left = checkpoints - .get(&left.commit_sha) - .context(format!("invalid left checkpoint: {}", left.commit_sha))?; - let right = checkpoints - .get(&right.commit_sha) - .context(format!("invalid right checkpoint: {}", right.commit_sha))?; - - Ok(left == right) - } - .boxed() - } - - fn diff_checkpoints( - &self, - base_checkpoint: GitRepositoryCheckpoint, - target_checkpoint: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result> { - let executor = self.executor.clone(); - let checkpoints = self.checkpoints.clone(); - async move { - executor.simulate_random_delay().await; - let checkpoints = checkpoints.lock(); - let base = checkpoints - .get(&base_checkpoint.commit_sha) - .context(format!( - "invalid base checkpoint: {}", - base_checkpoint.commit_sha - ))?; - let target = checkpoints - .get(&target_checkpoint.commit_sha) - .context(format!( - "invalid target checkpoint: {}", - target_checkpoint.commit_sha - ))?; - - fn collect_files( - entry: &FakeFsEntry, - prefix: String, - out: &mut std::collections::BTreeMap, - ) { - match entry { - FakeFsEntry::File { content, .. } => { - out.insert(prefix, String::from_utf8_lossy(content).into_owned()); - } - FakeFsEntry::Dir { entries, .. } => { - for (name, child) in entries { - let path = if prefix.is_empty() { - name.clone() - } else { - format!("{prefix}/{name}") - }; - collect_files(child, path, out); - } - } - FakeFsEntry::Symlink { .. } => {} - } - } - - let mut base_files = std::collections::BTreeMap::new(); - let mut target_files = std::collections::BTreeMap::new(); - collect_files(base, String::new(), &mut base_files); - collect_files(target, String::new(), &mut target_files); - - let all_paths: std::collections::BTreeSet<&String> = - base_files.keys().chain(target_files.keys()).collect(); - - let mut diff = String::new(); - for path in all_paths { - match (base_files.get(path), target_files.get(path)) { - (Some(base_content), Some(target_content)) - if base_content != target_content => - { - diff.push_str(&format!("diff --git a/{path} b/{path}\n")); - diff.push_str(&format!("--- a/{path}\n")); - diff.push_str(&format!("+++ b/{path}\n")); - for line in base_content.lines() { - diff.push_str(&format!("-{line}\n")); - } - for line in target_content.lines() { - diff.push_str(&format!("+{line}\n")); - } - } - (Some(_), None) => { - diff.push_str(&format!("diff --git a/{path} /dev/null\n")); - diff.push_str("deleted file\n"); - } - (None, Some(_)) => { - diff.push_str(&format!("diff --git /dev/null b/{path}\n")); - diff.push_str("new file\n"); - } - _ => {} - } - } - Ok(diff) + let entry = checkpoints + .get(&commit_sha) + .context(format!("invalid checkpoint: {commit_sha}"))?; + fs.insert_entry(&repository_dir_path, entry.clone())?; + Ok(()) } .boxed() } diff --git a/crates/fs/tests/integration/fake_git_repo_tests.rs b/crates/fs/tests/integration/fake_git_repo_tests.rs index 3be81ad7301..63d1e398dbf 100644 --- a/crates/fs/tests/integration/fake_git_repo_tests.rs +++ b/crates/fs/tests/integration/fake_git_repo_tests.rs @@ -1,4 +1,4 @@ -use fs::{FakeFs, Fs}; +use fs::{FakeFs, Fs, RemoveOptions}; use gpui::{BackgroundExecutor, TestAppContext}; use serde_json::json; use std::path::{Path, PathBuf}; @@ -122,7 +122,7 @@ async fn test_fake_worktree_lifecycle(cx: &mut TestAppContext) { } #[gpui::test] -async fn test_checkpoints(executor: BackgroundExecutor) { +async fn test_archive_checkpoints(executor: BackgroundExecutor) { let fs = FakeFs::new(executor); fs.insert_tree( path!("/"), @@ -144,27 +144,15 @@ async fn test_checkpoints(executor: BackgroundExecutor) { .open_repo(Path::new("/foo/.git"), Some("git".as_ref())) .unwrap(); - let checkpoint_1 = repository.checkpoint().await.unwrap(); + let (staged_sha, unstaged_sha) = repository.create_archive_checkpoint().await.unwrap(); + fs.remove_file(Path::new("/foo/a"), RemoveOptions::default()) + .await + .unwrap(); fs.write(Path::new("/foo/b"), b"IPSUM").await.unwrap(); fs.write(Path::new("/foo/c"), b"dolor").await.unwrap(); - let checkpoint_2 = repository.checkpoint().await.unwrap(); - let checkpoint_3 = repository.checkpoint().await.unwrap(); - - assert!( - repository - .compare_checkpoints(checkpoint_2.clone(), checkpoint_3.clone()) - .await - .unwrap() - ); - assert!( - !repository - .compare_checkpoints(checkpoint_1.clone(), checkpoint_2.clone()) - .await - .unwrap() - ); repository - .restore_checkpoint(checkpoint_1.clone()) + .restore_archive_checkpoint(staged_sha, unstaged_sha) .await .unwrap(); assert_eq!( @@ -175,22 +163,4 @@ async fn test_checkpoints(executor: BackgroundExecutor) { (Path::new(path!("/foo/b")).into(), b"ipsum".into()) ] ); - - // diff_checkpoints: identical checkpoints produce empty diff - let diff = repository - .diff_checkpoints(checkpoint_2.clone(), checkpoint_3.clone()) - .await - .unwrap(); - assert!( - diff.is_empty(), - "identical checkpoints should produce empty diff" - ); - - // diff_checkpoints: different checkpoints produce non-empty diff - let diff = repository - .diff_checkpoints(checkpoint_1.clone(), checkpoint_2.clone()) - .await - .unwrap(); - assert!(diff.contains("b"), "diff should mention changed file 'b'"); - assert!(diff.contains("c"), "diff should mention added file 'c'"); } diff --git a/crates/git/src/checkpoint.gitignore b/crates/git/src/checkpoint.gitignore deleted file mode 100644 index 8921e677df3..00000000000 --- a/crates/git/src/checkpoint.gitignore +++ /dev/null @@ -1,91 +0,0 @@ -# This lists files that we don't track in checkpoints - -# Compiled source and executables -*.exe -*.dll -*.so -*.dylib -*.a -*.lib -*.o -*.obj -*.elf -*.out -*.app -*.deb -*.rpm -*.dmg -*.pkg -*.msi - -# Archives and compressed files -*.7z -*.zip -*.tar -*.tar.gz -*.tgz -*.tar.bz2 -*.tbz2 -*.tar.xz -*.txz -*.rar -*.jar -*.war -*.ear - -# Media files -*.jpg -*.jpeg -*.png -*.gif -*.ico -*.svg -*.webp -*.bmp -*.tiff -*.mp3 -*.mp4 -*.avi -*.mov -*.wmv -*.flv -*.mkv -*.webm -*.wav -*.flac -*.aac - -# Database files -*.db -*.sqlite -*.sqlite3 -*.mdb - -# Documents (often binary) -*.pdf -*.doc -*.docx -*.xls -*.xlsx -*.ppt -*.pptx - -# IDE and editor files -.idea/ -.vscode/ -*.swp -*.swo -*~ -.DS_Store -Thumbs.db - -# Language-specific files -*.rlib -*.rmeta -*.pdb -*.class -*.egg -*.egg-info/ -*.pyc -*.pto -__pycache__ diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs index 58423167efc..946206db4dd 100644 --- a/crates/git/src/repository.rs +++ b/crates/git/src/repository.rs @@ -1072,12 +1072,6 @@ pub trait GitRepository: Send + Sync { path_prefixes: &[RepoPath], ) -> BoxFuture<'static, Result>; - /// Creates a checkpoint for the repository. - fn checkpoint(&self) -> BoxFuture<'static, Result>; - - /// Resets to a previously-created checkpoint. - fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>>; - /// Creates two detached commits capturing the current staged and unstaged /// state without moving any branch. Returns (staged_sha, unstaged_sha). fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>>; @@ -1092,20 +1086,6 @@ pub trait GitRepository: Send + Sync { unstaged_sha: String, ) -> BoxFuture<'_, Result<()>>; - /// Compares two checkpoints, returning true if they are equal - fn compare_checkpoints( - &self, - left: GitRepositoryCheckpoint, - right: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result>; - - /// Computes a diff between two checkpoints. - fn diff_checkpoints( - &self, - base_checkpoint: GitRepositoryCheckpoint, - target_checkpoint: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result>; - fn load_commit_template(&self) -> BoxFuture<'_, Result>>; fn default_branch( @@ -1344,11 +1324,6 @@ impl RealGitRepository { } } -#[derive(Clone, Debug)] -pub struct GitRepositoryCheckpoint { - pub commit_sha: Oid, -} - #[derive(Debug)] pub struct GitCommitter { pub name: Option, @@ -3083,64 +3058,6 @@ impl GitRepository for RealGitRepository { .boxed() } - fn checkpoint(&self) -> BoxFuture<'static, Result> { - let git = self.git_binary_in_worktree(); - self.executor - .spawn(async move { - let mut git = git?.envs(checkpoint_author_envs()); - git.with_temp_index(async |git| { - let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok(); - - git.run(&["add", "--update"]).await?; - let untracked_files = untracked_files_for_checkpoint(git).await?; - add_files_to_index(git, &untracked_files).await?; - let tree = git.run(&["write-tree"]).await?; - let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() { - git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"]) - .await? - } else { - git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await? - }; - - Ok(GitRepositoryCheckpoint { - commit_sha: checkpoint_sha.parse()?, - }) - }) - .await - }) - .boxed() - } - - fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> { - let git = self.git_binary_in_worktree(); - self.executor - .spawn(async move { - let git = git?; - git.run(&[ - "restore", - "--source", - &checkpoint.commit_sha.to_string(), - "--worktree", - ".", - ]) - .await?; - - // TODO: We don't track binary and large files anymore, - // so the following call would delete them. - // Implement an alternative way to track files added by agent. - // - // git.with_temp_index(async move |git| { - // git.run(&["read-tree", &checkpoint.commit_sha.to_string()]) - // .await?; - // git.run(&["clean", "-d", "--force"]).await - // }) - // .await?; - - Ok(()) - }) - .boxed() - } - fn create_archive_checkpoint(&self) -> BoxFuture<'_, Result<(String, String)>> { let git = self.git_binary_in_worktree(); self.executor @@ -3223,61 +3140,6 @@ impl GitRepository for RealGitRepository { .boxed() } - fn compare_checkpoints( - &self, - left: GitRepositoryCheckpoint, - right: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result> { - let git = self.git_binary_in_worktree(); - self.executor - .spawn(async move { - let git = git?; - let result = git - .run(&[ - "diff-tree", - "--quiet", - &left.commit_sha.to_string(), - &right.commit_sha.to_string(), - ]) - .await; - match result { - Ok(_) => Ok(true), - Err(error) => { - if let Some(GitBinaryCommandError { status, .. }) = - error.downcast_ref::() - && status.code() == Some(1) - { - return Ok(false); - } - - Err(error) - } - } - }) - .boxed() - } - - fn diff_checkpoints( - &self, - base_checkpoint: GitRepositoryCheckpoint, - target_checkpoint: GitRepositoryCheckpoint, - ) -> BoxFuture<'_, Result> { - let git = self.git_binary_in_worktree(); - self.executor - .spawn(async move { - let git = git?; - git.run(&[ - "diff", - "--find-renames", - "--patch", - &base_checkpoint.commit_sha.to_string(), - &target_checkpoint.commit_sha.to_string(), - ]) - .await - }) - .boxed() - } - fn default_branch( &self, include_remote_name: bool, @@ -3792,111 +3654,6 @@ fn git_status_args(path_prefixes: &[RepoPath]) -> Vec { args } -/// Lists untracked files that should be included in a checkpoint, skipping -/// commonly ignored file types and files over 2MB. -async fn untracked_files_for_checkpoint(git: &GitBinary) -> Result> { - const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB - - // The extra checkpoint excludes are passed ad hoc via --exclude-from - // rather than by mutating .git/info/exclude, whose writes would trigger a - // rescan of the repository. The scratch file is placed directly in the - // .git directory with a .tmp extension so that the worktree scanner - // filters out the events it generates. - let excludes_file_path = git - .git_directory - .join(format!("checkpoint-excludes-{}.tmp", Uuid::new_v4())); - - let delete_excludes_file = util::defer({ - let excludes_file_path = excludes_file_path.clone(); - let executor = git.executor.clone(); - move || { - executor - .spawn(async move { - smol::fs::remove_file(excludes_file_path).await.log_err(); - }) - .detach(); - } - }); - - smol::fs::write(&excludes_file_path, include_str!("./checkpoint.gitignore")).await?; - - let mut exclude_from_arg = OsString::from("--exclude-from="); - exclude_from_arg.push(&excludes_file_path); - let output = git - .run(&[ - OsStr::new("ls-files"), - OsStr::new("--others"), - OsStr::new("--exclude-standard"), - OsStr::new("-z"), - exclude_from_arg.as_os_str(), - ]) - .await; - - smol::fs::remove_file(&excludes_file_path).await.ok(); - delete_excludes_file.abort(); - let output = output?; - - let working_directory = git.working_directory.clone(); - let size_checks = output - .split('\0') - .filter(|path| !path.is_empty()) - .map(|path| { - let full_path = working_directory.join(path); - let path = path.to_string(); - smol::spawn(async move { - match smol::fs::metadata(&full_path).await { - Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => None, - _ => Some(path), - } - }) - }) - .collect::>(); - - let untracked_files = futures::future::join_all(size_checks) - .await - .into_iter() - .flatten() - .collect(); - Ok(untracked_files) -} - -async fn add_files_to_index(git: &GitBinary, files: &[String]) -> Result<()> { - if files.is_empty() { - return Ok(()); - } - - let mut process = git - .build_command(&["update-index", "--add", "-z", "--stdin"]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn()?; - - let mut stdin = BufWriter::new( - process - .stdin - .take() - .context("no stdin for git update-index subprocess")?, - ); - for file in files { - stdin.write_all(file.as_bytes()).await?; - stdin.write_all(b"\0").await?; - } - stdin.flush().await?; - drop(stdin); - - let output = process.output().await?; - anyhow::ensure!( - output.status.success(), - GitBinaryCommandError { - stdout: String::from_utf8_lossy(&output.stdout).to_string(), - stderr: String::from_utf8_lossy(&output.stderr).to_string(), - status: output.status, - } - ); - Ok(()) -} - pub(crate) struct GitBinary { git_binary_path: PathBuf, working_directory: PathBuf, @@ -5755,96 +5512,6 @@ mod tests { ); } - #[gpui::test] - async fn test_checkpoint_basic(cx: &mut TestAppContext) { - disable_git_global_config(); - - cx.executor().allow_parking(); - - let repo_dir = tempfile::tempdir().unwrap(); - - git_init_repo(repo_dir.path()); - let file_path = repo_dir.path().join("file"); - smol::fs::write(&file_path, "initial").await.unwrap(); - - let repo = RealGitRepository::new( - &repo_dir.path().join(".git"), - None, - Some("git".into()), - cx.executor(), - ) - .unwrap(); - - repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default())) - .await - .unwrap(); - repo.commit( - "Initial commit".into(), - None, - CommitOptions::default(), - AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}), - Arc::new(test_commit_envs()), - ) - .await - .unwrap(); - - smol::fs::write(&file_path, "modified before checkpoint") - .await - .unwrap(); - smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1") - .await - .unwrap(); - let checkpoint = repo.checkpoint().await.unwrap(); - - // Ensure the user can't see any branches after creating a checkpoint. - assert_eq!(repo.branches().await.unwrap().branches.len(), 1); - - smol::fs::write(&file_path, "modified after checkpoint") - .await - .unwrap(); - repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default())) - .await - .unwrap(); - repo.commit( - "Commit after checkpoint".into(), - None, - CommitOptions::default(), - AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}), - Arc::new(test_commit_envs()), - ) - .await - .unwrap(); - - smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint")) - .await - .unwrap(); - smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2") - .await - .unwrap(); - - // Ensure checkpoint stays alive even after a Git GC. - repo.gc().await.unwrap(); - repo.restore_checkpoint(checkpoint.clone()).await.unwrap(); - - assert_eq!( - smol::fs::read_to_string(&file_path).await.unwrap(), - "modified before checkpoint" - ); - assert_eq!( - smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint")) - .await - .unwrap(), - "1" - ); - // See TODO above - // assert_eq!( - // smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint")) - // .await - // .ok(), - // None - // ); - } - #[cfg(unix)] #[gpui::test] async fn test_commit_runs_git_hooks(cx: &mut TestAppContext) { @@ -6113,52 +5780,6 @@ mod tests { ); } - #[gpui::test] - async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) { - disable_git_global_config(); - - cx.executor().allow_parking(); - - let repo_dir = tempfile::tempdir().unwrap(); - git_init_repo(repo_dir.path()); - let repo = RealGitRepository::new( - &repo_dir.path().join(".git"), - None, - Some("git".into()), - cx.executor(), - ) - .unwrap(); - - smol::fs::write(repo_dir.path().join("foo"), "foo") - .await - .unwrap(); - let checkpoint_sha = repo.checkpoint().await.unwrap(); - - // Ensure the user can't see any branches after creating a checkpoint. - assert_eq!(repo.branches().await.unwrap().branches.len(), 1); - - smol::fs::write(repo_dir.path().join("foo"), "bar") - .await - .unwrap(); - smol::fs::write(repo_dir.path().join("baz"), "qux") - .await - .unwrap(); - repo.restore_checkpoint(checkpoint_sha).await.unwrap(); - assert_eq!( - smol::fs::read_to_string(repo_dir.path().join("foo")) - .await - .unwrap(), - "foo" - ); - // See TODOs above - // assert_eq!( - // smol::fs::read_to_string(repo_dir.path().join("baz")) - // .await - // .ok(), - // None - // ); - } - #[gpui::test] async fn test_branches_return_head_when_commit_metadata_cannot_be_read( cx: &mut TestAppContext, @@ -6217,111 +5838,6 @@ mod tests { ); } - #[gpui::test] - async fn test_compare_checkpoints(cx: &mut TestAppContext) { - disable_git_global_config(); - - cx.executor().allow_parking(); - - let repo_dir = tempfile::tempdir().unwrap(); - git_init_repo(repo_dir.path()); - let repo = RealGitRepository::new( - &repo_dir.path().join(".git"), - None, - Some("git".into()), - cx.executor(), - ) - .unwrap(); - - smol::fs::write(repo_dir.path().join("file1"), "content1") - .await - .unwrap(); - let checkpoint1 = repo.checkpoint().await.unwrap(); - - smol::fs::write(repo_dir.path().join("file2"), "content2") - .await - .unwrap(); - let checkpoint2 = repo.checkpoint().await.unwrap(); - - assert!( - !repo - .compare_checkpoints(checkpoint1, checkpoint2.clone()) - .await - .unwrap() - ); - - let checkpoint3 = repo.checkpoint().await.unwrap(); - assert!( - repo.compare_checkpoints(checkpoint2, checkpoint3) - .await - .unwrap() - ); - } - - #[gpui::test] - async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) { - disable_git_global_config(); - - cx.executor().allow_parking(); - - let repo_dir = tempfile::tempdir().unwrap(); - let text_path = repo_dir.path().join("main.rs"); - let bin_path = repo_dir.path().join("binary.o"); - - git_init_repo(repo_dir.path()); - - smol::fs::write(&text_path, "fn main() {}").await.unwrap(); - - smol::fs::write(&bin_path, "some binary file here") - .await - .unwrap(); - - let repo = RealGitRepository::new( - &repo_dir.path().join(".git"), - None, - Some("git".into()), - cx.executor(), - ) - .unwrap(); - - // initial commit - repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default())) - .await - .unwrap(); - repo.commit( - "Initial commit".into(), - None, - CommitOptions::default(), - AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}), - Arc::new(test_commit_envs()), - ) - .await - .unwrap(); - - let checkpoint = repo.checkpoint().await.unwrap(); - - smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }") - .await - .unwrap(); - smol::fs::write(&bin_path, "Modified binary file") - .await - .unwrap(); - - repo.restore_checkpoint(checkpoint).await.unwrap(); - - // Text files should be restored to checkpoint state, - // but binaries should not (they aren't tracked) - assert_eq!( - smol::fs::read_to_string(&text_path).await.unwrap(), - "fn main() {}" - ); - - assert_eq!( - smol::fs::read_to_string(&bin_path).await.unwrap(), - "Modified binary file" - ); - } - #[test] fn test_branches_parsing() { // suppress "help: octal escapes are not supported, `\0` is always null" @@ -6787,6 +6303,78 @@ mod tests { ); } + #[gpui::test] + async fn test_archive_checkpoint_round_trip(cx: &mut TestAppContext) { + disable_git_global_config(); + cx.executor().allow_parking(); + + let repo_dir = tempfile::tempdir().unwrap(); + let path = repo_dir.path(); + git_init_repo(path); + // Archive commits must not depend on the user having a Git identity. + git_command(path, ["config", "user.useConfigOnly", "true"]); + for name in ["staged", "unstaged", "deleted"] { + fs::write(path.join(name), "initial").unwrap(); + } + git_command(path, ["add", "--all"]); + git_command(path, ["commit", "-m", "Initial commit"]); + + fs::write(path.join("staged"), "staged change").unwrap(); + git_command(path, ["add", "staged"]); + fs::write(path.join("unstaged"), "unstaged change").unwrap(); + fs::write(path.join("untracked"), "untracked").unwrap(); + fs::remove_file(path.join("deleted")).unwrap(); + let status_before = git_command_output(path, ["status", "--porcelain"]); + + let repo = + RealGitRepository::new(&path.join(".git"), None, Some("git".into()), cx.executor()) + .unwrap(); + let (staged_sha, unstaged_sha) = repo.create_archive_checkpoint().await.unwrap(); + + assert_eq!( + git_command_output(path, ["status", "--porcelain"]), + status_before, + "archiving must not touch the index or working tree" + ); + assert_eq!( + git_command_output(path, ["for-each-ref", "refs/heads"]) + .lines() + .count(), + 1, + "archiving must not create branches" + ); + let leftover_temp_indexes = fs::read_dir(path.join(".git")) + .unwrap() + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.file_name().to_string_lossy().starts_with("index-")) + .count(); + assert_eq!(leftover_temp_indexes, 0); + + git_command(path, ["reset", "--hard"]); + git_command(path, ["clean", "--force"]); + repo.restore_archive_checkpoint(staged_sha, unstaged_sha) + .await + .unwrap(); + + assert_eq!( + git_command_output(path, ["status", "--porcelain"]), + status_before + ); + assert_eq!( + fs::read_to_string(path.join("staged")).unwrap(), + "staged change" + ); + assert_eq!( + fs::read_to_string(path.join("unstaged")).unwrap(), + "unstaged change" + ); + assert_eq!( + fs::read_to_string(path.join("untracked")).unwrap(), + "untracked" + ); + assert!(!path.join("deleted").exists()); + } + #[gpui::test] async fn test_initial_graph_data_ref_set(cx: &mut TestAppContext) { disable_git_global_config(); @@ -6817,11 +6405,24 @@ mod tests { } commits }; + // Commits the worktree without moving HEAD or any branch. + let commit_worktree = |parent: Option<&str>| -> Oid { + git_command(repo_dir.path(), ["add", "--all"]); + let tree = git_command_output(repo_dir.path(), ["write-tree"]); + let mut arguments = vec!["commit-tree", tree.trim(), "-m", "commit"]; + if let Some(parent) = parent { + arguments.extend(["-p", parent]); + } + git_command_output(repo_dir.path(), arguments) + .trim() + .parse() + .unwrap() + }; smol::fs::write(repo_dir.path().join("file1"), "1") .await .unwrap(); - let branch_sha = repo.checkpoint().await.unwrap().commit_sha; + let branch_sha = commit_worktree(None); repo.update_ref("refs/heads/main".into(), branch_sha.to_string()) .await .unwrap(); @@ -6829,7 +6430,7 @@ mod tests { smol::fs::write(repo_dir.path().join("file2"), "2") .await .unwrap(); - let hidden_sha = repo.checkpoint().await.unwrap().commit_sha; + let hidden_sha = commit_worktree(Some(&branch_sha.to_string())); repo.update_ref("refs/custom/hidden".into(), hidden_sha.to_string()) .await .unwrap(); @@ -6980,30 +6581,6 @@ mod tests { ); } - impl RealGitRepository { - /// Force a Git garbage collection on the repository. - fn gc(&self) -> BoxFuture<'_, Result<()>> { - let working_directory = self.command_directory(); - let git_directory = self.path(); - let git_binary_path = self.any_git_binary_path.clone(); - let executor = self.executor.clone(); - self.executor - .spawn(async move { - let git_binary_path = git_binary_path.clone(); - let git = GitBinary::new( - git_binary_path, - working_directory, - git_directory, - executor, - true, - ); - git.run(&["gc", "--prune"]).await?; - Ok(()) - }) - .boxed() - } - } - #[test] fn test_parse_remote_urls() { let stdout = concat!( diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs index 16d07793ec0..4a80ab1bef8 100644 --- a/crates/project/src/git_store.rs +++ b/crates/project/src/git_store.rs @@ -40,10 +40,9 @@ use git::{ repository::{ Branch, BranchesScanResult, CommitData, CommitDetails, CommitFileStatus, CommitOptions, CreateWorktreeTarget, DiffStatType, DiffType, FetchOptions, FileHistoryChangedFileSets, - GitCommitTemplate, GitRepository, GitRepositoryCheckpoint, InitialGraphCommitData, - LogOrder, LogSource, PushOptions, Remote, RemoteCommandOutput, RepoPath, ResetMode, - SearchCommitArgs, UpstreamTrackingStatus, Worktree as GitWorktree, delete_branch_flag, - is_binary_content, + GitCommitTemplate, GitRepository, InitialGraphCommitData, LogOrder, LogSource, PushOptions, + Remote, RemoteCommandOutput, RepoPath, ResetMode, SearchCommitArgs, UpstreamTrackingStatus, + Worktree as GitWorktree, delete_branch_flag, is_binary_content, }, stash::{GitStash, StashEntry}, status::{ @@ -494,11 +493,6 @@ struct LocalDownstreamState { _task: Task>, } -#[derive(Clone, Debug)] -pub struct GitStoreCheckpoint { - checkpoints_by_work_dir_abs_path: HashMap, GitRepositoryCheckpoint>, -} - #[derive(Clone, Debug, PartialEq, Eq)] pub struct StatusEntry { pub repo_path: RepoPath, @@ -1065,12 +1059,8 @@ impl GitStore { client.add_entity_request_handler(Self::handle_run_hook); client.add_entity_request_handler(Self::handle_reset); client.add_entity_request_handler(Self::handle_show); - client.add_entity_request_handler(Self::handle_create_checkpoint); client.add_entity_request_handler(Self::handle_create_archive_checkpoint); - client.add_entity_request_handler(Self::handle_restore_checkpoint); client.add_entity_request_handler(Self::handle_restore_archive_checkpoint); - client.add_entity_request_handler(Self::handle_compare_checkpoints); - client.add_entity_request_handler(Self::handle_diff_checkpoints); client.add_entity_request_handler(Self::handle_load_commit_diff); client.add_entity_request_handler(Self::handle_checkout_files); client.add_entity_request_handler(Self::handle_add_path_to_gitignore); @@ -2152,92 +2142,6 @@ impl GitStore { Some(repo.read(cx).status_for_path(&repo_path)?.status) } - pub fn checkpoint(&self, cx: &mut App) -> Task> { - let mut work_directory_abs_paths = Vec::new(); - let mut checkpoints = Vec::new(); - for repository in self.repositories.values() { - repository.update(cx, |repository, _| { - work_directory_abs_paths.push(repository.snapshot.work_directory_abs_path.clone()); - checkpoints.push(repository.checkpoint().map(|checkpoint| checkpoint?)); - }); - } - - cx.background_executor().spawn(async move { - let checkpoints = future::try_join_all(checkpoints).await?; - Ok(GitStoreCheckpoint { - checkpoints_by_work_dir_abs_path: work_directory_abs_paths - .into_iter() - .zip(checkpoints) - .collect(), - }) - }) - } - - pub fn restore_checkpoint( - &self, - checkpoint: GitStoreCheckpoint, - cx: &mut App, - ) -> Task> { - let repositories_by_work_dir_abs_path = self - .repositories - .values() - .map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo)) - .collect::>(); - - let mut tasks = Vec::new(); - for (work_dir_abs_path, checkpoint) in checkpoint.checkpoints_by_work_dir_abs_path { - if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path) { - let restore = repository.update(cx, |repository, _| { - repository.restore_checkpoint(checkpoint) - }); - tasks.push(async move { restore.await? }); - } - } - cx.background_spawn(async move { - future::try_join_all(tasks).await?; - Ok(()) - }) - } - - /// Compares two checkpoints, returning true if they are equal. - pub fn compare_checkpoints( - &self, - left: GitStoreCheckpoint, - mut right: GitStoreCheckpoint, - cx: &mut App, - ) -> Task> { - let repositories_by_work_dir_abs_path = self - .repositories - .values() - .map(|repo| (repo.read(cx).snapshot.work_directory_abs_path.clone(), repo)) - .collect::>(); - - let mut tasks = Vec::new(); - for (work_dir_abs_path, left_checkpoint) in left.checkpoints_by_work_dir_abs_path { - if let Some(right_checkpoint) = right - .checkpoints_by_work_dir_abs_path - .remove(&work_dir_abs_path) - { - if let Some(repository) = repositories_by_work_dir_abs_path.get(&work_dir_abs_path) - { - let compare = repository.update(cx, |repository, _| { - repository.compare_checkpoints(left_checkpoint, right_checkpoint) - }); - - tasks.push(async move { compare.await? }); - } - } else { - return Task::ready(Ok(false)); - } - } - cx.background_spawn(async move { - Ok(future::try_join_all(tasks) - .await? - .into_iter() - .all(|result| result)) - }) - } - /// Blames a buffer. pub fn blame_buffer( &self, @@ -4453,23 +4357,6 @@ impl GitStore { }) } - async fn handle_create_checkpoint( - this: Entity, - envelope: TypedEnvelope, - mut cx: AsyncApp, - ) -> Result { - let repository_id = RepositoryId::from_proto(envelope.payload.repository_id); - let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?; - - let checkpoint = repository_handle - .update(&mut cx, |repository, _| repository.checkpoint()) - .await??; - - Ok(proto::GitCreateCheckpointResponse { - commit_sha: checkpoint.commit_sha.as_bytes().to_vec(), - }) - } - async fn handle_create_archive_checkpoint( this: Entity, envelope: TypedEnvelope, @@ -4490,27 +4377,6 @@ impl GitStore { }) } - async fn handle_restore_checkpoint( - this: Entity, - envelope: TypedEnvelope, - mut cx: AsyncApp, - ) -> Result { - let repository_id = RepositoryId::from_proto(envelope.payload.repository_id); - let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?; - - let checkpoint = GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&envelope.payload.commit_sha)?, - }; - - repository_handle - .update(&mut cx, |repository, _| { - repository.restore_checkpoint(checkpoint) - }) - .await??; - - Ok(proto::Ack {}) - } - async fn handle_restore_archive_checkpoint( this: Entity, envelope: TypedEnvelope, @@ -4530,54 +4396,6 @@ impl GitStore { Ok(proto::Ack {}) } - async fn handle_compare_checkpoints( - this: Entity, - envelope: TypedEnvelope, - mut cx: AsyncApp, - ) -> Result { - let repository_id = RepositoryId::from_proto(envelope.payload.repository_id); - let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?; - - let left = GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&envelope.payload.left_commit_sha)?, - }; - let right = GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&envelope.payload.right_commit_sha)?, - }; - - let equal = repository_handle - .update(&mut cx, |repository, _| { - repository.compare_checkpoints(left, right) - }) - .await??; - - Ok(proto::GitCompareCheckpointsResponse { equal }) - } - - async fn handle_diff_checkpoints( - this: Entity, - envelope: TypedEnvelope, - mut cx: AsyncApp, - ) -> Result { - let repository_id = RepositoryId::from_proto(envelope.payload.repository_id); - let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?; - - let base = GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&envelope.payload.base_commit_sha)?, - }; - let target = GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&envelope.payload.target_commit_sha)?, - }; - - let diff = repository_handle - .update(&mut cx, |repository, _| { - repository.diff_checkpoints(base, target) - }) - .await??; - - Ok(proto::GitDiffCheckpointsResponse { diff }) - } - async fn handle_load_commit_diff( this: Entity, envelope: TypedEnvelope, @@ -9986,53 +9804,6 @@ impl Repository { ) } - pub fn checkpoint(&mut self) -> oneshot::Receiver> { - let id = self.id; - self.send_job("checkpoint", None, move |repo, _cx| async move { - match repo { - RepositoryState::Local(LocalRepositoryState { backend, .. }) => { - backend.checkpoint().await - } - RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { - let response = client - .request(proto::GitCreateCheckpoint { - project_id: project_id.0, - repository_id: id.to_proto(), - }) - .await?; - - Ok(GitRepositoryCheckpoint { - commit_sha: Oid::from_bytes(&response.commit_sha)?, - }) - } - } - }) - } - - pub fn restore_checkpoint( - &mut self, - checkpoint: GitRepositoryCheckpoint, - ) -> oneshot::Receiver> { - let id = self.id; - self.send_job("restore_checkpoint", None, move |repo, _cx| async move { - match repo { - RepositoryState::Local(LocalRepositoryState { backend, .. }) => { - backend.restore_checkpoint(checkpoint).await - } - RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { - client - .request(proto::GitRestoreCheckpoint { - project_id: project_id.0, - repository_id: id.to_proto(), - commit_sha: checkpoint.commit_sha.as_bytes().to_vec(), - }) - .await?; - Ok(()) - } - } - }) - } - pub(crate) fn apply_remote_update( &mut self, update: proto::UpdateRepository, @@ -10134,60 +9905,6 @@ impl Repository { Ok(()) } - pub fn compare_checkpoints( - &mut self, - left: GitRepositoryCheckpoint, - right: GitRepositoryCheckpoint, - ) -> oneshot::Receiver> { - let id = self.id; - self.send_job("compare_checkpoints", None, move |repo, _cx| async move { - match repo { - RepositoryState::Local(LocalRepositoryState { backend, .. }) => { - backend.compare_checkpoints(left, right).await - } - RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { - let response = client - .request(proto::GitCompareCheckpoints { - project_id: project_id.0, - repository_id: id.to_proto(), - left_commit_sha: left.commit_sha.as_bytes().to_vec(), - right_commit_sha: right.commit_sha.as_bytes().to_vec(), - }) - .await?; - Ok(response.equal) - } - } - }) - } - - pub fn diff_checkpoints( - &mut self, - base_checkpoint: GitRepositoryCheckpoint, - target_checkpoint: GitRepositoryCheckpoint, - ) -> oneshot::Receiver> { - let id = self.id; - self.send_job("diff_checkpoints", None, move |repo, _cx| async move { - match repo { - RepositoryState::Local(LocalRepositoryState { backend, .. }) => { - backend - .diff_checkpoints(base_checkpoint, target_checkpoint) - .await - } - RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => { - let response = client - .request(proto::GitDiffCheckpoints { - project_id: project_id.0, - repository_id: id.to_proto(), - base_commit_sha: base_checkpoint.commit_sha.as_bytes().to_vec(), - target_commit_sha: target_checkpoint.commit_sha.as_bytes().to_vec(), - }) - .await?; - Ok(response.diff) - } - } - }) - } - fn clear_pending_ops(&mut self, cx: &mut Context) { let updated = SumTree::from_iter( self.pending_ops.iter().filter_map(|ops| { diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.proto index 02231fb0fe6..46ed17b5c68 100644 --- a/crates/proto/proto/git.proto +++ b/crates/proto/proto/git.proto @@ -674,15 +674,6 @@ message GitCreateWorktree { bool use_existing_branch = 6; } -message GitCreateCheckpoint { - uint64 project_id = 1; - uint64 repository_id = 2; -} - -message GitCreateCheckpointResponse { - bytes commit_sha = 1; -} - message GitCreateArchiveCheckpoint { uint64 project_id = 1; uint64 repository_id = 2; @@ -693,12 +684,6 @@ message GitCreateArchiveCheckpointResponse { string unstaged_commit_sha = 2; } -message GitRestoreCheckpoint { - uint64 project_id = 1; - uint64 repository_id = 2; - bytes commit_sha = 3; -} - message GitRestoreArchiveCheckpoint { uint64 project_id = 1; uint64 repository_id = 2; @@ -706,28 +691,6 @@ message GitRestoreArchiveCheckpoint { string unstaged_commit_sha = 4; } -message GitCompareCheckpoints { - uint64 project_id = 1; - uint64 repository_id = 2; - bytes left_commit_sha = 3; - bytes right_commit_sha = 4; -} - -message GitCompareCheckpointsResponse { - bool equal = 1; -} - -message GitDiffCheckpoints { - uint64 project_id = 1; - uint64 repository_id = 2; - bytes base_commit_sha = 3; - bytes target_commit_sha = 4; -} - -message GitDiffCheckpointsResponse { - string diff = 1; -} - message GitRemoveWorktree { uint64 project_id = 1; uint64 repository_id = 2; diff --git a/crates/proto/proto/zed.proto b/crates/proto/proto/zed.proto index 2d3fae59ced..44b90f726e8 100644 --- a/crates/proto/proto/zed.proto +++ b/crates/proto/proto/zed.proto @@ -465,13 +465,6 @@ message Envelope { KillKernel kill_kernel = 428; GitRemoveWorktree git_remove_worktree = 431; GitRenameWorktree git_rename_worktree = 432; - GitCreateCheckpoint git_create_checkpoint = 433; - GitCreateCheckpointResponse git_create_checkpoint_response = 434; - GitRestoreCheckpoint git_restore_checkpoint = 435; - GitCompareCheckpoints git_compare_checkpoints = 436; - GitCompareCheckpointsResponse git_compare_checkpoints_response = 437; - GitDiffCheckpoints git_diff_checkpoints = 438; - GitDiffCheckpointsResponse git_diff_checkpoints_response = 439; GitGetHeadSha git_get_head_sha = 440; GitGetHeadShaResponse git_get_head_sha_response = 441; GitRepairWorktrees git_repair_worktrees = 442; @@ -553,6 +546,7 @@ message Envelope { reserved 211 to 216, 232 to 233; reserved 397 to 398; reserved 406 to 408; + reserved 433 to 439; } message Hello { diff --git a/crates/proto/src/proto.rs b/crates/proto/src/proto.rs index 453bc34626d..5903a44d0a5 100644 --- a/crates/proto/src/proto.rs +++ b/crates/proto/src/proto.rs @@ -346,16 +346,9 @@ messages!( (GitAddPathToGitInfoExclude, Background), (GitShow, Background), (GitCommitDetails, Background), - (GitCreateCheckpoint, Background), - (GitCreateCheckpointResponse, Background), (GitCreateArchiveCheckpoint, Background), (GitCreateArchiveCheckpointResponse, Background), - (GitRestoreCheckpoint, Background), (GitRestoreArchiveCheckpoint, Background), - (GitCompareCheckpoints, Background), - (GitCompareCheckpointsResponse, Background), - (GitDiffCheckpoints, Background), - (GitDiffCheckpointsResponse, Background), (SetIndexText, Background), (Push, Background), (Fetch, Background), @@ -612,15 +605,11 @@ request_messages!( (InstallExtension, Ack), (RegisterBufferWithLanguageServers, Ack), (GitShow, GitCommitDetails), - (GitCreateCheckpoint, GitCreateCheckpointResponse), ( GitCreateArchiveCheckpoint, GitCreateArchiveCheckpointResponse ), - (GitRestoreCheckpoint, Ack), (GitRestoreArchiveCheckpoint, Ack), - (GitCompareCheckpoints, GitCompareCheckpointsResponse), - (GitDiffCheckpoints, GitDiffCheckpointsResponse), (GitReset, Ack), (GitDeleteBranch, Ack), (GitCheckoutFiles, Ack), @@ -844,10 +833,6 @@ entity_messages!( CancelLanguageServerWork, RegisterBufferWithLanguageServers, GitShow, - GitCreateCheckpoint, - GitRestoreCheckpoint, - GitCompareCheckpoints, - GitDiffCheckpoints, GitReset, GitDeleteBranch, GitCheckoutFiles, diff --git a/crates/remote_server/src/remote_editing_tests.rs b/crates/remote_server/src/remote_editing_tests.rs index 20b24670409..2bbe0d5cc6f 100644 --- a/crates/remote_server/src/remote_editing_tests.rs +++ b/crates/remote_server/src/remote_editing_tests.rs @@ -4735,153 +4735,6 @@ async fn test_remote_git_branches(cx: &mut TestAppContext, server_cx: &mut TestA assert_eq!(default_branch_with_remote.as_deref(), Some("origin/main")); } -#[gpui::test] -async fn test_remote_git_checkpoints(cx: &mut TestAppContext, server_cx: &mut TestAppContext) { - let fs = FakeFs::new(server_cx.executor()); - fs.insert_tree( - path!("/code"), - json!({ - "project1": { - ".git": {}, - "file.txt": "original content", - }, - }), - ) - .await; - - let (project, _headless) = init_test(&fs, cx, server_cx).await; - - let (_worktree, _) = project - .update(cx, |project, cx| { - project.find_or_create_worktree(path!("/code/project1"), true, cx) - }) - .await - .unwrap(); - cx.run_until_parked(); - - let repository = project.update(cx, |project, cx| project.active_repository(cx).unwrap()); - - // 1. Create a checkpoint of the original state - let checkpoint_1 = repository - .update(cx, |repository, _| repository.checkpoint()) - .await - .unwrap() - .unwrap(); - - // 2. Modify a file on the server-side fs - fs.write( - Path::new(path!("/code/project1/file.txt")), - b"modified content", - ) - .await - .unwrap(); - - // 3. Create a second checkpoint with the modified state - let checkpoint_2 = repository - .update(cx, |repository, _| repository.checkpoint()) - .await - .unwrap() - .unwrap(); - - // 4. compare_checkpoints: same checkpoint with itself => equal - let equal = repository - .update(cx, |repository, _| { - repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_1.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!(equal, "a checkpoint compared with itself should be equal"); - - // 5. compare_checkpoints: different states => not equal - let equal = repository - .update(cx, |repository, _| { - repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_2.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!( - !equal, - "checkpoints of different states should not be equal" - ); - - // 6. diff_checkpoints: same checkpoint => empty diff - let diff = repository - .update(cx, |repository, _| { - repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_1.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!( - diff.is_empty(), - "diff of identical checkpoints should be empty" - ); - - // 7. diff_checkpoints: different checkpoints => non-empty diff mentioning the changed file - let diff = repository - .update(cx, |repository, _| { - repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_2.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!( - !diff.is_empty(), - "diff of different checkpoints should be non-empty" - ); - assert!( - diff.contains("file.txt"), - "diff should mention the changed file" - ); - assert!( - diff.contains("original content"), - "diff should contain removed content" - ); - assert!( - diff.contains("modified content"), - "diff should contain added content" - ); - - // 8. restore_checkpoint: restore to original state - repository - .update(cx, |repository, _| { - repository.restore_checkpoint(checkpoint_1.clone()) - }) - .await - .unwrap() - .unwrap(); - cx.run_until_parked(); - - // 9. Create a checkpoint after restore - let checkpoint_3 = repository - .update(cx, |repository, _| repository.checkpoint()) - .await - .unwrap() - .unwrap(); - - // 10. compare_checkpoints: restored state matches original - let equal = repository - .update(cx, |repository, _| { - repository.compare_checkpoints(checkpoint_1.clone(), checkpoint_3.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!(equal, "restored state should match original checkpoint"); - - // 11. diff_checkpoints: restored state vs original => empty diff - let diff = repository - .update(cx, |repository, _| { - repository.diff_checkpoints(checkpoint_1.clone(), checkpoint_3.clone()) - }) - .await - .unwrap() - .unwrap(); - assert!(diff.is_empty(), "diff after restore should be empty"); -} - #[gpui::test] async fn test_remote_agent_fs_tool_calls(cx: &mut TestAppContext, server_cx: &mut TestAppContext) { let fs = FakeFs::new(server_cx.executor()); diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rs index 97bdd6050f7..c3d444c03ab 100644 --- a/crates/sidebar/src/sidebar_tests.rs +++ b/crates/sidebar/src/sidebar_tests.rs @@ -13444,8 +13444,7 @@ mod property_test { let thread_id = active_thread_id(&panel, cx); let session_id = active_session_id(&panel, cx); // Make the thread non-draft without exercising the prompt - // send path; these invariants are about sidebar state, not - // git checkpointing during user prompts. + // send path; these invariants are about sidebar state. cx.update(|_, cx| { connection.send_update( session_id.clone(), diff --git a/docs/src/ai/agent-panel.md b/docs/src/ai/agent-panel.md index 127b163ca97..c002f506d9b 100644 --- a/docs/src/ai/agent-panel.md +++ b/docs/src/ai/agent-panel.md @@ -1,6 +1,6 @@ --- title: AI Coding Agent - Zed Agent Panel -description: Use Zed's AI coding agent to generate, refactor, and debug code with tool calling, checkpoints, and multi-model support. +description: Use Zed's AI coding agent to generate, refactor, and debug code with tool calling and multi-model support. --- # Agent Panel @@ -26,7 +26,7 @@ Expand the editor with {#kb agent::ExpandMessageEditor} if you need more room. Responses stream in with indicators showing [which tools](./tools.md) the model is using. The sections below cover what you can do from here. -> Note that some Agent Panel features may not be available for every External Agent. Restoring threads from history, checkpoints, token usage display, and similar features depend on the agent integration. +> Note that some Agent Panel features may not be available for every External Agent. Restoring threads from history, token usage display, and similar features depend on the agent integration. > Their availability varies depending on the agent. ### Creating New Threads {#new-thread} @@ -69,12 +69,6 @@ By default, queued messages get sent once the agent finishes generating. If you You can edit or remove (an individual or all) queued messages. You can also still interrupt the agent immediately if you want by either clicking on the stop button or by clicking the "Send Now" (double-enter) on a queued message. -### Checkpoints {#checkpoints} - -Every time the model performs an edit, you should see a "Restore Checkpoint" button at the top of your message, allowing you to return your code base to the state it was in prior to that message. - -The checkpoint button appears even if you interrupt the thread midway through an edit, as this is likely a moment when you've identified that the agent is not heading in the right direction and you want to revert back. - ### Context Menu {#context-menu} Right-click on any agent response in the thread view to access a context menu with the following actions: