Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Materialize tool-call diffs lazily, on first view (#65444)
John Yani9e65fc768247
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex fbfab0e6f5d..a217fcfeace 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3095,13 +3095,12 @@ impl ToolCallContent {meta: content.meta,},PreparedToolCallContent::LegacyDiff(source) => {- let diff = cx.new(|cx| {+ let diff = cx.new(|_| {Diff::finalized(source.path.to_string_lossy().into_owned(),source.old_text.clone(),source.new_text.clone(),language_registry.clone(),- cx,)});Self::LegacyDiff { source, diff }@@ -3179,7 +3178,7 @@ impl ToolCallContent {pub fn to_markdown(&self, cx: &App) -> String {match self {- Self::ContentBlock { block, .. } => block.to_markdown(cx).to_string(),+ Self::ContentBlock { block, .. } => block.to_markdown(cx).to_owned(),Self::Diff(diff) | Self::LegacyDiff { diff, .. } => diff.read(cx).to_markdown(cx),Self::Terminal { terminal, .. } => terminal.read(cx).to_markdown(cx),Self::DiffPatch { source, .. } => format!(@@ -9749,13 +9748,12 @@ mod tests {};assert_eq!(source.path, PathBuf::from("second.rs"));assert_ne!(diff, &previous);- let native_diff = cx.new(|cx| {+ let native_diff = cx.new(|_| {Diff::finalized("native.rs".into(),Some("before".into()),"after".into(),languages.clone(),- cx,)});let mut native = ToolCallContent::Diff(native_diff.clone());diff --git a/crates/acp_thread/src/diff.rs b/crates/acp_thread/src/diff.rsindex a8c991fb8fa..266a34f2098 100644--- a/crates/acp_thread/src/diff.rs+++ b/crates/acp_thread/src/diff.rs@@ -7,11 +7,20 @@ use collections::{HashMap, HashSet};use gpui::{App, AppContext, AsyncApp, Context, Entity, SharedString, Subscription, Task};use itertools::Itertools;use language::{- Anchor, Buffer, Capability, LanguageRegistry, OffsetRangeExt as _, Point, TextBuffer,+ Anchor, Buffer, Capability, LanguageRegistry, LineEnding, OffsetRangeExt as _, Point,+ TextBuffer,};use markdown::Markdown;use multi_buffer::{MultiBuffer, PathKey, excerpt_context_lines};-use std::{cmp::Reverse, ops::Range, path::Path, sync::Arc};+use std::{+ cell::{Cell, OnceCell},+ cmp::Reverse,+ mem,+ ops::Range,+ path::Path,+ rc::Rc,+ sync::Arc,+};use util::ResultExt;use util::paths::PathStyle;@@ -307,70 +316,27 @@ impl Diff {old_text: Option<String>,new_text: String,language_registry: Arc<LanguageRegistry>,- cx: &mut Context<Self>,) -> Self {- let multibuffer = cx.new(|_cx| MultiBuffer::without_headers(Capability::ReadOnly));- let new_buffer = cx.new(|cx| Buffer::local(new_text, cx));let base_text_exists = old_text.is_some();- let base_text = old_text.clone().unwrap_or(String::new()).into();- let task = cx.spawn({- let multibuffer = multibuffer.clone();- let path = path.clone();- let buffer = new_buffer.clone();- async move |_, cx| {- let language = language_registry- .load_language_for_file_path(Path::new(&path))- .await- .log_err();-- buffer.update(cx, |buffer, cx| buffer.set_language(language.clone(), cx));- buffer.update(cx, |buffer, _| buffer.parsing_idle()).await;-- let diff = build_buffer_diff(- old_text.unwrap_or("".into()).into(),- base_text_exists,- &buffer,- cx,- )- .await?;-- multibuffer.update(cx, |multibuffer, cx| {- let hunk_ranges = {- let buffer = buffer.read(cx);- diff.read(cx)- .snapshot(cx)- .hunks_intersecting_range(- Anchor::min_for_buffer(buffer.remote_id())- ..Anchor::max_for_buffer(buffer.remote_id()),- buffer,- )- .map(|diff_hunk| diff_hunk.buffer_range.to_point(buffer))- .collect::<Vec<_>>()- };-- multibuffer.set_excerpts_for_path(- PathKey::for_buffer(&buffer, cx),- buffer.clone(),- hunk_ranges,- excerpt_context_lines(cx),- cx,- );- multibuffer.add_diff(diff, cx);- });-- anyhow::Ok(())- }- });-Self::Finalized(FinalizedDiff {- multibuffer,path,- base_text,- new_buffer,- _update_diff: task,+ base_text: Arc::from(old_text.unwrap_or_default()),+ base_text_exists,+ state: FinalizedDiffState::Deferred(DeferredSource {+ new_text,+ language_registry,+ has_changes: OnceCell::new(),+ }),})}+ /// Restores an interrupted edit's buffer to its base text.+ pub fn discard_partial_edit(&mut self, cx: &mut Context<Self>) {+ let base_text = self.base_text().clone();+ self.buffer(cx)+ .update(cx, |buffer, cx| buffer.set_text(base_text.as_ref(), cx));+ }+pub fn new(buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Self {let buffer_text_snapshot = buffer.read(cx).text_snapshot();let language = buffer.read(cx).language().cloned();@@ -423,14 +389,6 @@ impl Diff {}}- /// Returns the buffer being edited (for pending diffs) or the snapshot buffer (for finalized diffs).- pub fn buffer(&self) -> &Entity<Buffer> {- match self {- Self::Pending(PendingDiff { new_buffer, .. }) => new_buffer,- Self::Finalized(FinalizedDiff { new_buffer, .. }) => new_buffer,- }- }-pub fn file_path(&self, cx: &App) -> Option<String> {match self {Self::Pending(PendingDiff { new_buffer, .. }) => new_buffer@@ -441,29 +399,45 @@ impl Diff {}}- pub fn multibuffer(&self) -> &Entity<MultiBuffer> {+ pub fn multibuffer(&mut self, cx: &mut Context<Self>) -> Entity<MultiBuffer> {match self {- Self::Pending(PendingDiff { multibuffer, .. }) => multibuffer,- Self::Finalized(FinalizedDiff { multibuffer, .. }) => multibuffer,+ Self::Pending(PendingDiff { multibuffer, .. }) => multibuffer.clone(),+ Self::Finalized(finalized) => {+ finalized.with_resolved(cx, |resolved| resolved.multibuffer.clone())+ }}}pub fn to_markdown(&self, cx: &App) -> String {- let buffer_text = self- .multibuffer()- .read(cx)- .all_buffers()- .iter()- .map(|buffer| buffer.read(cx).text())- .join("\n");- let path = match self {- Diff::Pending(PendingDiff {- new_buffer: buffer, ..- }) => buffer- .read(cx)- .file()- .map(|file| file.path().display(file.path_style(cx))),- Diff::Finalized(FinalizedDiff { path, .. }) => Some(path.as_str().into()),+ let (path, buffer_text) = match self {+ Self::Pending(PendingDiff {+ new_buffer,+ multibuffer,+ ..+ }) => {+ let buffer_text = multibuffer+ .read(cx)+ .all_buffers()+ .iter()+ .map(|buffer| buffer.read(cx).text())+ .join("\n");+ let path = new_buffer+ .read(cx)+ .file()+ .map(|file| file.path().display(file.path_style(cx)));+ (path, buffer_text)+ }+ Self::Finalized(finalized) => {+ let buffer_text = match &finalized.state {+ FinalizedDiffState::Resolved(resolved) => {+ finalized.export_resolved(resolved, cx)+ }+ FinalizedDiffState::Deferred(deferred) => finalized+ .normalized_changed_text(deferred.new_text.clone())+ .unwrap_or_default(),+ };+ (Some(finalized.path.as_str().into()), buffer_text)+ }};format!("Diff: {}\n```\n{}\n```\n",@@ -473,12 +447,34 @@ impl Diff {}pub fn has_revealed_range(&self, cx: &App) -> bool {- !self.multibuffer().read(cx).is_empty()+ match self {+ Self::Pending(PendingDiff { multibuffer, .. }) => !multibuffer.read(cx).is_empty(),+ Self::Finalized(finalized) => match &finalized.state {+ FinalizedDiffState::Resolved(resolved) => !resolved.multibuffer.read(cx).is_empty(),+ FinalizedDiffState::Deferred(_) => false,+ },+ }+ }++ pub fn has_changes(&self, cx: &App) -> bool {+ match self {+ Self::Pending(PendingDiff { multibuffer, .. }) => !multibuffer.read(cx).is_empty(),+ Self::Finalized(finalized) => match &finalized.state {+ FinalizedDiffState::Resolved(resolved) => {+ finalized.resolved_has_changes(resolved, cx)+ }+ FinalizedDiffState::Deferred(deferred) => *deferred.has_changes.get_or_init(|| {+ finalized+ .normalized_changed_text(deferred.new_text.clone())+ .is_some()+ }),+ },+ }}pub fn needs_update(&self, old_text: &str, new_text: &str, cx: &App) -> bool {match self {- Diff::Pending(PendingDiff {+ Self::Pending(PendingDiff {base_text,new_buffer,..@@ -486,13 +482,26 @@ impl Diff {base_text.as_ref() != old_text|| !new_buffer.read(cx).as_rope().chunks().equals_str(new_text)}- Diff::Finalized(FinalizedDiff {- base_text,- new_buffer,- ..- }) => {- base_text.as_ref() != old_text- || !new_buffer.read(cx).as_rope().chunks().equals_str(new_text)+ Self::Finalized(finalized) => {+ let FinalizedDiffState::Resolved(resolved) = &finalized.state else {+ return true;+ };+ finalized.base_text.as_ref() != old_text+ || !resolved+ .new_buffer+ .read(cx)+ .as_rope()+ .chunks()+ .equals_str(new_text)+ }+ }+ }++ fn buffer(&mut self, cx: &mut Context<Self>) -> Entity<Buffer> {+ match self {+ Self::Pending(PendingDiff { new_buffer, .. }) => new_buffer.clone(),+ Self::Finalized(finalized) => {+ finalized.with_resolved(cx, |resolved| resolved.new_buffer.clone())}}}@@ -576,10 +585,10 @@ impl PendingDiff {}});- let update_diff = cx.spawn(async move |this, cx| {+ let update_diff = cx.spawn(async move |diff, cx| {let buffer_diff = buffer_diff.await?;- this.update(cx, |this, cx| {- this.multibuffer().update(cx, |multibuffer, cx| {+ diff.update(cx, |diff, cx| {+ diff.multibuffer(cx).update(cx, |multibuffer, cx| {let path_key = PathKey::for_buffer(&buffer, cx);multibuffer.clear(cx);multibuffer.set_excerpts_for_path(@@ -599,9 +608,13 @@ impl PendingDiff {FinalizedDiff {path,base_text: self.base_text.clone(),- multibuffer: self.multibuffer.clone(),- new_buffer: self.new_buffer.clone(),- _update_diff: update_diff,+ base_text_exists: true,+ state: FinalizedDiffState::Resolved(ResolvedFinalized {+ new_buffer: self.new_buffer.clone(),+ multibuffer: self.multibuffer.clone(),+ _update_diff: update_diff,+ populated: Rc::new(Cell::new(true)),+ }),}}@@ -663,9 +676,137 @@ impl PendingDiff {pub struct FinalizedDiff {path: String,base_text: Arc<str>,+ base_text_exists: bool,+ state: FinalizedDiffState,+}++enum FinalizedDiffState {+ Deferred(DeferredSource),+ Resolved(ResolvedFinalized),+}++struct DeferredSource {+ new_text: String,+ language_registry: Arc<LanguageRegistry>,+ has_changes: OnceCell<bool>,+}++struct ResolvedFinalized {new_buffer: Entity<Buffer>,multibuffer: Entity<MultiBuffer>,_update_diff: Task<Result<()>>,+ populated: Rc<Cell<bool>>,+}++impl FinalizedDiff {+ fn with_resolved<T>(&mut self, cx: &mut App, read: impl FnOnce(&ResolvedFinalized) -> T) -> T {+ match &mut self.state {+ FinalizedDiffState::Resolved(resolved) => read(resolved),+ FinalizedDiffState::Deferred(deferred) => {+ let resolved = build_finalized(+ self.path.clone(),+ self.base_text_exists,+ self.base_text.clone(),+ mem::take(&mut deferred.new_text),+ deferred.language_registry.clone(),+ cx,+ );+ let result = read(&resolved);+ self.state = FinalizedDiffState::Resolved(resolved);+ result+ }+ }+ }++ fn resolved_has_changes(&self, resolved: &ResolvedFinalized, cx: &App) -> bool {+ if resolved.populated.get() {+ return !resolved.multibuffer.read(cx).is_empty();+ }+ self.normalized_changed_text(resolved.new_buffer.read(cx).text())+ .is_some()+ }++ fn export_resolved(&self, resolved: &ResolvedFinalized, cx: &App) -> String {+ if resolved.populated.get() {+ return resolved+ .multibuffer+ .read(cx)+ .all_buffers()+ .iter()+ .map(|buffer| buffer.read(cx).text())+ .join("\n");+ }+ self.normalized_changed_text(resolved.new_buffer.read(cx).text())+ .unwrap_or_default()+ }++ fn normalized_changed_text(&self, mut new_text: String) -> Option<String> {+ let base_text = LineEnding::normalize_arc(self.base_text.clone());+ LineEnding::normalize(&mut new_text);+ (!self.base_text_exists || new_text.as_str() != base_text.as_ref()).then_some(new_text)+ }+}++fn build_finalized(+ path: String,+ base_text_exists: bool,+ base_text: Arc<str>,+ new_text: String,+ language_registry: Arc<LanguageRegistry>,+ cx: &mut App,+) -> ResolvedFinalized {+ let multibuffer = cx.new(|_| MultiBuffer::without_headers(Capability::ReadOnly));+ let new_buffer = cx.new(|cx| Buffer::local(new_text, cx));+ let populated = Rc::new(Cell::new(false));+ let task = cx.spawn({+ let multibuffer = multibuffer.clone();+ let buffer = new_buffer.clone();+ let populated = populated.clone();+ async move |cx| {+ let language = language_registry+ .load_language_for_file_path(Path::new(&path))+ .await+ .log_err();+ buffer.update(cx, |buffer, cx| buffer.set_language(language, cx));+ buffer.update(cx, |buffer, _| buffer.parsing_idle()).await;++ let diff = build_buffer_diff(base_text, base_text_exists, &buffer, cx).await?;++ multibuffer.update(cx, |multibuffer, cx| {+ let hunk_ranges = {+ let buffer = buffer.read(cx);+ diff.read(cx)+ .snapshot(cx)+ .hunks_intersecting_range(+ Anchor::min_for_buffer(buffer.remote_id())+ ..Anchor::max_for_buffer(buffer.remote_id()),+ buffer,+ )+ .map(|diff_hunk| diff_hunk.buffer_range.to_point(buffer))+ .collect::<Vec<_>>()+ };++ multibuffer.set_excerpts_for_path(+ PathKey::for_buffer(&buffer, cx),+ buffer.clone(),+ hunk_ranges,+ excerpt_context_lines(cx),+ cx,+ );+ multibuffer.add_diff(diff, cx);+ });++ populated.set(true);+ anyhow::Ok(())+ }+ });++ ResolvedFinalized {+ new_buffer,+ multibuffer,+ _update_diff: task,+ populated,+ }}async fn build_buffer_diff(@@ -1037,10 +1178,139 @@ mod tests {#[gpui::test]async fn test_pending_diff(cx: &mut TestAppContext) {let buffer = cx.new(|cx| Buffer::local("hello!", cx));- let _diff = cx.new(|cx| Diff::new(buffer.clone(), cx));+ let diff = cx.new(|cx| Diff::new(buffer.clone(), cx));+ let multibuffer = diff.update(cx, |diff, cx| diff.multibuffer(cx));buffer.update(cx, |buffer, cx| {buffer.set_text("HELLO!", cx);});cx.run_until_parked();++ diff.update(cx, |diff, cx| diff.finalize(cx));+ assert_eq!(+ diff.update(cx, |diff, cx| diff.multibuffer(cx)),+ multibuffer+ );+ cx.run_until_parked();++ buffer.update(cx, |buffer, cx| buffer.set_text("later", cx));+ cx.run_until_parked();+ assert_eq!(+ multibuffer.read_with(cx, |multibuffer, cx| {+ multibuffer+ .all_buffers()+ .iter()+ .map(|buffer| buffer.read(cx).text())+ .collect::<Vec<_>>()+ }),+ ["HELLO!"]+ );+ }++ #[gpui::test]+ async fn test_finalized_diff_export_survives_resolution(cx: &mut TestAppContext) {+ let languages =+ cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));+ for (old_text, new_text, expected_changes, expected_body) in [+ (Some("same"), "same", false, ""),+ (Some("before"), "after", true, "after"),+ (Some("a\r\nb"), "a\r\nb", false, ""),+ (Some("a\nb"), "a\r\nb", false, ""),+ (None, "added", true, "added"),+ (None, "", true, ""),+ (Some(""), "", false, ""),+ (Some("removed"), "", true, ""),+ ] {+ let diff = cx.new(|_| {+ Diff::finalized(+ "test.rs".into(),+ old_text.map(str::to_string),+ new_text.to_string(),+ languages.clone(),+ )+ });+ let exported_before = cx.update(|cx| diff.read(cx).to_markdown(cx));+ assert_eq!(+ exported_before,+ format!("Diff: test.rs\n```\n{expected_body}\n```\n")+ );+ assert!(diff.read_with(cx, |diff, _| matches!(+ diff,+ Diff::Finalized(FinalizedDiff {+ state: FinalizedDiffState::Deferred(_),+ ..+ })+ )));+ assert_eq!(+ cx.update(|cx| diff.read(cx).has_changes(cx)),+ expected_changes,+ "unexpected has_changes before resolving {old_text:?} -> {new_text:?}"+ );++ let multibuffer = diff.update(cx, |diff, cx| diff.multibuffer(cx));+ assert_eq!(+ diff.update(cx, |diff, cx| diff.multibuffer(cx)),+ multibuffer+ );++ assert_eq!(+ cx.update(|cx| diff.read(cx).has_changes(cx)),+ expected_changes,+ "has_changes must not wait for the async build {old_text:?} -> {new_text:?}"+ );+ assert_eq!(+ cx.update(|cx| diff.read(cx).to_markdown(cx)),+ exported_before,+ "export must not wait for the async build {old_text:?} -> {new_text:?}"+ );++ cx.run_until_parked();++ let exported_after = cx.update(|cx| diff.read(cx).to_markdown(cx));+ assert_eq!(+ cx.update(|cx| diff.read(cx).has_changes(cx)),+ expected_changes,+ "has_changes changed when resolving {old_text:?} -> {new_text:?}"+ );+ assert_eq!(+ exported_after, exported_before,+ "export changed when resolving {old_text:?} -> {new_text:?}"+ );+ }+ }++ #[gpui::test]+ async fn test_discard_partial_edit_resolves_deferred_diff(cx: &mut TestAppContext) {+ let languages =+ cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));+ let diff = cx.new(|_| {+ Diff::finalized(+ "test.rs".into(),+ Some("before".into()),+ "after".into(),+ languages,+ )+ });++ assert!(+ diff.read_with(cx, |diff, cx| diff.has_changes(cx)),+ "deferred diff should report changes without resolution"+ );++ diff.update(cx, |diff, cx| diff.discard_partial_edit(cx));++ assert_eq!(+ diff.update(cx, |diff, cx| diff.buffer(cx).read(cx).text()),+ "before"+ );+ assert!(+ !diff.read_with(cx, |diff, cx| diff.has_changes(cx)),+ "discarding should clear has_changes before the async build completes"+ );+ cx.run_until_parked();+ assert!(!diff.read_with(cx, |diff, cx| diff.has_changes(cx)));+ assert_eq!(+ diff.read_with(cx, |diff, cx| diff.to_markdown(cx)),+ "Diff: test.rs\n```\n\n```\n"+ );}}diff --git a/crates/agent/src/tools/edit_session.rs b/crates/agent/src/tools/edit_session.rsindex 063bcf84e41..aaf2251b537 100644--- a/crates/agent/src/tools/edit_session.rs+++ b/crates/agent/src/tools/edit_session.rs@@ -248,13 +248,12 @@ impl EditSessionContext {new_text,..} => {- event_stream.update_diff(cx.new(|cx| {+ event_stream.update_diff(cx.new(|_| {Diff::finalized(input_path.to_string_lossy().into_owned(),Some(old_text.to_string()),new_text,self.language_registry.clone(),- cx,)}));Ok(())diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 396f5694530..9fbc4290be5 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -1592,7 +1592,7 @@ impl ConversationView {entry_view_state.update(cx, |view_state, cx| {for ix in 0..count {- view_state.sync_entry(ix, &thread, window, cx);+ view_state.sync_entry_initial(ix, &thread, window, cx);}list_state.splice_focusable(0..0,diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 0d7960f9a69..3e0803c0e46 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -1450,6 +1450,17 @@ impl ThreadView {!self.message_queue.is_empty()}+ fn materialize_tool_call_views(+ &mut self,+ entry_ix: usize,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.entry_view_state.update(cx, |state, cx| {+ state.materialize_entry(entry_ix, &self.thread, window, cx);+ });+ }+// eventspub fn handle_entry_view_event(@@ -8930,6 +8941,7 @@ impl ThreadView {this.entry_view_state.update(cx, |state, _cx| {state.toggle_tool_call_expansion(&id);});+ this.materialize_tool_call_views(entry_ix, window, cx);this.refresh_thread_search(window, cx);cx.notify();}@@ -9206,7 +9218,12 @@ impl ThreadView {.any(|content| matches!(content, ToolCallContent::DiffPatch { .. }));let is_cancelled_edit = is_edit && matches!(tool_call.status(), ToolCallStatus::Canceled);- let (has_revealed_diff, tool_call_output_focus, tool_call_output_focus_handle) = tool_call+ let has_diff_changes = is_cancelled_edit+ && tool_call+ .diffs()+ .next()+ .is_some_and(|diff| diff.read(cx).has_changes(cx));+ let (tool_call_output_focus, tool_call_output_focus_handle) = tool_call.diffs().next().and_then(|diff| {@@ -9215,12 +9232,11 @@ impl ThreadView {.read(cx).entry(entry_ix).and_then(|entry| entry.editor_for_diff(diff))?;- let has_revealed_diff = diff.read(cx).has_revealed_range(cx);let has_focus = editor.read(cx).is_focused(window);let focus_handle = editor.focus_handle(cx);- Some((has_revealed_diff, has_focus, focus_handle))+ Some((has_focus, focus_handle))})- .unwrap_or_else(|| (false, false, focus_handle.clone()));+ .unwrap_or((false, focus_handle.clone()));let use_card_layout = needs_confirmation || is_edit || is_terminal_tool;@@ -9499,7 +9515,7 @@ impl ThreadView {tool_call,is_edit,is_cancelled_edit,- has_revealed_diff,+ has_diff_changes,use_card_layout,window,cx,@@ -9507,7 +9523,7 @@ impl ThreadView {.child(h_flex().when(is_collapsible || failed_or_canceled, |this| {- let diff_for_discard = if has_revealed_diff+ let diff_for_discard = if has_diff_changes&& is_cancelled_edit{tool_call.diffs().next().cloned()@@ -9543,6 +9559,7 @@ impl ThreadView {);},);+ this.materialize_tool_call_views(entry_ix, window, cx);this.refresh_thread_search(window, cx);cx.notify();}@@ -9550,7 +9567,7 @@ impl ThreadView {)}).when(failed_or_canceled, |this| {- if is_cancelled_edit && !has_revealed_diff {+ if is_cancelled_edit && !has_diff_changes {this.child(div().id(entry_ix)@@ -9598,21 +9615,9 @@ impl ThreadView {let tool_call_id =tool_call_id.clone();move |this, _, _window, cx| {- let diff_data = diff.read(cx);- let base_text = diff_data- .base_text()- .clone();- let buffer =- diff_data.buffer().clone();- buffer.update(- cx,- |buffer, cx| {- buffer.set_text(- base_text.as_ref(),- cx,- );- },- );+ diff.update(cx, |diff, cx| {+ diff.discard_partial_edit(cx)+ });this.discarded_partial_edits.insert(tool_call_id.clone(),@@ -11010,7 +11015,7 @@ impl ThreadView {tool_call: &ToolCall,is_edit: bool,has_failed: bool,- has_revealed_diff: bool,+ has_diff_changes: bool,use_card_layout: bool,window: &Window,cx: &Context<Self>,@@ -11027,7 +11032,7 @@ impl ThreadView {Icon::new(IconName::ToolPencil).color(Color::Muted)};- let interrupted_edit = is_file && has_failed && has_revealed_diff;+ let interrupted_edit = is_file && has_failed && has_diff_changes;let tool_icon = if interrupted_edit {div().child(DecoratedIcon::new(@@ -11920,6 +11925,7 @@ impl ThreadView {state.toggle_tool_call_expansion(&card_id);state.is_tool_call_expanded(&card_id)});+ this.materialize_tool_call_views(entry_ix, window, cx);this.refresh_thread_search(window, cx);telemetry::event!("Subagent Toggled", expanded);cx.notify();diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex 1ffc8b6d1a9..f36f15e9b96 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -41,6 +41,18 @@ fn reindex_after_removal(index: usize, removed: &Range<usize>) -> Option<usize>}}+/// How much of a tool call's content to materialize while syncing an entry.+#[derive(Clone, Copy)]+enum ToolCallSync {+ /// Live updates: materialize visible content and run terminal lifecycle.+ Live,+ /// Thread restore: skip content that is not visible.+ Restore,+ /// First view after expansion: materialize without re-running terminal+ /// lifecycle, which would collapse the card again.+ Materialize,+}+pub struct EntryViewState {workspace: WeakEntity<Workspace>,project: WeakEntity<Project>,@@ -240,6 +252,47 @@ impl EntryViewState {window: &mut Window,cx: &mut Context<Self>,) {+ self.sync_entry_inner(index, thread, window, ToolCallSync::Live, cx);+ }++ /// Like [`Self::sync_entry`], but skips the views of tool calls that are not+ /// visible. Used when restoring a thread's history.+ pub fn sync_entry_initial(+ &mut self,+ index: usize,+ thread: &Entity<AcpThread>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.sync_entry_inner(index, thread, window, ToolCallSync::Restore, cx);+ }++ /// Materializes a tool call's diff and terminal views without running the+ /// terminal lifecycle, which would collapse an expanded card again.+ pub fn materialize_entry(+ &mut self,+ index: usize,+ thread: &Entity<AcpThread>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) {+ self.sync_entry_inner(index, thread, window, ToolCallSync::Materialize, cx);+ }++ fn sync_entry_inner(+ &mut self,+ index: usize,+ thread: &Entity<AcpThread>,+ window: &mut Window,+ tool_call_sync: ToolCallSync,+ cx: &mut Context<Self>,+ ) {+ let materialize_tool_calls = matches!(+ tool_call_sync,+ ToolCallSync::Live | ToolCallSync::Materialize+ );+ let run_terminal_lifecycle =+ matches!(tool_call_sync, ToolCallSync::Live | ToolCallSync::Restore);let Some(thread_entry) = thread.read(cx).entries().get(index) else {return;};@@ -315,6 +368,8 @@ impl EntryViewState {}AgentThreadEntry::ToolCall(tool_call) => {let id = tool_call.id.clone();+ let materialize_content =+ materialize_tool_calls || self.is_tool_call_content_visible(tool_call);let terminals = tool_call.terminals().cloned().collect::<Vec<_>>();let diffs = tool_call.diffs().cloned().collect::<Vec<_>>();let patch_hunk_buffers = tool_call@@ -334,117 +389,152 @@ impl EntryViewState {.map(|buffer| buffer.entity_id()).collect();- let views = if let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) {- &mut tool_call.content- } else {- self.set_entry(- index,- Entry::ToolCall(ToolCallEntry {- content: HashMap::default(),- patch_hunk_ids: HashSet::default(),- focus_handle: cx.focus_handle(),- }),- );- let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) else {- unreachable!()+ let tool_call_entry =+ if let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) {+ tool_call+ } else {+ self.set_entry(+ index,+ Entry::ToolCall(ToolCallEntry {+ content: HashMap::default(),+ patch_hunk_ids: HashSet::default(),+ restored_view_ids: HashSet::default(),+ focus_handle: cx.focus_handle(),+ }),+ );+ let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) else {+ unreachable!()+ };+ tool_call};- &mut tool_call.content- };+ let ToolCallEntry {+ content: views,+ restored_view_ids,+ ..+ } = tool_call_entry;let is_tool_call_completed =matches!(tool_call.status(), acp_thread::ToolCallStatus::Completed);-- for terminal in terminals {- match views.entry(terminal.entity_id()) {- collections::hash_map::Entry::Vacant(entry) => {- let element = create_terminal(- self.workspace.clone(),- self.project.clone(),- terminal.clone(),- window,- cx,- )- .into_any();- cx.emit(EntryViewEvent {- entry_index: index,- view_event: ViewEvent::NewTerminal(id.clone()),- });- entry.insert(element);- }- collections::hash_map::Entry::Occupied(_entry) => {- let terminal = terminal.read(cx);- if is_tool_call_completed- && terminal.is_process_backed()- && terminal.output().is_none()- {- cx.emit(EntryViewEvent {- entry_index: index,- view_event: ViewEvent::TerminalMovedToBackground(id.clone()),- });+ let emit_new_view_events = matches!(tool_call_sync, ToolCallSync::Live);++ if materialize_content {+ for terminal in terminals {+ let terminal_id = terminal.entity_id();+ match views.entry(terminal_id) {+ collections::hash_map::Entry::Vacant(entry) => {+ let element = create_terminal(+ self.workspace.clone(),+ self.project.clone(),+ terminal.clone(),+ window,+ cx,+ )+ .into_any();+ let was_restored = restored_view_ids.remove(&terminal_id);+ if emit_new_view_events && !was_restored {+ cx.emit(EntryViewEvent {+ entry_index: index,+ view_event: ViewEvent::NewTerminal(id.clone()),+ });+ }+ entry.insert(element);+ }+ collections::hash_map::Entry::Occupied(_entry) => {+ let terminal = terminal.read(cx);+ if run_terminal_lifecycle+ && is_tool_call_completed+ && terminal.is_process_backed()+ && terminal.output().is_none()+ {+ cx.emit(EntryViewEvent {+ entry_index: index,+ view_event: ViewEvent::TerminalMovedToBackground(+ id.clone(),+ ),+ });+ }}}}- }- for diff in diffs {- views.entry(diff.entity_id()).or_insert_with(|| {- let editor = create_editor_diff(diff.clone(), window, cx);- cx.subscribe(&editor, {- let diff = diff.clone();- let entry_index = index;- move |_this, _editor, event: &EditorEvent, cx| {- if let EditorEvent::OpenExcerptsRequested {- selections_by_buffer,- split,- } = event- {- let multibuffer = diff.read(cx).multibuffer();- if let Some((buffer_id, (ranges, _))) =- selections_by_buffer.iter().next()+ for diff in diffs {+ let diff_id = diff.entity_id();+ if let collections::hash_map::Entry::Vacant(entry) = views.entry(diff_id) {+ let multibuffer = diff.update(cx, |diff, cx| diff.multibuffer(cx));+ let editor =+ create_multibuffer_diff_editor(multibuffer.clone(), window, cx);+ cx.subscribe(&editor, {+ let diff = diff.clone();+ let entry_index = index;+ move |_this, _editor, event: &EditorEvent, cx| {+ if let EditorEvent::OpenExcerptsRequested {+ selections_by_buffer,+ split,+ } = event{- if let Some(buffer) =- multibuffer.read(cx).buffer(*buffer_id)+ if let Some((buffer_id, (ranges, _))) =+ selections_by_buffer.iter().next(){- if let Some(range) = ranges.first() {- let point =- buffer.read(cx).offset_to_point(range.start.0);- if let Some(path) = diff.read(cx).file_path(cx) {- cx.emit(EntryViewEvent {- entry_index,- view_event: ViewEvent::OpenDiffLocation {- path,- position: point,- split: *split,- },- });+ if let Some(buffer) =+ multibuffer.read(cx).buffer(*buffer_id)+ {+ if let Some(range) = ranges.first() {+ let point = buffer+ .read(cx)+ .offset_to_point(range.start.0);+ if let Some(path) = diff.read(cx).file_path(cx)+ {+ cx.emit(EntryViewEvent {+ entry_index,+ view_event:+ ViewEvent::OpenDiffLocation {+ path,+ position: point,+ split: *split,+ },+ });+ }}}}}}+ })+ .detach();+ let was_restored = restored_view_ids.remove(&diff_id);+ if emit_new_view_events && !was_restored {+ cx.emit(EntryViewEvent {+ entry_index: index,+ view_event: ViewEvent::NewDiff(id.clone()),+ });}- })- .detach();- cx.emit(EntryViewEvent {- entry_index: index,- view_event: ViewEvent::NewDiff(id.clone()),- });- editor.into_any()- });- }- for buffer in patch_hunk_buffers {- views.entry(buffer.entity_id()).or_insert_with(|| {- let editor = create_multibuffer_diff_editor(buffer, window, cx);- cx.emit(EntryViewEvent {- entry_index: index,- view_event: ViewEvent::NewDiff(id.clone()),- });- editor.into_any()- });+ entry.insert(editor.into_any());+ }+ }+ for buffer in patch_hunk_buffers {+ let buffer_id = buffer.entity_id();+ if let collections::hash_map::Entry::Vacant(entry) = views.entry(buffer_id)+ {+ let editor = create_multibuffer_diff_editor(buffer, window, cx);+ let was_restored = restored_view_ids.remove(&buffer_id);+ if emit_new_view_events && !was_restored {+ cx.emit(EntryViewEvent {+ entry_index: index,+ view_event: ViewEvent::NewDiff(id.clone()),+ });+ }+ entry.insert(editor.into_any());+ }+ }+ } else {+ restored_view_ids.extend(terminals.iter().map(|terminal| terminal.entity_id()));+ restored_view_ids.extend(diffs.iter().map(|diff| diff.entity_id()));+ restored_view_ids.extend(patch_hunk_ids.iter().copied());}if let Some(Entry::ToolCall(entry)) = self.entries.get_mut(index) {for stale_id in entry.patch_hunk_ids.difference(&patch_hunk_ids) {entry.content.remove(stale_id);+ entry.restored_view_ids.remove(stale_id);}entry.patch_hunk_ids = patch_hunk_ids;}@@ -597,6 +687,7 @@ impl AssistantMessageEntry {pub struct ToolCallEntry {content: HashMap<EntityId, AnyEntity>,patch_hunk_ids: HashSet<EntityId>,+ restored_view_ids: HashSet<EntityId>,focus_handle: FocusHandle,}@@ -749,14 +840,6 @@ fn create_terminal(})}-fn create_editor_diff(- diff: Entity<acp_thread::Diff>,- window: &mut Window,- cx: &mut App,-) -> Entity<Editor> {- create_multibuffer_diff_editor(diff.read(cx).multibuffer().clone(), window, cx)-}-fn create_multibuffer_diff_editor(multibuffer: Entity<MultiBuffer>,window: &mut Window,@@ -810,6 +893,7 @@ fn diff_editor_text_style_refinement(cx: &mut App) -> TextStyleRefinement {#[cfg(test)]mod tests {+ use std::cell::Cell;use std::path::Path;use std::rc::Rc;use std::sync::Arc;@@ -822,7 +906,7 @@ mod tests {use gpui::{AppContext as _, TestAppContext};use parking_lot::RwLock;- use crate::entry_view_state::{Entry, EntryViewState};+ use crate::entry_view_state::{Entry, EntryViewEvent, EntryViewState, ToolCallSync, ViewEvent};use crate::message_editor::SessionCapabilities;use multi_buffer::MultiBufferRow;use pretty_assertions::assert_matches;@@ -866,92 +950,127 @@ mod tests {cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());- let tool_call = acp_v1::ToolCall::new("tool", "Tool call")- .status(acp_v1::ToolCallStatus::InProgress)- .content(vec![acp_v1::ToolCallContent::Diff(- acp_v1::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),- )]);- let connection = Rc::new(StubAgentConnection::new());- let thread = cx- .update(|_, cx| {- connection.clone().new_session(- project.clone(),- PathList::new(&[Path::new(path!("/project"))]),- cx,+ for sync_mode in [ToolCallSync::Live, ToolCallSync::Materialize] {+ let tool_call = acp_v1::ToolCall::new("tool", "Tool call")+ .status(acp_v1::ToolCallStatus::InProgress)+ .content(vec![acp_v1::ToolCallContent::Diff(+ acp_v1::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),+ )]);+ let connection = Rc::new(StubAgentConnection::new());+ let thread = cx+ .update(|_, cx| {+ connection.clone().new_session(+ project.clone(),+ PathList::new(&[Path::new(path!("/project"))]),+ cx,+ )+ })+ .await+ .unwrap();+ let session_id = thread.update(cx, |thread, _| thread.session_id().clone());++ cx.update(|_, cx| {+ connection.send_update(session_id, acp_v1::SessionUpdate::ToolCall(tool_call), cx)+ });++ let view_state = cx.new(|_cx| {+ EntryViewState::new(+ workspace.downgrade(),+ project.downgrade(),+ None,+ Arc::new(RwLock::new(SessionCapabilities::default())),+ "Test Agent".into(),)- })- .await- .unwrap();- let session_id = thread.update(cx, |thread, _| thread.session_id().clone());-- cx.update(|_, cx| {- connection.send_update(session_id, acp_v1::SessionUpdate::ToolCall(tool_call), cx)- });+ });++ view_state.update_in(cx, |view_state, window, cx| {+ view_state.sync_entry_initial(0, &thread, window, cx)+ });++ let diff = thread.read_with(cx, |thread, _| {+ thread+ .entries()+ .get(0)+ .unwrap()+ .diffs()+ .next()+ .unwrap()+ .clone()+ });++ view_state.read_with(cx, |view_state, _cx| {+ assert!(+ view_state+ .entry(0)+ .unwrap()+ .editor_for_diff(&diff)+ .is_none(),+ "restoring history should not build a diff editor for a collapsed tool call"+ );+ });++ let saw_new_diff = Rc::new(Cell::new(false));+ let _subscription = cx.update(|_, cx| {+ let saw_new_diff = saw_new_diff.clone();+ cx.subscribe(&view_state, move |_, event: &EntryViewEvent, _| {+ if matches!(event.view_event, ViewEvent::NewDiff(_)) {+ saw_new_diff.set(true);+ }+ })+ });- let thread_store = None;+ view_state.update_in(cx, |view_state, window, cx| {+ view_state.sync_entry_inner(0, &thread, window, sync_mode, cx)+ });- let view_state = cx.new(|_cx| {- EntryViewState::new(- workspace.downgrade(),- project.downgrade(),- thread_store,- Arc::new(RwLock::new(SessionCapabilities::default())),- "Test Agent".into(),- )- });+ cx.run_until_parked();- view_state.update_in(cx, |view_state, window, cx| {- view_state.sync_entry(0, &thread, window, cx)- });+ assert!(+ !saw_new_diff.get(),+ "materializing a restored diff must not emit NewDiff"+ );- let diff = thread.read_with(cx, |thread, _| {- thread- .entries()- .get(0)- .unwrap()- .diffs()- .next()- .unwrap()- .clone()- });-- cx.run_until_parked();-- let diff_editor = view_state.read_with(cx, |view_state, _cx| {- view_state.entry(0).unwrap().editor_for_diff(&diff).unwrap()- });- assert_eq!(- diff_editor.read_with(cx, |editor, cx| editor.text(cx)),- "hi world\nhello world"- );- let row_infos = diff_editor.read_with(cx, |editor, cx| {- let multibuffer = editor.buffer().read(cx);- multibuffer- .snapshot(cx)- .row_infos(MultiBufferRow(0))- .collect::<Vec<_>>()- });- assert_matches!(- row_infos.as_slice(),- [- RowInfo {- multibuffer_row: Some(MultiBufferRow(0)),- diff_status: Some(DiffHunkStatus {- kind: DiffHunkStatusKind::Deleted,+ let diff_editor = view_state.read_with(cx, |view_state, _cx| {+ let entry = view_state.entry(0).unwrap();+ let Entry::ToolCall(tool_call) = entry else {+ panic!("expected tool call");+ };+ assert!(tool_call.restored_view_ids.is_empty());+ entry.editor_for_diff(&diff).unwrap()+ });+ assert_eq!(+ diff_editor.read_with(cx, |editor, cx| editor.text(cx)),+ "hi world\nhello world"+ );+ let row_infos = diff_editor.read_with(cx, |editor, cx| {+ let multibuffer = editor.buffer().read(cx);+ multibuffer+ .snapshot(cx)+ .row_infos(MultiBufferRow(0))+ .collect::<Vec<_>>()+ });+ assert_matches!(+ row_infos.as_slice(),+ [+ RowInfo {+ multibuffer_row: Some(MultiBufferRow(0)),+ diff_status: Some(DiffHunkStatus {+ kind: DiffHunkStatusKind::Deleted,+ ..+ }),..- }),- ..- },- RowInfo {- multibuffer_row: Some(MultiBufferRow(1)),- diff_status: Some(DiffHunkStatus {- kind: DiffHunkStatusKind::Added,+ },+ RowInfo {+ multibuffer_row: Some(MultiBufferRow(1)),+ diff_status: Some(DiffHunkStatus {+ kind: DiffHunkStatusKind::Added,+ ..+ }),..- }),- ..- }- ]- );+ }+ ]+ );+ }}#[gpui::test]