Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Skip git checkpoints for threads that can't restore them (#65304)
Smit Barmase4ce1fdd57620
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 6eea0a2ec54..414d824da5c 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3906,6 +3906,12 @@ 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.+ 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)+ }+pub fn work_dirs(&self) -> Option<&PathList> {self.session_info.work_dirs.as_ref()}@@ -6148,6 +6154,7 @@ impl AcpThread {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 {@@ -6167,20 +6174,22 @@ impl AcpThread {}).ok();- 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();+ 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| {@@ -15442,6 +15451,156 @@ mod tests {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::<oneshot::Receiver<()>>));+ 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<AcpThread>,+ _cx: AsyncApp|+ -> LocalBoxFuture<'static, Result<acp_v1::PromptResponse>> {+ 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_v1::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;diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rsindex a8b516d5432..51aadd3d63d 100644--- a/crates/agent/src/tests/mod.rs+++ b/crates/agent/src/tests/mod.rs@@ -7300,27 +7300,23 @@ async fn test_subagent_context_limit_exceeded_without_partial_output(cx: &mut Te}#[gpui::test]-async fn test_subagent_context_limit_preserves_terminal_result_during_checkpoint(+async fn test_subagent_context_limit_preserves_result_after_turn_completes(cx: &mut TestAppContext,) {for provider_error in [false, true] {- let test = SubagentCompactionTest::new_with_files(json!({".git": {}}), cx).await;+ let test = SubagentCompactionTest::new(cx).await;test.configure_compaction(false, 1_000_000, None, cx);- let mut send = test.send("subagent task prompt", cx);- let repository = test.thread.read_with(cx, |thread, cx| {- thread- .project()- .read(cx)- .git_store()- .read(cx)- .active_repository()- .unwrap()- });- let (resume_checkpoint, checkpoint_gate) = oneshot::channel::<()>();- let checkpoint_job = repository.update(cx, |repository, _| {- repository.send_job("hold checkpoint", None, move |_, _| checkpoint_gate)- });+ let send = test.send("subagent task prompt", cx);test.fake.send_last_text(&test.model, "partial work");+ // The final usage update crosses the limit as the turn ends, so the limit+ // signal fires while the finished turn's result is still on its way.+ test.fake.send_last_event(+ &test.model,+ LanguageModelCompletionEvent::UsageUpdate(TokenUsage {+ input_tokens: 800_000,+ ..TokenUsage::default()+ }),+ );if provider_error {test.fake.send_last_error(&test.model,@@ -7333,40 +7329,7 @@ async fn test_subagent_context_limit_preserves_terminal_result_during_checkpoint);}test.fake.end_last(&test.model);- cx.run_until_parked();-- test.thread- .read_with(cx, |thread, _| assert!(thread.is_turn_complete()));- assert!((&mut send).now_or_never().is_none());- repository.read_with(cx, |repository, _| {- let queue = repository.job_debug_queue().to_debug_value();- assert_eq!(- queue["entries"]- .as_array()- .unwrap()- .iter()- .filter(|job| job["description"] == "checkpoint" && job["status"] == "Pending")- .count(),- 1,- );- });- test.thread.update(cx, |thread, cx| {- assert!(thread.is_turn_complete());- cx.emit(TokenUsageUpdated(Some(acp_thread::TokenUsage {- max_tokens: 1_000_000,- used_tokens: 800_000,- input_tokens: 800_000,- ..acp_thread::TokenUsage::default()- })));- });- cx.run_until_parked();- assert!((&mut send).now_or_never().is_none());- test.parent.read_with(cx, |thread, cx| {- assert_eq!(thread.running_subagent_ids(cx), vec![test.handle.id()]);- });- resume_checkpoint.send(()).unwrap();- checkpoint_job.await.unwrap().unwrap();if provider_error {assert_eq!(send.await.unwrap_err().to_string(),diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 8885a352dc9..134dc146b84 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -1277,9 +1277,7 @@ impl ThreadView {else {return false;};- !self.is_subagent()- && thread.supports_truncate(cx)- && message.client_id.is_some()+ thread.can_rewind_to(message.client_id.as_ref(), cx)&& message.content.source_blocks()@@ -6783,9 +6781,10 @@ impl ThreadView {.is_some_and(|checkpoint| checkpoint.show);let is_subagent = self.is_subagent();- let can_restore_checkpoint = self.thread.read(cx).supports_truncate(cx)- && message.client_id.is_some()- && !is_subagent;+ let can_restore_checkpoint = self+ .thread+ .read(cx)+ .can_rewind_to(message.client_id.as_ref(), cx);let source_is_representable = message.content.source_blocks()diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex 18338022156..54ea5eb8fe8 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -242,16 +242,15 @@ impl EntryViewState {match thread_entry {AgentThreadEntry::UserMessage(message) => {- let can_rewind = thread.read(cx).supports_truncate(cx);- let has_client_id = message.client_id.is_some();- let is_subagent = thread.read(cx).parent_session_id().is_some();+ let can_rewind = thread+ .read(cx)+ .can_rewind_to(message.client_id.as_ref(), cx);let source_blocks = message.content.source_blocks();let source_version = message.content.source_version();let source_is_representable = source_blocks.iter().all(acp_thread::content::can_convert_to_v1);- let is_editable =- can_rewind && has_client_id && !is_subagent && source_is_representable;+ let is_editable = can_rewind && source_is_representable;if let Some(Entry::UserMessage {editor,synced_source_version,