Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Add shared tool-call state and diff previews (#64875)
Ben Brandt986828d15713
diff --git a/Cargo.lock b/Cargo.lockindex 12aae028775..07f7172ded4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -95,6 +95,7 @@ dependencies = ["buffer_diff","chrono","collections",+ "diffy","env_logger 0.11.8","feature_flags","file_icons",diff --git a/Cargo.toml b/Cargo.tomlindex a8e1cd85ab1..abec5e2530a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -620,6 +620,7 @@ derive_more = { version = "2.1.1", features = ["not",] }dialoguer = { version = "0.12", default-features = false }+diffy = "0.4.2"dirs = "6.0"documented = "0.10"dotenvy = "0.15.0"diff --git a/crates/acp_thread/Cargo.toml b/crates/acp_thread/Cargo.tomlindex 0cd63169ada..05aad4f3ad7 100644--- a/crates/acp_thread/Cargo.toml+++ b/crates/acp_thread/Cargo.toml@@ -25,6 +25,7 @@ anyhow.workspace = truebuffer_diff.workspace = truechrono.workspace = truecollections.workspace = true+diffy.workspace = truefeature_flags.workspace = truemulti_buffer.workspace = truefile_icons.workspace = truediff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex e1b2265b3d5..5a4a6fdb447 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -45,7 +45,7 @@ use task::{Shell, ShellBuilder};pub use terminal::*;use text::Bias;use ui::App;-use util::markdown::MarkdownEscaped;+use util::markdown::{MarkdownCodeBlock, MarkdownEscaped};use util::path_list::PathList;use util::{ResultExt, get_default_system_shell_preferring_bash,@@ -1020,9 +1020,13 @@ pub struct ToolCall {pub id: acp_v1::ToolCallId,pub label: Entity<Markdown>,title: Option<SharedString>,- pub kind: acp_v1::ToolKind,+ pub name: Option<SharedString>,+ pub reported_kind: Option<acp_v2::ToolKind>,+ pub reported_status: Option<acp_v2::ToolCallStatus>,+ pub meta: Option<acp_v2::Meta>,structured_content: Vec<ToolCallContent>,- pub status: ToolCallStatus,+ local_status: Option<ToolCallStatus>,+ authorization: Option<ToolCallAuthorization>,pub locations: Vec<acp_v1::ToolCallLocation>,pub resolved_locations: Vec<Option<AgentLocation>>,pub raw_input: Option<serde_json::Value>,@@ -1039,58 +1043,196 @@ pub struct ToolCall {pub sandbox_not_applied: Option<SandboxNotAppliedReason>,}+#[derive(Debug)]+pub struct ToolCallAuthorization {+ pub options: PermissionOptions,+ pub kind: AuthorizationKind,+ respond_tx: oneshot::Sender<RequestPermissionOutcome>,+}++struct ToolCallPatch {+ title: MaybeUndefined<String>,+ name: MaybeUndefined<String>,+ kind: MaybeUndefined<acp_v2::ToolKind>,+ status: MaybeUndefined<acp_v2::ToolCallStatus>,+ content: MaybeUndefined<ToolContentPatch>,+ locations: MaybeUndefined<Vec<acp_v1::ToolCallLocation>>,+ raw_input: MaybeUndefined<serde_json::Value>,+ raw_output: MaybeUndefined<serde_json::Value>,+ meta: ToolMetadataPatch,+}++enum ToolContentPatch {+ Legacy(Vec<acp_v1::ToolCallContent>),+ Protocol(Vec<acp_v2::ToolCallContent>),+}++impl ToolContentPatch {+ fn prepare(+ self,+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,+ ) -> Result<Vec<PreparedToolCallContent>> {+ match self {+ Self::Legacy(content) => PreparedToolCallContent::prepare(content, terminals),+ Self::Protocol(content) => PreparedToolCallContent::prepare_v2(content, terminals),+ }+ }+}++enum ToolMetadataPatch {+ Legacy(Option<acp_v1::Meta>),+ Protocol(MaybeUndefined<acp_v2::Meta>),+}++fn legacy_tool_field<T>(value: Option<T>) -> MaybeUndefined<T> {+ value.map(MaybeUndefined::Value).unwrap_or_default()+}++fn tool_kind_from_v1(kind: acp_v1::ToolKind) -> Option<acp_v2::ToolKind> {+ Some(match kind {+ acp_v1::ToolKind::Read => acp_v2::ToolKind::Read,+ acp_v1::ToolKind::Edit => acp_v2::ToolKind::Edit,+ acp_v1::ToolKind::Delete => acp_v2::ToolKind::Delete,+ acp_v1::ToolKind::Move => acp_v2::ToolKind::Move,+ acp_v1::ToolKind::Search => acp_v2::ToolKind::Search,+ acp_v1::ToolKind::Execute => acp_v2::ToolKind::Execute,+ acp_v1::ToolKind::Think => acp_v2::ToolKind::Think,+ acp_v1::ToolKind::Fetch => acp_v2::ToolKind::Fetch,+ acp_v1::ToolKind::SwitchMode => acp_v2::ToolKind::SwitchMode,+ acp_v1::ToolKind::Other => acp_v2::ToolKind::Other,+ _ => return None,+ })+}++fn tool_status_from_v1(status: acp_v1::ToolCallStatus) -> Option<acp_v2::ToolCallStatus> {+ Some(match status {+ acp_v1::ToolCallStatus::Pending => acp_v2::ToolCallStatus::Pending,+ acp_v1::ToolCallStatus::InProgress => acp_v2::ToolCallStatus::InProgress,+ acp_v1::ToolCallStatus::Completed => acp_v2::ToolCallStatus::Completed,+ acp_v1::ToolCallStatus::Failed => acp_v2::ToolCallStatus::Failed,+ _ => return None,+ })+}++impl ToolCallPatch {+ fn legacy(fields: acp_v1::ToolCallUpdateFields, meta: Option<acp_v1::Meta>) -> Self {+ Self {+ title: legacy_tool_field(fields.title),+ name: legacy_tool_field(fields.name),+ kind: legacy_tool_field(fields.kind.and_then(tool_kind_from_v1)),+ status: legacy_tool_field(fields.status.and_then(tool_status_from_v1)),+ content: legacy_tool_field(fields.content.map(ToolContentPatch::Legacy)),+ locations: legacy_tool_field(fields.locations),+ raw_input: legacy_tool_field(fields.raw_input),+ raw_output: legacy_tool_field(fields.raw_output),+ meta: ToolMetadataPatch::Legacy(meta),+ }+ }++ fn protocol(update: acp_v2::ToolCallUpdate) -> Self {+ Self {+ title: update.title,+ name: update.name,+ kind: update.kind,+ status: update.status,+ content: update.content.map_value(ToolContentPatch::Protocol),+ // Unlike v2 AbsolutePath, this also preserves relative native paths.+ locations: update.locations.map_value(|locations| {+ locations+ .into_iter()+ .map(|location| {+ acp_v1::ToolCallLocation::new(location.path.0)+ .line(location.line)+ .meta(location.meta)+ })+ .collect()+ }),+ raw_input: update.raw_input,+ raw_output: update.raw_output,+ meta: ToolMetadataPatch::Protocol(update.meta),+ }+ }+}+impl ToolCall {fn from_acp(tool_call: acp_v1::ToolCall,- status: ToolCallStatus,+ status: Option<ToolCallStatus>,+ language_registry: Arc<LanguageRegistry>,+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,+ cx: &mut App,+ ) -> Result<Self> {+ let update = acp_v1::ToolCallUpdate::from(tool_call);+ let mut call = Self::from_patch(+ update.tool_call_id,+ ToolCallPatch::legacy(update.fields, update.meta),+ language_registry,+ terminals,+ cx,+ )?;+ if let Some(status) = status {+ call.set_legacy_status(status);+ }+ Ok(call)+ }++ fn from_patch(+ id: acp_v1::ToolCallId,+ patch: ToolCallPatch,language_registry: Arc<LanguageRegistry>,terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,cx: &mut App,) -> Result<Self> {- let title =- Some(SharedString::from(tool_call.title)).filter(|title| !title.trim().is_empty());- let content = PreparedToolCallContent::prepare(tool_call.content, terminals)?+ let content = patch+ .content+ .take()+ .map(|content| content.prepare(terminals))+ .transpose()?+ .unwrap_or_default().into_iter().map(|item| ToolCallContent::from_prepared(item, &language_registry, cx)).collect();-- let raw_input_markdown = tool_call- .raw_input+ let title = patch.title.take().map(SharedString::from);+ let name = patch.name.take().map(SharedString::from);+ let kind = patch.kind.take();+ let raw_input = patch.raw_input.take();+ let raw_input_markdown = raw_input.as_ref().and_then(|input| markdown_for_raw_output(input, &language_registry, cx));-- let tool_name = tool_call- .name- .map(SharedString::from)- .or_else(|| tool_name_from_meta(&tool_call.meta));-- let subagent_session_info = subagent_session_info_from_meta(&tool_call.meta);- let sandbox_authorization_details =- sandbox_authorization_details_from_meta(&tool_call.meta);+ let meta = match patch.meta {+ ToolMetadataPatch::Legacy(meta) => meta,+ ToolMetadataPatch::Protocol(meta) => meta.take(),+ };+ let tool_name = name.clone().or_else(|| tool_name_from_meta(&meta));+ let subagent_session_info = subagent_session_info_from_meta(&meta);+ let sandbox_authorization_details = sandbox_authorization_details_from_meta(&meta);let sandbox_fallback_authorization_details =- sandbox_fallback_authorization_details_from_meta(&tool_call.meta);- let sandbox_not_applied = sandbox_not_applied_from_meta(&tool_call.meta);-+ sandbox_fallback_authorization_details_from_meta(&meta);+ let sandbox_not_applied = sandbox_not_applied_from_meta(&meta);let label = Self::new_label(- title.as_ref(),+ title.as_ref().filter(|title| !title.trim().is_empty()),tool_name.as_ref(),- tool_call.kind,+ kind.as_ref().unwrap_or(&acp_v2::ToolKind::Other),language_registry.clone(),cx,);let mut result = Self {- id: tool_call.tool_call_id,+ id,label,title,- kind: tool_call.kind,+ name,+ reported_kind: kind,+ reported_status: patch.status.take(),+ meta,structured_content: content,- locations: tool_call.locations,+ locations: patch.locations.take().unwrap_or_default(),resolved_locations: Vec::default(),- status,- raw_input: tool_call.raw_input,+ local_status: None,+ authorization: None,+ raw_input,raw_input_markdown,- raw_output: tool_call.raw_output,+ raw_output: patch.raw_output.take(),raw_output_content: None,tool_name,subagent_session_info,@@ -1102,10 +1244,56 @@ impl ToolCall {Ok(result)}+ pub fn kind(&self) -> &acp_v2::ToolKind {+ self.reported_kind+ .as_ref()+ .unwrap_or(&acp_v2::ToolKind::Other)+ }++ pub fn status(&self) -> ToolCallStatus {+ if self.authorization.is_some() {+ ToolCallStatus::WaitingForConfirmation+ } else {+ self.underlying_status()+ }+ }++ pub fn authorization(&self) -> Option<&ToolCallAuthorization> {+ self.authorization.as_ref()+ }++ fn underlying_status(&self) -> ToolCallStatus {+ self.local_status+ .or_else(|| ToolCallStatus::from_reported(self.reported_status.as_ref()))+ .unwrap_or(ToolCallStatus::Pending)+ }++ fn permission_status(&self) -> Option<acp_v1::ToolCallStatus> {+ self.local_status+ .or_else(|| ToolCallStatus::from_reported(self.reported_status.as_ref()))+ .and_then(|status| status.as_acp_status())+ }++ fn set_legacy_status(&mut self, status: ToolCallStatus) {+ self.local_status = (Some(status)+ != ToolCallStatus::from_reported(self.reported_status.as_ref()))+ .then_some(status);+ }++ fn set_local_status(&mut self, status: ToolCallStatus) {+ // An explicit decision survives a later clear of reported information,+ // even if the two statuses happen to agree right now.+ self.local_status = Some(status);+ }++ fn effective_title(&self) -> Option<&SharedString> {+ self.title.as_ref().filter(|title| !title.trim().is_empty())+ }+fn label_text(title: Option<&SharedString>,tool_name: Option<&SharedString>,- kind: acp_v1::ToolKind,+ kind: &acp_v2::ToolKind,) -> SharedString {let Some(title) = title else {return tool_name@@ -1114,9 +1302,9 @@ impl ToolCall {.unwrap_or_else(|| "Tool call".into());};- if kind == acp_v1::ToolKind::Execute {+ if kind == &acp_v2::ToolKind::Execute {title.clone()- } else if kind == acp_v1::ToolKind::Edit {+ } else if kind == &acp_v2::ToolKind::Edit {MarkdownEscaped(title).to_string().into()} else if let Some((first_line, _)) = title.split_once('\n') {(first_line.to_owned() + "…").into()@@ -1128,13 +1316,13 @@ impl ToolCall {fn new_label(title: Option<&SharedString>,tool_name: Option<&SharedString>,- kind: acp_v1::ToolKind,+ kind: &acp_v2::ToolKind,language_registry: Arc<LanguageRegistry>,cx: &mut App,) -> Entity<Markdown> {let text = Self::label_text(title, tool_name, kind);cx.new(|cx| {- if title.is_none() || kind == acp_v1::ToolKind::Execute {+ if title.is_none() || kind == &acp_v2::ToolKind::Execute {Markdown::new_text(text, cx)} else {Markdown::new(text, Some(language_registry), None, cx)@@ -1150,7 +1338,22 @@ impl ToolCall {terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,cx: &mut App,) -> Result<()> {- let acp_v1::ToolCallUpdateFields {+ self.apply_patch(+ ToolCallPatch::legacy(fields, meta),+ language_registry,+ terminals,+ cx,+ )+ }++ fn apply_patch(+ &mut self,+ patch: ToolCallPatch,+ language_registry: Arc<LanguageRegistry>,+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,+ cx: &mut App,+ ) -> Result<()> {+ let ToolCallPatch {kind,status,title,@@ -1159,57 +1362,80 @@ impl ToolCall {locations,raw_input,raw_output,- ..- } = fields;- let output_changed = content.is_some() || raw_output.is_some();+ meta,+ } = patch;+ let output_changed = !content.is_undefined() || !raw_output.is_undefined();// Completion remains authoritative even when output cannot be displayed;// otherwise a finished tool could leave its permission request waiting.- if let Some(status) = status {- self.update_acp_status(status);- }+ self.apply_reported_status(status);// Prepare all content before changing presentation fields or shared// display entities; cloning their handles would not isolate mutations.- let content = content- .map(|content| PreparedToolCallContent::prepare(content, terminals))- .transpose()?;-- let was_plain_text = self.title.is_none() || self.kind == acp_v1::ToolKind::Execute;- let mut label_changed = title.is_some() || kind.is_some();- if let Some(kind) = kind {- self.kind = kind;- }-- if let Some(tool_name) = name.map(SharedString::from) {- self.tool_name = Some(tool_name);- label_changed = true;- } else if self.tool_name.is_none() {- // Legacy metadata only fills a missing name so it cannot replace a- // first-class name received earlier.- self.tool_name = tool_name_from_meta(&meta);- label_changed |= self.tool_name.is_some();- }-- if let Some(subagent_session_info) = subagent_session_info_from_meta(&meta) {- self.subagent_session_info = Some(subagent_session_info);- }- if let Some(sandbox_authorization_details) = sandbox_authorization_details_from_meta(&meta)- {- self.sandbox_authorization_details = Some(sandbox_authorization_details);+ let content = match content {+ MaybeUndefined::Undefined => None,+ MaybeUndefined::Null => Some(Vec::new()),+ MaybeUndefined::Value(content) => Some(content.prepare(terminals)?),+ };+ let was_plain_text =+ self.effective_title().is_none() || self.kind() == &acp_v2::ToolKind::Execute;+ let mut label_changed = !title.is_undefined() || !kind.is_undefined();+ if !kind.is_undefined() {+ self.reported_kind = kind.take();}- if let Some(sandbox_fallback_authorization_details) =- sandbox_fallback_authorization_details_from_meta(&meta)- {- self.sandbox_fallback_authorization_details =- Some(sandbox_fallback_authorization_details);+ let name_changed = !name.is_undefined();+ if name_changed {+ self.name = name.take().map(SharedString::from);}- if let Some(sandbox_not_applied) = sandbox_not_applied_from_meta(&meta) {- self.sandbox_not_applied = Some(sandbox_not_applied);+ let old_tool_name = self.tool_name.clone();+ match meta {+ ToolMetadataPatch::Legacy(meta) => {+ if name_changed {+ self.tool_name = self.name.clone();+ } else if self.tool_name.is_none() {+ self.tool_name = tool_name_from_meta(&meta);+ }+ // Legacy extension hints are sticky; omitted or malformed hints+ // have never cleared values received in an earlier v1 update.+ if let Some(value) = subagent_session_info_from_meta(&meta) {+ self.subagent_session_info = Some(value);+ }+ if let Some(value) = sandbox_authorization_details_from_meta(&meta) {+ self.sandbox_authorization_details = Some(value);+ }+ if let Some(value) = sandbox_fallback_authorization_details_from_meta(&meta) {+ self.sandbox_fallback_authorization_details = Some(value);+ }+ if let Some(value) = sandbox_not_applied_from_meta(&meta) {+ self.sandbox_not_applied = Some(value);+ }+ if meta.is_some() {+ self.meta = meta;+ }+ }+ ToolMetadataPatch::Protocol(meta) => {+ let meta_changed = !meta.is_undefined();+ if meta_changed {+ self.meta = meta.take();+ self.subagent_session_info = subagent_session_info_from_meta(&self.meta);+ self.sandbox_authorization_details =+ sandbox_authorization_details_from_meta(&self.meta);+ self.sandbox_fallback_authorization_details =+ sandbox_fallback_authorization_details_from_meta(&self.meta);+ self.sandbox_not_applied = sandbox_not_applied_from_meta(&self.meta);+ }+ if name_changed || meta_changed {+ self.tool_name = self+ .name+ .clone()+ .or_else(|| tool_name_from_meta(&self.meta));+ }+ }}+ label_changed |= self.tool_name != old_tool_name;- if let Some(title) = title {- self.title = Some(SharedString::from(title)).filter(|title| !title.trim().is_empty());- if self.kind == acp_v1::ToolKind::Execute- && let Some(title) = &self.title+ if !title.is_undefined() {+ self.title = title.take().map(SharedString::from);+ if self.kind() == &acp_v2::ToolKind::Execute+ && let Some(title) = self.effective_title(){// A missing tool title must not overwrite an actual terminal command.for terminal in self.terminals() {@@ -1220,18 +1446,19 @@ impl ToolCall {}}if label_changed {- let is_plain_text = self.title.is_none() || self.kind == acp_v1::ToolKind::Execute;+ let is_plain_text =+ self.effective_title().is_none() || self.kind() == &acp_v2::ToolKind::Execute;if was_plain_text != is_plain_text {self.label = Self::new_label(- self.title.as_ref(),+ self.effective_title(),self.tool_name.as_ref(),- self.kind,+ self.kind(),language_registry.clone(),cx,);} else {let text =- Self::label_text(self.title.as_ref(), self.tool_name.as_ref(), self.kind);+ Self::label_text(self.effective_title(), self.tool_name.as_ref(), self.kind());if self.label.read(cx).source() != &text {self.label.update(cx, |label, cx| label.replace(text, cx));}@@ -1255,30 +1482,35 @@ impl ToolCall {self.structured_content.truncate(new_content_len);}- if let Some(locations) = locations {- self.locations = locations;+ if !locations.is_undefined() {+ let locations = locations.take().unwrap_or_default();+ if self.locations != locations {+ self.locations = locations;+ self.resolved_locations.clear();+ }}- if let Some(raw_input) = raw_input- && self.raw_input.as_ref() != Some(&raw_input)- {- match (- self.raw_input_markdown.as_ref(),- raw_output_text(&raw_input),- ) {- (Some(markdown), Some(text)) => update_markdown_in_place(markdown, &text, cx),- (_, Some(text)) => {- self.raw_input_markdown = Some(cx.new(|cx| {- Markdown::new(text.into(), Some(language_registry.clone()), None, cx)- }));+ if !raw_input.is_undefined() {+ let raw_input = raw_input.take();+ if self.raw_input != raw_input {+ match (+ self.raw_input_markdown.as_ref(),+ raw_input.as_ref().and_then(raw_output_text),+ ) {+ (Some(markdown), Some(text)) => update_markdown_in_place(markdown, &text, cx),+ (_, Some(text)) => {+ self.raw_input_markdown = Some(cx.new(|cx| {+ Markdown::new(text.into(), Some(language_registry.clone()), None, cx)+ }));+ }+ (_, None) => self.raw_input_markdown = None,}- (_, None) => self.raw_input_markdown = None,+ self.raw_input = raw_input;}- self.raw_input = Some(raw_input);}- if let Some(raw_output) = raw_output {- self.raw_output = Some(raw_output);+ if !raw_output.is_undefined() {+ self.raw_output = raw_output.take();}if output_changed {self.update_raw_output_content(&language_registry, cx);@@ -1299,16 +1531,19 @@ impl ToolCall {self.raw_output_content = None;return;};- if let Some(ToolCallContent::ContentBlock(block)) = self.raw_output_content.as_deref()- && let Some(markdown) = block.markdown()+ if let Some(markdown) = self+ .raw_output_content+ .as_deref()+ .and_then(ToolCallContent::markdown){update_markdown_in_place(markdown, &text, cx);} else {let markdown =cx.new(|cx| Markdown::new(text.into(), Some(language_registry.clone()), None, cx));- self.raw_output_content = Some(Box::new(ToolCallContent::ContentBlock(- ContentBlock::from_markdown(markdown),- )));+ self.raw_output_content = Some(Box::new(ToolCallContent::ContentBlock {+ block: ContentBlock::from_markdown(markdown),+ meta: None,+ }));}}@@ -1323,30 +1558,26 @@ impl ToolCall {}}- fn update_status(&mut self, status: ToolCallStatus) {+ fn apply_reported_status(&mut self, status: MaybeUndefined<acp_v2::ToolCallStatus>) {match status {- ToolCallStatus::Pending => self.update_acp_status(acp_v1::ToolCallStatus::Pending),- ToolCallStatus::InProgress => {- self.update_acp_status(acp_v1::ToolCallStatus::InProgress)+ MaybeUndefined::Undefined => {}+ MaybeUndefined::Null => {+ // Clearing reported information does not resolve a local request+ // or undo a user's local decision.+ self.reported_status = None;+ }+ MaybeUndefined::Value(status) => {+ if matches!(+ status,+ acp_v2::ToolCallStatus::Completed+ | acp_v2::ToolCallStatus::Failed+ | acp_v2::ToolCallStatus::Cancelled+ ) {+ self.authorization = None;+ }+ self.reported_status = Some(status);+ self.local_status = None;}- ToolCallStatus::Completed => self.update_acp_status(acp_v1::ToolCallStatus::Completed),- ToolCallStatus::Failed => self.update_acp_status(acp_v1::ToolCallStatus::Failed),- status @ (ToolCallStatus::WaitingForConfirmation { .. }- | ToolCallStatus::Rejected- | ToolCallStatus::Canceled) => self.status = status,- }- }-- fn update_acp_status(&mut self, status: acp_v1::ToolCallStatus) {- if let ToolCallStatus::WaitingForConfirmation { current_status, .. } = &mut self.status- && matches!(- status,- acp_v1::ToolCallStatus::Pending | acp_v1::ToolCallStatus::InProgress- )- {- *current_status = status;- } else {- self.status = status.into();}}@@ -1354,9 +1585,10 @@ impl ToolCall {self.structured_content.iter().filter_map(|content| match content {- ToolCallContent::Diff(diff) => Some(diff),- ToolCallContent::ContentBlock(_) => None,- ToolCallContent::Terminal(_) => None,+ ToolCallContent::Diff(diff) | ToolCallContent::LegacyDiff { diff, .. } => {+ Some(diff)+ }+ _ => None,})}@@ -1364,9 +1596,8 @@ impl ToolCall {self.structured_content.iter().filter_map(|content| match content {- ToolCallContent::Terminal(terminal) => Some(terminal),- ToolCallContent::ContentBlock(_) => None,- ToolCallContent::Diff(_) => None,+ ToolCallContent::Terminal { terminal, .. } => Some(terminal),+ _ => None,})}@@ -1377,12 +1608,12 @@ impl ToolCall {pub fn to_markdown(&self, cx: &App) -> String {let label = self.label.read(cx).source();- let label = if self.title.is_none() {+ let label = if self.effective_title().is_none() {MarkdownEscaped(label).to_string()} else {label.to_string()};- let mut markdown = format!("**Tool Call: {}**\nStatus: {}\n\n", label, self.status);+ let mut markdown = format!("**Tool Call: {}**\nStatus: {}\n\n", label, self.status());for content in self.content() {markdown.push_str(content.to_markdown(cx).as_str());markdown.push_str("\n\n");@@ -1528,18 +1759,13 @@ pub enum AuthorizationKind {ActionChoice,}-#[derive(Debug)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum ToolCallStatus {/// The tool call hasn't started running yet, but we start showing it to/// the user.Pending,/// The tool call is waiting for confirmation from the user.- WaitingForConfirmation {- current_status: acp_v1::ToolCallStatus,- options: PermissionOptions,- respond_tx: oneshot::Sender<RequestPermissionOutcome>,- kind: AuthorizationKind,- },+ WaitingForConfirmation,/// The tool call is currently running.InProgress,/// The tool call completed successfully.@@ -1554,25 +1780,31 @@ pub enum ToolCallStatus {impl From<acp_v1::ToolCallStatus> for ToolCallStatus {fn from(status: acp_v1::ToolCallStatus) -> Self {- match status {- acp_v1::ToolCallStatus::Pending => Self::Pending,- acp_v1::ToolCallStatus::InProgress => Self::InProgress,- acp_v1::ToolCallStatus::Completed => Self::Completed,- acp_v1::ToolCallStatus::Failed => Self::Failed,- _ => Self::Pending,- }+ Self::from_reported(tool_status_from_v1(status).as_ref()).unwrap_or(Self::Pending)}}impl ToolCallStatus {+ fn from_reported(status: Option<&acp_v2::ToolCallStatus>) -> Option<Self> {+ match status? {+ acp_v2::ToolCallStatus::Pending => Some(Self::Pending),+ acp_v2::ToolCallStatus::InProgress => Some(Self::InProgress),+ acp_v2::ToolCallStatus::Completed => Some(Self::Completed),+ acp_v2::ToolCallStatus::Failed => Some(Self::Failed),+ acp_v2::ToolCallStatus::Cancelled => Some(Self::Canceled),+ _ => None,+ }+ }+fn as_acp_status(&self) -> Option<acp_v1::ToolCallStatus> {match self {ToolCallStatus::Pending => Some(acp_v1::ToolCallStatus::Pending),- ToolCallStatus::WaitingForConfirmation { current_status, .. } => Some(*current_status),ToolCallStatus::InProgress => Some(acp_v1::ToolCallStatus::InProgress),ToolCallStatus::Completed => Some(acp_v1::ToolCallStatus::Completed),ToolCallStatus::Failed => Some(acp_v1::ToolCallStatus::Failed),- ToolCallStatus::Rejected | ToolCallStatus::Canceled => None,+ ToolCallStatus::WaitingForConfirmation+ | ToolCallStatus::Rejected+ | ToolCallStatus::Canceled => None,}}@@ -1591,7 +1823,7 @@ impl Display for ToolCallStatus {"{}",match self {ToolCallStatus::Pending => "Pending",- ToolCallStatus::WaitingForConfirmation { .. } => "Waiting for confirmation",+ ToolCallStatus::WaitingForConfirmation => "Waiting for confirmation",ToolCallStatus::InProgress => "In Progress",ToolCallStatus::Completed => "Completed",ToolCallStatus::Failed => "Failed",@@ -2062,6 +2294,74 @@ impl ContentBlock {}}+ fn new_tool_content(+ block: acp_v2::ContentBlock,+ language_registry: &Arc<LanguageRegistry>,+ cx: &mut App,+ ) -> Self {+ let render = Self::render_from_source(&block, language_registry, cx);+ Self {+ render,+ source: Some(block),+ }+ }++ fn update_tool_content(+ &mut self,+ block: acp_v2::ContentBlock,+ language_registry: &Arc<LanguageRegistry>,+ cx: &mut App,+ ) {+ let reused = match (self.source.as_ref(), &block) {+ (Some(acp_v2::ContentBlock::Text(old)), acp_v2::ContentBlock::Text(new))+ if matches!(self.render, RenderBlock::Markdown { .. }) =>+ {+ if old.text != new.text {+ self.update_text_in_place(&block, cx);+ }+ true+ }+ (Some(acp_v2::ContentBlock::Image(old)), acp_v2::ContentBlock::Image(new)) => {+ old.data == new.data && old.mime_type == new.mime_type+ }+ (Some(acp_v2::ContentBlock::Resource(old)), acp_v2::ContentBlock::Resource(new)) => {+ match (&old.resource, &new.resource) {+ (+ acp_v2::EmbeddedResourceResource::TextResourceContents(_),+ acp_v2::EmbeddedResourceResource::TextResourceContents(new),+ ) => {+ if let RenderBlock::EmbeddedResource {+ markdown: Some(markdown),+ } = &self.render+ {+ update_markdown_in_place(+ markdown,+ &Self::text_resource_markdown(new),+ cx,+ );+ true+ } else {+ false+ }+ }+ (+ acp_v2::EmbeddedResourceResource::BlobResourceContents(old),+ acp_v2::EmbeddedResourceResource::BlobResourceContents(new),+ ) => old.blob == new.blob && old.mime_type == new.mime_type,+ _ => false,+ }+ }+ (Some(acp_v2::ContentBlock::Audio(_)), acp_v2::ContentBlock::Audio(_))+ | (Some(acp_v2::ContentBlock::Other(_)), acp_v2::ContentBlock::Other(_)) => true,+ (Some(previous), _) => previous == &block,+ _ => false,+ };+ if !reused {+ self.render = Self::render_from_source(&block, language_registry, cx);+ }+ self.source = Some(block);+ }+fn render_from_source(block: &acp_v2::ContentBlock,language_registry: &Arc<LanguageRegistry>,@@ -2507,15 +2807,38 @@ fn text_resource_render_mode(mime_type: Option<&str>) -> TextResourceRenderMode#[derive(Debug)]pub enum ToolCallContent {- ContentBlock(ContentBlock),+ ContentBlock {+ block: ContentBlock,+ meta: Option<acp_v2::Meta>,+ },Diff(Entity<Diff>),- Terminal(Entity<Terminal>),+ LegacyDiff {+ source: acp_v1::Diff,+ diff: Entity<Diff>,+ },+ Terminal {+ terminal: Entity<Terminal>,+ meta: Option<acp_v2::Meta>,+ },+ DiffPatch {+ source: acp_v2::Diff,+ render: DiffPatch,+ },+ Other {+ source: acp_v2::ToolCallContent,+ markdown: Entity<Markdown>,+ },}enum PreparedToolCallContent {- ContentBlock(acp_v2::ContentBlock),- Diff(acp_v1::Diff),- Terminal(Entity<Terminal>),+ ContentBlock(acp_v2::Content),+ LegacyDiff(acp_v1::Diff),+ Terminal {+ terminal: Entity<Terminal>,+ meta: Option<acp_v2::Meta>,+ },+ DiffPatch(acp_v2::Diff),+ Other(acp_v2::ToolCallContent),}impl PreparedToolCallContent {@@ -2526,46 +2849,104 @@ impl PreparedToolCallContent {let mut prepared = Vec::with_capacity(content.len());for content in content {let content = match content {- acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => {- Self::ContentBlock(content::from_v1(content)?)- }- acp_v1::ToolCallContent::Diff(diff) => Self::Diff(diff),- acp_v1::ToolCallContent::Terminal(acp_v1::Terminal { terminal_id, .. }) => {- Self::Terminal(- terminals- .get(&terminal_id)- .cloned()- .ok_or_else(|| anyhow!("Terminal with id `{terminal_id}` not found"))?,- )+ acp_v1::ToolCallContent::Content(acp_v1::Content { content, meta, .. }) => {+ Self::ContentBlock(acp_v2::Content::new(content::from_v1(content)?).meta(meta))}+ acp_v1::ToolCallContent::Diff(diff) => Self::LegacyDiff(diff),+ acp_v1::ToolCallContent::Terminal(acp_v1::Terminal {+ terminal_id, meta, ..+ }) => Self::Terminal {+ terminal: terminals+ .get(&terminal_id)+ .cloned()+ .ok_or_else(|| anyhow!("Terminal with id `{terminal_id}` not found"))?,+ meta,+ },_ => continue,};prepared.push(content);}Ok(prepared)}++ fn prepare_v2(+ content: Vec<acp_v2::ToolCallContent>,+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,+ ) -> Result<Vec<Self>> {+ content+ .into_iter()+ .map(|content| match content {+ acp_v2::ToolCallContent::Content(content) => Ok(Self::ContentBlock(*content)),+ acp_v2::ToolCallContent::Diff(diff) => Ok(Self::DiffPatch(diff)),+ acp_v2::ToolCallContent::Terminal(terminal) => {+ let terminal_id = acp_v1::TerminalId::new(terminal.terminal_id.0);+ Ok(Self::Terminal {+ terminal: terminals+ .get(&terminal_id)+ .cloned()+ .ok_or_else(|| anyhow!("Terminal with id `{terminal_id}` not found"))?,+ meta: terminal.meta,+ })+ }+ other => Ok(Self::Other(other)),+ })+ .collect()+ }}impl ToolCallContent {+ fn patch_preview(diff: &acp_v2::Diff) -> String {+ match diff.patch.as_ref() {+ Some(patch) => MarkdownCodeBlock {+ tag: if patch.format == acp_v2::DiffPatchFormat::GitPatch {+ "diff"+ } else {+ ""+ },+ text: &patch.text,+ }+ .to_string(),+ None => "Diff patch preview unavailable.".to_string(),+ }+ }+fn from_prepared(content: PreparedToolCallContent,language_registry: &Arc<LanguageRegistry>,cx: &mut App,) -> Self {match content {- PreparedToolCallContent::ContentBlock(content) => {- Self::ContentBlock(ContentBlock::new_output(content, language_registry, cx))+ PreparedToolCallContent::ContentBlock(content) => Self::ContentBlock {+ block: ContentBlock::new_tool_content(content.content, language_registry, cx),+ meta: content.meta,+ },+ PreparedToolCallContent::LegacyDiff(source) => {+ let diff = cx.new(|cx| {+ 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 }}- PreparedToolCallContent::Diff(diff) => Self::Diff(cx.new(|cx| {- Diff::finalized(- diff.path.to_string_lossy().into_owned(),- diff.old_text,- diff.new_text,- language_registry.clone(),+ PreparedToolCallContent::Terminal { terminal, meta } => {+ Self::Terminal { terminal, meta }+ }+ PreparedToolCallContent::DiffPatch(source) => Self::DiffPatch {+ render: DiffPatch::new(&source, language_registry, cx),+ source,+ },+ PreparedToolCallContent::Other(source) => Self::Other {+ source,+ markdown: ContentBlock::create_markdown(+ "Unsupported tool call content.".into(),+ language_registry,cx,- )- })),- PreparedToolCallContent::Terminal(terminal) => Self::Terminal(terminal),+ ),+ },}}@@ -2575,38 +2956,79 @@ impl ToolCallContent {language_registry: &Arc<LanguageRegistry>,cx: &mut App,) {- if let (Self::ContentBlock(block), PreparedToolCallContent::ContentBlock(content)) =- (&mut *self, &new)- && block.update_text_in_place(content, cx)- {- return;- }- if let (Self::Diff(old_diff), PreparedToolCallContent::Diff(new_diff)) = (&*self, &new) {- let old_diff = old_diff.read(cx);- if old_diff.file_path(cx).as_deref() == Some(new_diff.path.to_string_lossy().as_ref())- && !old_diff.needs_update(- new_diff.old_text.as_deref().unwrap_or(""),- &new_diff.new_text,- cx,- )+ match (&mut *self, new) {+ (+ Self::ContentBlock { block, meta },+ PreparedToolCallContent::ContentBlock(content),+ ) => {+ block.update_tool_content(content.content, language_registry, cx);+ *meta = content.meta;+ }+ (Self::LegacyDiff { source, .. }, PreparedToolCallContent::LegacyDiff(new_source))+ if source.path == new_source.path+ && source.old_text == new_source.old_text+ && source.new_text == new_source.new_text =>{- return;+ *source = new_source;+ }+ (+ Self::Terminal { terminal, meta },+ PreparedToolCallContent::Terminal {+ terminal: new_terminal,+ meta: new_meta,+ },+ ) if *terminal == new_terminal => *meta = new_meta,+ (+ Self::DiffPatch { source, render },+ PreparedToolCallContent::DiffPatch(new_source),+ ) => {+ if source.patch != new_source.patch+ || source.changes.len() != new_source.changes.len()+ || source+ .changes+ .iter()+ .zip(&new_source.changes)+ .any(|(old, new)| {+ old.operation != new.operation || old.file_type != new.file_type+ })+ {+ *render = DiffPatch::new(&new_source, language_registry, cx);+ }+ *source = new_source;+ }+ (Self::Other { source, .. }, PreparedToolCallContent::Other(new_source)) => {+ *source = new_source;}+ (_, new) => *self = Self::from_prepared(new, language_registry, cx),}- *self = Self::from_prepared(new, language_registry, cx);}pub fn to_markdown(&self, cx: &App) -> String {match self {- Self::ContentBlock(content) => content.to_markdown(cx).to_string(),- Self::Diff(diff) => diff.read(cx).to_markdown(cx),- Self::Terminal(terminal) => terminal.read(cx).to_markdown(cx),+ Self::ContentBlock { block, .. } => block.to_markdown(cx).to_string(),+ 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!(+ "{}\n\n{}",+ source.changes.iter().map(diff_change_label).join("\n"),+ Self::patch_preview(source)+ ),+ Self::Other { markdown, .. } => markdown.read(cx).source().to_string(),+ }+ }++ pub fn markdown(&self) -> Option<&Entity<Markdown>> {+ match self {+ Self::ContentBlock { block, .. } => block.markdown(),+ Self::DiffPatch { render, .. } => render.fallback.as_ref(),+ Self::Other { markdown, .. } => Some(markdown),+ Self::Diff(_) | Self::LegacyDiff { .. } | Self::Terminal { .. } => None,}}pub fn image(&self) -> Option<(&Arc<gpui::Image>, Option<gpui::Size<u32>>)> {match self {- Self::ContentBlock(content) => content.image(),+ Self::ContentBlock { block, .. } => block.image(),_ => None,}}@@ -3289,10 +3711,7 @@ impl AcpThread {for entry in self.entries.iter().rev() {match entry {AgentThreadEntry::UserMessage(_) => return false,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::WaitingForConfirmation { .. },- ..- }) => return true,+ AgentThreadEntry::ToolCall(call) if call.authorization().is_some() => return true,AgentThreadEntry::Elicitation(elicitation_id)if self.elicitations.elicitation(elicitation_id).is_some_and(|(_, elicitation)| {@@ -3323,12 +3742,12 @@ impl AcpThread {for entry in self.entries.iter().rev() {match entry {AgentThreadEntry::UserMessage(_) => return false,- AgentThreadEntry::ToolCall(- call @ ToolCall {- status: ToolCallStatus::InProgress | ToolCallStatus::Pending,- ..- },- ) if call.diffs().next().is_some() => {+ AgentThreadEntry::ToolCall(call)+ if matches!(+ call.status(),+ ToolCallStatus::InProgress | ToolCallStatus::Pending+ ) && call.diffs().next().is_some() =>+ {return true;}AgentThreadEntry::ToolCall(_)@@ -3345,12 +3764,14 @@ impl AcpThread {for entry in self.entries.iter().rev() {match entry {AgentThreadEntry::UserMessage(_) => return false,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::InProgress | ToolCallStatus::Pending,- ..- }) => {- return true;- }+ AgentThreadEntry::ToolCall(call)+ if matches!(+ call.status(),+ ToolCallStatus::InProgress | ToolCallStatus::Pending+ ) =>+ {+ return true;+ }AgentThreadEntry::ToolCall(_)| AgentThreadEntry::Elicitation(_)| AgentThreadEntry::AssistantMessage(_)@@ -4313,27 +4734,16 @@ impl AcpThread {Some(ix) => ix,None => {// Tool call not found - create a failed tool call entry- let failed_tool_call = ToolCall {- id: update.id().clone(),- label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)),- title: Some("Tool call not found".into()),- kind: acp_v1::ToolKind::Fetch,- structured_content: vec![ToolCallContent::ContentBlock(- ContentBlock::new_output("Tool call not found".into(), &languages, cx),- )],- status: ToolCallStatus::Failed,- locations: Vec::new(),- resolved_locations: Vec::new(),- raw_input: None,- raw_input_markdown: None,- raw_output: None,- raw_output_content: None,- tool_name: None,- subagent_session_info: None,- sandbox_authorization_details: None,- sandbox_fallback_authorization_details: None,- sandbox_not_applied: None,- };+ let failed_tool_call = ToolCall::from_acp(+ acp_v1::ToolCall::new(update.id().clone(), "Tool call not found")+ .kind(acp_v1::ToolKind::Fetch)+ .status(acp_v1::ToolCallStatus::Failed)+ .content(vec!["Tool call not found".into()]),+ Some(ToolCallStatus::Failed),+ languages,+ &self.terminals,+ cx,+ )?;self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx);return Ok(());}@@ -4363,8 +4773,10 @@ impl AcpThread {}ToolCallUpdate::UpdateTerminal(update) => {call.structured_content.clear();- call.structured_content- .push(ToolCallContent::Terminal(update.terminal));+ call.structured_content.push(ToolCallContent::Terminal {+ terminal: update.terminal,+ meta: None,+ });call.update_raw_output_content(&languages, cx);}}@@ -4380,20 +4792,14 @@ impl AcpThread {tool_call: acp_v1::ToolCall,cx: &mut Context<Self>,) -> Result<(), acp_v1::Error> {- let status = tool_call.status.into();+ let status = ToolCallStatus::from_reported(tool_status_from_v1(tool_call.status).as_ref());+ if let Some(status) = status {+ self.report_tool_call_completed(status);+ }self.upsert_tool_call_inner(tool_call.into(), status, cx)}- /// Fails if id does not match an existing entry.- pub fn upsert_tool_call_inner(- &mut self,- update: acp_v1::ToolCallUpdate,- status: ToolCallStatus,- cx: &mut Context<Self>,- ) -> Result<(), acp_v1::Error> {- let language_registry = self.project.read(cx).languages().clone();- let id = update.tool_call_id.clone();-+ fn report_tool_call_completed(&self, status: ToolCallStatus) {let agent_telemetry_id = self.connection().telemetry_id();let session = self.session_id();let parent_session_id = self.parent_session_id();@@ -4411,7 +4817,16 @@ impl AcpThread {status);}+ }+ fn upsert_tool_call_inner(+ &mut self,+ update: acp_v1::ToolCallUpdate,+ status: Option<ToolCallStatus>,+ cx: &mut Context<Self>,+ ) -> Result<(), acp_v1::Error> {+ let language_registry = self.project.read(cx).languages().clone();+ let id = update.tool_call_id.clone();if let Some(ix) = self.index_for_tool_call(&id) {let AgentThreadEntry::ToolCall(call) = &mut self.entries[ix] else {unreachable!()@@ -4427,7 +4842,9 @@ impl AcpThread {cx.emit(AcpThreadEvent::EntryUpdated(ix));return Err(acp_v1::Error::from(error));}- call.update_status(status);+ if let Some(status) = status {+ call.set_legacy_status(status);+ }cx.emit(AcpThreadEvent::EntryUpdated(ix));} else {@@ -4445,6 +4862,35 @@ impl AcpThread {Ok(())}+ pub fn upsert_tool_call_patch(+ &mut self,+ update: acp_v2::ToolCallUpdate,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let id = acp_v1::ToolCallId::new(update.tool_call_id.0.clone());+ let patch = ToolCallPatch::protocol(update);+ let locations_changed = !patch.locations.is_undefined();+ if let Some(status) = ToolCallStatus::from_reported(patch.status.value()) {+ self.report_tool_call_completed(status);+ }+ let languages = self.project.read(cx).languages().clone();+ if let Some(index) = self.index_for_tool_call(&id) {+ let AgentThreadEntry::ToolCall(call) = &mut self.entries[index] else {+ unreachable!()+ };+ let result = call.apply_patch(patch, languages, &self.terminals, cx);+ cx.emit(AcpThreadEvent::EntryUpdated(index));+ result?;+ } else {+ let call = ToolCall::from_patch(id.clone(), patch, languages, &self.terminals, cx)?;+ self.push_entry(AgentThreadEntry::ToolCall(call), cx);+ }+ if locations_changed {+ self.resolve_locations(id, cx);+ }+ Ok(())+ }+fn index_for_tool_call(&self, id: &acp_v1::ToolCallId) -> Option<usize> {self.entries.iter()@@ -4516,11 +4962,18 @@ impl AcpThread {let Some((_, tool_call)) = self.tool_call_mut(&id) else {return;};+ let expected_locations = tool_call.locations.clone();let task = tool_call.resolve_locations(project, cx);cx.spawn(async move |this, cx| {let resolved_locations = task.await;this.update(cx, |this, cx| {+ if this+ .tool_call(&id)+ .is_none_or(|(_, call)| call.locations != expected_locations)+ {+ return;+ }let project = this.project.clone();for location in resolved_locations.iter().flatten() {@@ -4579,18 +5032,24 @@ impl AcpThread {let current_status = self.tool_call(&tool_call.tool_call_id)- .and_then(|(_, tool_call)| tool_call.status.as_acp_status())+ .and_then(|(_, tool_call)| tool_call.permission_status()).or(tool_call.fields.status)- .unwrap_or(acp_v1::ToolCallStatus::Pending);- let status = ToolCallStatus::WaitingForConfirmation {- current_status,+ .and_then(tool_status_from_v1);+ let current_status = ToolCallStatus::from_reported(current_status.as_ref())+ .unwrap_or(ToolCallStatus::Pending);++ let tool_call_id = tool_call.tool_call_id.clone();+ self.upsert_tool_call_inner(tool_call, Some(current_status), cx)?;+ let (_, call) = self+ .tool_call_mut(&tool_call_id)+ .context("tool call disappeared while requesting authorization")?;+ // A new explicit request is installed after applying its descriptive+ // fields, preserving the legacy request's captured continuation status.+ call.authorization = Some(ToolCallAuthorization {options,respond_tx: tx,kind,- };-- let tool_call_id = tool_call.tool_call_id.clone();- self.upsert_tool_call_inner(tool_call, status, cx)?;+ });cx.emit(AcpThreadEvent::ToolAuthorizationRequested(tool_call_id.clone(),));@@ -4613,11 +5072,12 @@ impl AcpThread {let Some((ix, call)) = self.tool_call_mut(id) else {return;};- if !matches!(call.status, ToolCallStatus::WaitingForConfirmation { .. }) {+ if call.authorization.is_none() {return;}- call.status = ToolCallStatus::Canceled;+ call.authorization = None;+ call.set_local_status(ToolCallStatus::Canceled);cx.emit(AcpThreadEvent::EntryUpdated(ix));cx.emit(AcpThreadEvent::ToolAuthorizationReceived(id.clone()));}@@ -4632,20 +5092,21 @@ impl AcpThread {return;};- let new_status = match &call.status {- ToolCallStatus::WaitingForConfirmation {+ let new_status = match call.authorization() {+ Some(ToolCallAuthorization {kind: AuthorizationKind::ActionChoice,..- } => ToolCallStatus::InProgress,- ToolCallStatus::WaitingForConfirmation { current_status, .. } => {+ }) => ToolCallStatus::InProgress,+ Some(_) => {+ let current_status = call.permission_status().unwrap_or_default();match outcome.option_kind {acp_v1::PermissionOptionKind::RejectOnce| acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,acp_v1::PermissionOptionKind::AllowOnce| acp_v1::PermissionOptionKind::AllowAlways => {- ToolCallStatus::status_after_permission_grant(*current_status)+ ToolCallStatus::status_after_permission_grant(current_status)}- _ => ToolCallStatus::status_after_permission_grant(*current_status),+ _ => ToolCallStatus::status_after_permission_grant(current_status),}}_ => match outcome.option_kind {@@ -4657,10 +5118,10 @@ impl AcpThread {},};- let curr_status = mem::replace(&mut call.status, new_status);-- if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } = curr_status {- respond_tx+ call.set_local_status(new_status);+ if let Some(authorization) = call.authorization.take() {+ authorization+ .respond_tx.send(RequestPermissionOutcome::Selected(outcome)).ok();}@@ -5048,7 +5509,7 @@ impl AcpThread {this.entries.iter().skip(user_msg_ix + 1).any(|entry| {if let AgentThreadEntry::ToolCall(tool_call) = entry {// Check if the tool call has completed and has output- matches!(tool_call.status, ToolCallStatus::Completed)+ matches!(tool_call.status(), ToolCallStatus::Completed)&& tool_call.raw_output.is_some()} else {false@@ -5183,17 +5644,18 @@ impl AcpThread {match entry {AgentThreadEntry::ToolCall(call) => {let cancel = matches!(- call.status,+ call.status(),ToolCallStatus::Pending- | ToolCallStatus::WaitingForConfirmation { .. }+ | ToolCallStatus::WaitingForConfirmation| ToolCallStatus::InProgress);if cancel {- let previous_status =- mem::replace(&mut call.status, ToolCallStatus::Canceled);- if let ToolCallStatus::WaitingForConfirmation { respond_tx, .. } =- previous_status- && respond_tx.send(permission_outcome.clone()).is_err()+ call.set_local_status(ToolCallStatus::Canceled);+ if let Some(authorization) = call.authorization.take()+ && authorization+ .respond_tx+ .send(permission_outcome.clone())+ .is_err(){log::debug!("Permission request closed before cancellation was delivered"@@ -7041,6 +7503,381 @@ mod tests {);}+ #[gpui::test]+ fn test_tool_content_retains_and_refreshes_inner_and_envelope_meta(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let make_content = |inner: &str, outer: &str| {+ acp_v2::ToolCallContent::Content(Box::new(+ acp_v2::Content::new(acp_v2::ContentBlock::Text(+ acp_v2::TextContent::new("same")+ .meta(acp_v2::Meta::from_iter([("inner".into(), inner.into())])),+ ))+ .meta(acp_v2::Meta::from_iter([("outer".into(), outer.into())])),+ ))+ };+ let prepared = PreparedToolCallContent::prepare_v2(+ vec![make_content("first", "first")],+ &HashMap::default(),+ )+ .expect("prepare content");+ let mut content = ToolCallContent::from_prepared(+ prepared.into_iter().next().expect("content"),+ &languages,+ cx,+ );+ let original = content.markdown().expect("markdown").clone();+ let prepared = PreparedToolCallContent::prepare_v2(+ vec![make_content("second", "second")],+ &HashMap::default(),+ )+ .expect("prepare update");+ content.update_from_prepared(+ prepared.into_iter().next().expect("update"),+ &languages,+ cx,+ );+ let ToolCallContent::ContentBlock { block, meta } = &content else {+ panic!("content block");+ };+ assert_eq!(block.markdown(), Some(&original));+ assert_eq!(+ meta.as_ref().and_then(|meta| meta.get("outer")),+ Some(&serde_json::json!("second"))+ );+ let Some(acp_v2::ContentBlock::Text(source)) = block.source.as_ref() else {+ panic!("retained text");+ };+ assert_eq!(+ source.meta.as_ref().and_then(|meta| meta.get("inner")),+ Some(&serde_json::json!("second"))+ );+ });+ }++ #[gpui::test]+ fn test_tool_content_resource_updates_refresh_source_and_reuse_rendering(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let resource = |uri: &str, mime: &str| {+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(+ acp_v2::EmbeddedResourceResource::TextResourceContents(+ acp_v2::TextResourceContents::new("**text**", uri)+ .mime_type(mime)+ .meta(acp_v2::Meta::from_iter([("uri".into(), json!(uri))])),+ ),+ ))+ };+ let mut content = ToolCallContent::from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(resource(+ "tool://old",+ "text/markdown",+ ))),+ &languages,+ cx,+ );+ let markdown = content.markdown().expect("preview").clone();+ for mime in ["text/markdown", "text/plain"] {+ let source = resource("tool://new", mime);+ content.update_from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(source.clone())),+ &languages,+ cx,+ );+ assert_eq!(content.markdown(), Some(&markdown));+ let ToolCallContent::ContentBlock { block, .. } = &content else {+ panic!("resource");+ };+ assert_eq!(block.source.as_ref(), Some(&source));+ assert_eq!(+ markdown.read(cx).source().as_ref(),+ if mime == "text/markdown" {+ "**text**"+ } else {+ "```\n**text**\n```"+ },+ );+ }++ let acp_v2::ContentBlock::Image(image) = message_test_image() else {+ panic!("image fixture");+ };+ let blob = |uri: &str| {+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(+ acp_v2::EmbeddedResourceResource::BlobResourceContents(+ acp_v2::BlobResourceContents::new(image.data.clone(), uri)+ .mime_type(image.mime_type.clone()),+ ),+ ))+ };+ content.update_from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(blob("tool://old.png"))),+ &languages,+ cx,+ );+ assert!(content.markdown().is_none());+ let decoded = content.image().expect("embedded image").0.clone();+ let source = blob("tool://renamed.png");+ content.update_from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(source.clone())),+ &languages,+ cx,+ );+ assert!(Arc::ptr_eq(content.image().expect("image").0, &decoded));+ let ToolCallContent::ContentBlock { block, .. } = &content else {+ panic!("resource image");+ };+ assert_eq!(block.source.as_ref(), Some(&source));+ });+ }++ #[gpui::test]+ fn test_tool_content_image_metadata_update_reuses_decoded_image(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let acp_v2::ContentBlock::Image(image) = message_test_image() else {+ panic!("image");+ };+ let mut content = ToolCallContent::from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(+ acp_v2::ContentBlock::Image(image.clone()),+ )),+ &languages,+ cx,+ );+ let original = content.image().expect("image").0.clone();+ content.update_from_prepared(+ PreparedToolCallContent::ContentBlock(acp_v2::Content::new(+ acp_v2::ContentBlock::Image(+ image.meta(acp_v2::Meta::from_iter([("revision".into(), 2.into())])),+ ),+ )),+ &languages,+ cx,+ );+ assert!(Arc::ptr_eq(&original, content.image().expect("image").0));+ let ToolCallContent::ContentBlock { block, .. } = &content else {+ panic!("image block");+ };+ let Some(acp_v2::ContentBlock::Image(source)) = block.source.as_ref() else {+ panic!("retained image");+ };+ assert_eq!(+ source.meta.as_ref().and_then(|meta| meta.get("revision")),+ Some(&serde_json::json!(2))+ );+ });+ }++ #[gpui::test]+ fn test_tool_content_legacy_diff_preserves_raw_source_and_native_authority(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let mut content = ToolCallContent::from_prepared(+ PreparedToolCallContent::LegacyDiff(acp_v1::Diff::new("first.rs", "new")),+ &languages,+ cx,+ );+ let ToolCallContent::LegacyDiff { diff, .. } = &content else {+ panic!("legacy diff")+ };+ let original = diff.clone();+ content.update_from_prepared(+ PreparedToolCallContent::LegacyDiff(+ acp_v1::Diff::new("first.rs", "new")+ .meta(acp_v1::Meta::from_iter([("revision".into(), 1.into())])),+ ),+ &languages,+ cx,+ );+ let ToolCallContent::LegacyDiff { source, diff } = &content else {+ panic!("legacy diff")+ };+ assert_eq!(diff, &original);+ assert_eq!(+ source.meta.as_ref().and_then(|meta| meta.get("revision")),+ Some(&serde_json::json!(1))+ );+ content.update_from_prepared(+ PreparedToolCallContent::LegacyDiff(+ acp_v1::Diff::new("first.rs", "new").old_text(""),+ ),+ &languages,+ cx,+ );+ let ToolCallContent::LegacyDiff { source, diff } = &content else {+ panic!("legacy diff")+ };+ assert_eq!(source.old_text.as_deref(), Some(""));+ assert_ne!(diff, &original);+ let previous = diff.clone();+ content.update_from_prepared(+ PreparedToolCallContent::LegacyDiff(+ acp_v1::Diff::new("second.rs", "new").old_text(""),+ ),+ &languages,+ cx,+ );+ let ToolCallContent::LegacyDiff { source, diff } = &content else {+ panic!("legacy diff")+ };+ assert_eq!(source.path, PathBuf::from("second.rs"));+ assert_ne!(diff, &previous);+ let native_diff = cx.new(|cx| {+ Diff::finalized(+ "native.rs".into(),+ Some("before".into()),+ "after".into(),+ languages.clone(),+ cx,+ )+ });+ let mut native = ToolCallContent::Diff(native_diff.clone());+ native.update_from_prepared(+ PreparedToolCallContent::LegacyDiff(acp_v1::Diff::new("native.rs", "replacement")),+ &languages,+ cx,+ );+ assert!(matches!(native, ToolCallContent::LegacyDiff { .. }));+ assert_eq!(+ native_diff.read(cx).file_path(cx).as_deref(),+ Some("native.rs")+ );+ assert_ne!(+ native_diff,+ match &native {+ ToolCallContent::LegacyDiff { diff, .. } => diff.clone(),+ _ => panic!("legacy diff"),+ }+ );+ });+ }++ #[gpui::test]+ fn test_tool_diff_patch_reuses_hunks_for_metadata_changes(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let mut source: acp_v2::Diff = serde_json::from_value(serde_json::json!({+ "changes": [{"operation": "modify", "path": "/test.rs"}],+ "patch": {+ "format": "git_patch",+ "text": "--- /test.rs\n+++ /test.rs\n@@ -5 +5 @@\n-before\n+after\n"+ }+ }))+ .expect("diff");+ let mut content = ToolCallContent::from_prepared(+ PreparedToolCallContent::DiffPatch(source.clone()),+ &languages,+ cx,+ );+ let ToolCallContent::DiffPatch { render, .. } = &content else {+ panic!("patch");+ };+ assert!(render.fallback.is_none());+ let buffer = render.files[0].hunks[0].buffer.clone();+ source.meta = Some(acp_v2::Meta::from_iter([("revision".into(), 2.into())]));+ source.changes[0].meta = source.meta.clone();+ source.changes[0].mime_type = Some(acp_v2::MediaType::new("text/x-rust"));+ content.update_from_prepared(+ PreparedToolCallContent::DiffPatch(source.clone()),+ &languages,+ cx,+ );+ let ToolCallContent::DiffPatch {+ source: retained,+ render,+ } = &content+ else {+ panic!("patch");+ };+ assert_eq!(retained, &source);+ assert_eq!(render.files[0].hunks[0].buffer, buffer);+ assert!(+ content.markdown().is_none(),+ "no hidden Markdown copy of a rendered patch"+ );+ assert!(content.to_markdown(cx).contains("-before\n+after"));+ source.patch.as_mut().expect("patch").text = "@@ -5 +5 @@\n-before\n+updated\n".into();+ content.update_from_prepared(+ PreparedToolCallContent::DiffPatch(source.clone()),+ &languages,+ cx,+ );+ let ToolCallContent::DiffPatch {+ source: retained,+ render,+ } = &content+ else {+ panic!("patch");+ };+ assert_eq!(retained, &source);+ assert_ne!(render.files[0].hunks[0].buffer, buffer);+ });+ }++ #[gpui::test]+ fn test_tool_content_v2_diff_patch_and_unknown_retain_source(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let patch = "diff --git a/one b/one\n+``` nested";+ let diff = acp_v2::Diff::patch(patch, vec![])+ .meta(acp_v2::Meta::from_iter([("revision".into(), 1.into())]));+ let unknown: acp_v2::ToolCallContent =+ serde_json::from_value(serde_json::json!({"type":"future","payload":{"value":1}}))+ .expect("unknown content");+ let prepared = PreparedToolCallContent::prepare_v2(+ vec![acp_v2::ToolCallContent::Diff(diff.clone()), unknown.clone()],+ &HashMap::default(),+ )+ .expect("prepare v2 content");+ let mut content: Vec<_> = prepared+ .into_iter()+ .map(|content| ToolCallContent::from_prepared(content, &languages, cx))+ .collect();+ let ToolCallContent::DiffPatch { source, render } = &content[0] else {+ panic!("patch")+ };+ assert_eq!(source, &diff);+ let markdown = render+ .fallback+ .as_ref()+ .expect("unsupported patch fallback");+ assert!(markdown.read(cx).source().contains("````diff\n"));+ let original = markdown.clone();+ content[0].update_from_prepared(+ PreparedToolCallContent::DiffPatch(+ acp_v2::Diff::patch(patch, vec![])+ .meta(acp_v2::Meta::from_iter([("revision".into(), 2.into())])),+ ),+ &languages,+ cx,+ );+ let ToolCallContent::DiffPatch { source, render } = &content[0] else {+ panic!("patch")+ };+ assert_eq!(render.fallback.as_ref(), Some(&original));+ assert_eq!(+ source.meta.as_ref().and_then(|meta| meta.get("revision")),+ Some(&serde_json::json!(2))+ );+ let ToolCallContent::Other { source, markdown } = &content[1] else {+ panic!("unknown")+ };+ assert_eq!(source, &unknown);+ assert!(!markdown.read(cx).source().is_empty());+ });+ }+#[gpui::test]async fn test_tool_call_content_preserves_embedded_text_resource(cx: &mut gpui::TestAppContext,@@ -9316,11 +10153,8 @@ mod tests {thread.read_with(cx, |thread, _| {assert!(matches!(- thread.entries[1],- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::InProgress,- ..- })+ &thread.entries[1],+ AgentThreadEntry::ToolCall(call) if call.status() == ToolCallStatus::InProgress));});@@ -9329,10 +10163,7 @@ mod tests {thread.read_with(cx, |thread, _| {assert!(matches!(&thread.entries[1],- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::Canceled,- ..- })+ AgentThreadEntry::ToolCall(call) if call.status() == ToolCallStatus::Canceled));});@@ -9353,11 +10184,8 @@ mod tests {thread.read_with(cx, |thread, _| {assert!(matches!(- thread.entries[1],- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::Completed,- ..- })+ &thread.entries[1],+ AgentThreadEntry::ToolCall(call) if call.status() == ToolCallStatus::Completed));});}@@ -9582,196 +10410,786 @@ mod tests {),cx,)- .expect("failed to append summary block");- }- });-- for replace_summary in [false, true] {+ .expect("failed to append summary block");+ }+ });++ for replace_summary in [false, true] {+ thread.update(cx, |thread, cx| {+ let mut update = acp_v1::CompactionUpdate::new(+ "compaction",+ acp_v1::CompactionStatus::Completed,+ );+ if replace_summary {+ update = update.summary(blocks.clone());+ }+ thread+ .handle_session_update(acp_v1::SessionUpdate::CompactionUpdate(update), cx)+ .expect("failed to complete compaction");+ });+ thread.read_with(cx, |thread, cx| {+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.first()+ else {+ panic!("expected compaction entry");+ };+ let [text, resource, image, link, unsupported, blob] =+ compaction.summary.as_slice()+ else {+ panic!("expected six retained content blocks");+ };+ assert_eq!(text.to_markdown(cx), "retained context");+ assert_eq!(+ resource+ .as_view()+ .embedded_resource()+ .map(|(resource, _)| resource),+ Some(text_resource)+ );+ assert_eq!(resource.to_markdown(cx), "Retained resource text");+ assert_eq!(+ image+ .image()+ .and_then(|(_, dimensions)| dimensions)+ .map(|size| (size.width, size.height)),+ Some((1, 1))+ );+ assert_eq!(+ link.as_view().resource_link().map(|link| link.uri.as_str()),+ Some("https://example.com/context")+ );+ let Some(content) = unsupported.unsupported_content() else {+ panic!("expected preserved audio with a visible fallback");+ };+ assert_eq!(content, stored_audio);+ assert!(unsupported.visible_content(cx));+ assert_eq!(+ blob.as_view()+ .embedded_resource()+ .map(|(resource, _)| resource),+ Some(blob_resource)+ );+ assert!(blob.visible_content(cx));+ assert_eq!(+ thread.to_markdown(cx),+ concat!(+ "## Context Compaction (Completed)\n\n",+ "retained context\n\n",+ "Retained resource text\n\n",+ "`Image`\n\n",+ "https://example.com/context\n\n",+ "Audio content is not supported.\n\n",+ "summary://attachment\n\n",+ )+ );+ });+ }++ thread.update(cx, |thread, cx| {+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::CompactionUpdate(+ acp_v1::CompactionUpdate::new(+ "compaction",+ acp_v1::CompactionStatus::Completed,+ )+ .summary(vec![audio.clone()]),+ ),+ cx,+ )+ .expect("failed to replace summary with audio");+ });+ thread.read_with(cx, |thread, cx| {+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.first()+ else {+ panic!("expected compaction entry");+ };+ assert!(matches!(+ compaction.summary.as_slice(),+ [block] if block.unsupported_content() == Some(stored_audio)+ ));+ assert!(+ thread+ .to_markdown(cx)+ .contains("Audio content is not supported.")+ );+ });+ }++ #[gpui::test]+ async fn test_context_compaction_updates_preserve_timeline_and_emit_events(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let connection = Rc::new(FakeAgentConnection::new());+ let thread = cx+ .update(|cx| {+ connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)+ })+ .await+ .expect("failed to create ACP thread");+ let events = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ let events = events.clone();+ cx.subscribe(&thread, move |_, event, _| match event {+ AcpThreadEvent::NewEntry => events.borrow_mut().push(None),+ AcpThreadEvent::EntryUpdated(index) => events.borrow_mut().push(Some(*index)),+ _ => {}+ })+ });++ thread.update(cx, |thread, cx| {+ for update in [+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(+ "first",+ acp_v1::CompactionStatus::InProgress,+ )),+ acp_v1::SessionUpdate::ToolCall(acp_v1::ToolCall::new("tool", "Unrelated tool")),+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(+ "second",+ acp_v1::CompactionStatus::InProgress,+ )),+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(+ "second",+ acp_v1::CompactionStatus::Completed,+ )),+ acp_v1::SessionUpdate::CompactionSummaryChunk(acp_v1::CompactionSummaryChunk::new(+ "first",+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("partial summary")),+ )),+ ] {+ thread+ .handle_session_update(update, cx)+ .expect("failed to apply interleaved session update");+ }+ assert!(thread.is_compacting());+ });+ assert_eq!(*events.borrow(), [None, None, None, Some(2), Some(0)]);++ thread.update(cx, |thread, cx| {+ thread+ .handle_session_update(+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(+ "first",+ acp_v1::CompactionStatus::Cancelled,+ )),+ cx,+ )+ .expect("failed to cancel compaction");+ assert!(!thread.is_compacting());+ });+ assert_eq!(+ *events.borrow(),+ [None, None, None, Some(2), Some(0), Some(0)]+ );+ thread.read_with(cx, |thread, cx| {+ let [+ AgentThreadEntry::ContextCompaction(first),+ AgentThreadEntry::ToolCall(_),+ AgentThreadEntry::ContextCompaction(second),+ ] = thread.entries.as_slice()+ else {+ panic!("updates must preserve the original timeline positions");+ };+ assert_eq!(first.id.0.as_ref(), "first");+ assert_eq!(first.status, ContextCompactionStatus::Canceled);+ assert_eq!(second.id.0.as_ref(), "second");+ assert_eq!(second.status, ContextCompactionStatus::Completed);+ assert!(+ thread+ .to_markdown(cx)+ .starts_with("## Context Compaction (Canceled)\n\npartial summary\n\n")+ );+ });+ }++ #[test]+ fn test_legacy_tool_enum_translations_preserve_known_values() {+ for kind in [+ acp_v1::ToolKind::Read,+ acp_v1::ToolKind::Edit,+ acp_v1::ToolKind::Delete,+ acp_v1::ToolKind::Move,+ acp_v1::ToolKind::Search,+ acp_v1::ToolKind::Execute,+ acp_v1::ToolKind::Think,+ acp_v1::ToolKind::Fetch,+ acp_v1::ToolKind::SwitchMode,+ acp_v1::ToolKind::Other,+ ] {+ assert_eq!(+ serde_json::to_value(tool_kind_from_v1(kind).expect("known kind"))+ .expect("v2 kind"),+ serde_json::to_value(kind).expect("v1 kind"),+ );+ }+ for status in [+ acp_v1::ToolCallStatus::Pending,+ acp_v1::ToolCallStatus::InProgress,+ acp_v1::ToolCallStatus::Completed,+ acp_v1::ToolCallStatus::Failed,+ ] {+ assert_eq!(+ serde_json::to_value(tool_status_from_v1(status).expect("known status"))+ .expect("v2 status"),+ serde_json::to_value(status).expect("v1 status"),+ );+ }+ }++ #[gpui::test]+ async fn test_skipped_legacy_tool_enums_preserve_current_state(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ let id = acp_v1::ToolCallId::new("kept");+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("kept")+ .kind(acp_v2::ToolKind::Execute)+ .status(acp_v2::ToolCallStatus::Completed),+ cx,+ )+ .expect("known state");+ assert!(legacy_tool_field::<acp_v2::ToolKind>(None).is_undefined());+ assert!(legacy_tool_field::<acp_v2::ToolCallStatus>(None).is_undefined());+ thread+ .upsert_tool_call_inner(+ acp_v1::ToolCallUpdate::new(+ id.clone(),+ acp_v1::ToolCallUpdateFields::new().title("updated title"),+ ),+ None,+ cx,+ )+ .expect("no translated kind or status");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.reported_kind, Some(acp_v2::ToolKind::Execute));+ assert_eq!(+ call.reported_status,+ Some(acp_v2::ToolCallStatus::Completed)+ );+ assert_eq!(call.status(), ToolCallStatus::Completed);+ assert_eq!(call.local_status, None);+ assert_eq!(call.label.read(cx).source(), "updated title");+ thread+ .update_tool_call(+ acp_v1::ToolCallUpdate::new(+ id,+ acp_v1::ToolCallUpdateFields::new().kind(acp_v1::ToolKind::Other),+ ),+ cx,+ )+ .expect("Other is a supported explicit value");+ assert_eq!(thread.entries().len(), 1);+ let languages = thread.project.read(cx).languages().clone();+ let empty = ToolCall::from_patch(+ "fallback".into(),+ ToolCallPatch::legacy(acp_v1::ToolCallUpdateFields::new(), None),+ languages,+ &thread.terminals,+ cx,+ )+ .expect("missing enums use display fallbacks");+ assert_eq!(empty.reported_kind, None);+ assert_eq!(empty.reported_status, None);+ assert_eq!(empty.kind(), &acp_v2::ToolKind::Other);+ assert_eq!(empty.status(), ToolCallStatus::Pending);+ let (_, call) = thread+ .tool_call(&acp_v1::ToolCallId::new("kept"))+ .expect("tool");+ assert_eq!(call.reported_kind, Some(acp_v2::ToolKind::Other));+ assert_eq!(call.status(), ToolCallStatus::Completed);+ });+ }++ #[gpui::test]+ async fn test_tool_patch_preserves_unknown_values_and_applies_field_clears(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ let id = acp_v1::ToolCallId::new("patch");+ thread+ .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("patch"), cx)+ .expect("ID-only upsert");+ let (_, call) = thread.tool_call(&id).expect("new tool");+ assert_eq!(call.reported_kind, None);+ assert_eq!(call.reported_status, None);+ assert_eq!(call.status(), ToolCallStatus::Pending);+ assert_eq!(call.label.read(cx).source(), "Tool call");+ assert!(call.content().is_empty());++ thread+ .upsert_tool_call_patch(+ serde_json::from_value(json!({+ "toolCallId": "patch",+ "title": "**Title**",+ "name": "named",+ "kind": "_future_kind",+ "status": "_future_status",+ "content": [{+ "type": "content",+ "content": {"type": "text", "text": "body", "_meta": {"block": true}},+ "_meta": {"envelope": true}+ }],+ "rawInput": {"nested": [1, {"value": "input"}]},+ "rawOutput": "fallback",+ "_meta": {"opaque": {"nested": [1, 2]}}+ }))+ .expect("SDK patch"),+ cx,+ )+ .expect("populated upsert");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(+ call.reported_kind,+ Some(acp_v2::ToolKind::Unknown("_future_kind".into()))+ );+ assert_eq!(+ call.reported_status,+ Some(acp_v2::ToolCallStatus::Other("_future_status".into()))+ );+ assert_eq!(call.status(), ToolCallStatus::Pending);+ assert_eq!(call.name.as_deref(), Some("named"));+ assert_eq!(+ serde_json::to_value(&call.meta).expect("metadata"),+ json!({"opaque": {"nested": [1, 2]}})+ );+ let [ToolCallContent::ContentBlock { block, meta }] = call.content() else {+ panic!("one protocol content block");+ };+ assert_eq!(+ serde_json::to_value(&block.source).expect("source"),+ json!({"type": "text", "text": "body", "_meta": {"block": true}})+ );+ assert_eq!(+ serde_json::to_value(meta).expect("envelope"),+ json!({"envelope": true})+ );+ let label = call.label.clone();+ let output = block.markdown().expect("body").clone();+ let input = call.raw_input_markdown.clone().expect("input");++ for patch in [+ json!({"toolCallId": "patch"}),+ json!({"toolCallId": "patch", "_meta": {}}),+ ] {+ thread+ .upsert_tool_call_patch(serde_json::from_value(patch).expect("patch"), cx)+ .expect("metadata-only update");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.label, label);+ assert_eq!(call.content()[0].markdown(), Some(&output));+ assert_eq!(call.raw_input_markdown.as_ref(), Some(&input));+ assert_eq!(output.read(cx).source(), "body");+ }+ assert_eq!(+ thread.tool_call(&id).expect("tool").1.meta,+ Some(acp_v2::Meta::new())+ );+ thread+ .upsert_tool_call_patch(acp_v2::ToolCallUpdate::new("patch").title(" "), cx)+ .expect("whitespace title");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.title.as_deref(), Some(" "));+ assert_eq!(call.label.read(cx).source(), "named");++ thread+ .upsert_tool_call_patch(+ serde_json::from_value(json!({+ "toolCallId": "patch",+ "title": null, "name": null, "kind": null, "status": null,+ "content": null, "rawInput": null, "_meta": null+ }))+ .expect("clear patch"),+ cx,+ )+ .expect("clear optional fields");+ let (_, call) = thread.tool_call(&id).expect("tool survives clear");+ assert_eq!(call.title, None);+ assert_eq!(call.name, None);+ assert_eq!(call.tool_name, None);+ assert_eq!(call.reported_kind, None);+ assert_eq!(call.reported_status, None);+ assert_eq!(call.meta, None);+ assert_eq!(call.raw_input, None);+ assert!(call.raw_input_markdown.is_none());+ assert_eq!(call.raw_output, Some(json!("fallback")));+ assert_eq!(call.content()[0].to_markdown(cx), "fallback");+ let ToolCallContent::ContentBlock { block, .. } = &call.content()[0] else {+ panic!("derived raw-output fallback");+ };+ assert!(block.source.is_none());+ assert_eq!(thread.entries().len(), 1);+ thread+ .upsert_tool_call_patch(+ serde_json::from_value(json!({"toolCallId": "patch", "rawOutput": null}))+ .expect("raw clear"),+ cx,+ )+ .expect("clear retained raw output");+ assert!(thread.tool_call(&id).expect("tool").1.content().is_empty());+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("patch")+ .content(vec!["refilled".into()])+ .status(acp_v2::ToolCallStatus::Completed),+ cx,+ )+ .expect("refill existing record");+ let (index, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(index, 0);+ assert_eq!(call.content()[0].to_markdown(cx), "refilled");+ assert_eq!(call.status(), ToolCallStatus::Completed);+ });+ }++ #[gpui::test]+ async fn test_tool_patch_metadata_policy_preserves_legacy_hints_and_clears_v2_hints(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ let id = acp_v1::ToolCallId::new("metadata");+ let meta = acp_v1::Meta::from_iter([+ (TOOL_NAME_META_KEY.into(), json!("legacy_name")),+ (+ SUBAGENT_SESSION_INFO_META_KEY.into(),+ json!({"session_id": "child", "message_start_index": 0}),+ ),+ ("opaque".into(), json!({"keep": ["all", "values"]})),+ ]);+ thread+ .upsert_tool_call(acp_v1::ToolCall::new(id.clone(), "").meta(meta.clone()), cx)+ .expect("legacy creation");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.name, None);+ assert_eq!(call.tool_name.as_deref(), Some("legacy_name"));+ assert!(call.subagent_session_info.is_some());+ assert_eq!(call.meta.as_ref(), Some(&meta));++ let newer_meta = acp_v1::Meta::from_iter([("opaque".into(), json!({"new": true}))]);+ thread+ .update_tool_call(+ acp_v1::ToolCallUpdate::new(id.clone(), acp_v1::ToolCallUpdateFields::new())+ .meta(newer_meta.clone()),+ cx,+ )+ .expect("legacy metadata update");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.meta.as_ref(), Some(&newer_meta));+ assert_eq!(call.tool_name.as_deref(), Some("legacy_name"));+ assert!(call.subagent_session_info.is_some());+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("metadata").meta(acp_v2::Meta::new()),+ cx,+ )+ .expect("authoritative metadata replacement");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.meta, Some(acp_v2::Meta::new()));+ assert_eq!(call.tool_name, None);+ assert!(call.subagent_session_info.is_none());+ assert_eq!(call.label.read(cx).source(), "Tool call");+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("metadata")+ .name("first_class")+ .meta(meta),+ cx,+ )+ .expect("first-class name wins");+ assert_eq!(+ thread.tool_call(&id).expect("tool").1.tool_name.as_deref(),+ Some("first_class")+ );+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("metadata").meta(None::<acp_v2::Meta>),+ cx,+ )+ .expect("clear metadata without clearing name");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.meta, None);+ assert_eq!(call.name.as_deref(), Some("first_class"));+ assert_eq!(call.tool_name.as_deref(), Some("first_class"));+ assert!(call.subagent_session_info.is_none());+ });+ }++ #[gpui::test]+ async fn test_tool_reported_status_is_independent_of_local_authorization(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ let id = acp_v1::ToolCallId::new("permission");+ let permission = thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization(+ acp_v1::ToolCall::new(id.clone(), "Authorize").into(),+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ "allow",+ "Allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ )]),+ AuthorizationKind::PermissionGrant,+ cx,+ )+ })+ .expect("request");+ thread.update(cx, |thread, cx| {+ for status in [json!("_future_status"), serde_json::Value::Null] {+ thread+ .upsert_tool_call_patch(+ serde_json::from_value(+ json!({"toolCallId": "permission", "status": status}),+ )+ .expect("status patch"),+ cx,+ )+ .expect("nonterminal status");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ assert!(call.authorization().is_some());+ assert_eq!(+ serde_json::to_value(&call.reported_status).expect("reported status"),+ status+ );+ }+ thread.cancel_tool_call_authorization(&id, cx);+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.reported_status, None);+ assert_eq!(call.status(), ToolCallStatus::Canceled);+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("permission")+ .status(None::<acp_v2::ToolCallStatus>),+ cx,+ )+ .expect("clear only reported information");+ assert_eq!(+ thread.tool_call(&id).expect("tool").1.status(),+ ToolCallStatus::Canceled+ );+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("permission")+ .status(acp_v2::ToolCallStatus::InProgress),+ cx,+ )+ .expect("new reported progress supersedes local outcome");+ assert_eq!(+ thread.tool_call(&id).expect("tool").1.status(),+ ToolCallStatus::InProgress+ );+ });+ assert!(matches!(+ permission.await,+ RequestPermissionOutcome::Cancelled+ ));++ let permission = thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization(+ acp_v1::ToolCallUpdate::new(id.clone(), acp_v1::ToolCallUpdateFields::new()),+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ "allow",+ "Allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ )]),+ AuthorizationKind::PermissionGrant,+ cx,+ )+ })+ .expect("second request");+ thread.update(cx, |thread, cx| {+ let original_label = thread.tool_call(&id).expect("tool").1.label.clone();+ let result = thread.upsert_tool_call_patch(+ serde_json::from_value(json!({+ "toolCallId": "permission",+ "status": "cancelled",+ "title": "must not replace valid presentation",+ "content": [{"type": "terminal", "terminalId": "missing"}]+ }))+ .expect("cancelled patch"),+ cx,+ );+ assert!(result.is_err());+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(+ call.reported_status,+ Some(acp_v2::ToolCallStatus::Cancelled)+ );+ assert_eq!(call.status(), ToolCallStatus::Canceled);+ assert!(call.authorization().is_none());+ assert_eq!(call.label, original_label);+ assert_eq!(call.label.read(cx).source(), "Authorize");+ });+ assert!(matches!(+ permission.await,+ RequestPermissionOutcome::Cancelled+ ));+ }++ #[gpui::test]+ async fn test_tool_authorization_preserves_legacy_continuation_without_rewriting_reported_status(+ cx: &mut TestAppContext,+ ) {+ init_test(cx);+ for (kind, initial, incoming, expected) in [+ (+ AuthorizationKind::PermissionGrant,+ acp_v1::ToolCallStatus::Pending,+ None,+ ToolCallStatus::InProgress,+ ),+ (+ AuthorizationKind::PermissionGrant,+ acp_v1::ToolCallStatus::InProgress,+ None,+ ToolCallStatus::InProgress,+ ),+ (+ AuthorizationKind::PermissionGrant,+ acp_v1::ToolCallStatus::Completed,+ None,+ ToolCallStatus::Completed,+ ),+ (+ AuthorizationKind::ActionChoice,+ acp_v1::ToolCallStatus::InProgress,+ None,+ ToolCallStatus::InProgress,+ ),+ (+ AuthorizationKind::ActionChoice,+ acp_v1::ToolCallStatus::Completed,+ None,+ ToolCallStatus::InProgress,+ ),+ (+ AuthorizationKind::PermissionGrant,+ acp_v1::ToolCallStatus::InProgress,+ Some(acp_v1::ToolCallStatus::Completed),+ ToolCallStatus::InProgress,+ ),+ ] {+ let thread = new_test_thread(cx).await;+ let id = acp_v1::ToolCallId::new("continuation");+ thread.update(cx, |thread, cx| {+ thread+ .upsert_tool_call(+ acp_v1::ToolCall::new(id.clone(), "Original").status(initial),+ cx,+ )+ .expect("initial tool");+ });+ let option_kind = if kind == AuthorizationKind::ActionChoice {+ acp_v1::PermissionOptionKind::RejectOnce+ } else {+ acp_v1::PermissionOptionKind::AllowOnce+ };+ let permission = thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization(+ acp_v1::ToolCallUpdate::new(+ id.clone(),+ acp_v1::ToolCallUpdateFields::new().status(incoming),+ ),+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ "selected",+ "Choose",+ option_kind,+ )]),+ kind,+ cx,+ )+ })+ .expect("explicit legacy authorization request");+ let reported =+ tool_status_from_v1(incoming.unwrap_or(initial)).expect("known test status");thread.update(cx, |thread, cx| {- let mut update = acp_v1::CompactionUpdate::new(- "compaction",- acp_v1::CompactionStatus::Completed,+ let (_, call) = thread.tool_call(&id).expect("waiting tool");+ assert_eq!(call.status(), ToolCallStatus::WaitingForConfirmation);+ assert_eq!(call.reported_status.as_ref(), Some(&reported));+ assert_eq!(call.permission_status(), Some(initial));+ thread.authorize_tool_call(+ id.clone(),+ SelectedPermissionOutcome::new("selected".into(), option_kind),+ cx,);- if replace_summary {- update = update.summary(blocks.clone());- }- thread- .handle_session_update(acp_v1::SessionUpdate::CompactionUpdate(update), cx)- .expect("failed to complete compaction");+ let (_, call) = thread.tool_call(&id).expect("authorized tool");+ assert_eq!(call.status(), expected);+ assert_eq!(call.reported_status.as_ref(), Some(&reported));+ assert!(call.authorization().is_none());});- thread.read_with(cx, |thread, cx| {- let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.first()- else {- panic!("expected compaction entry");- };- let [text, resource, image, link, unsupported, blob] =- compaction.summary.as_slice()- else {- panic!("expected six retained content blocks");- };- assert_eq!(text.to_markdown(cx), "retained context");- assert_eq!(- resource- .as_view()- .embedded_resource()- .map(|(resource, _)| resource),- Some(text_resource)- );- assert_eq!(resource.to_markdown(cx), "Retained resource text");- assert_eq!(- image- .image()- .and_then(|(_, dimensions)| dimensions)- .map(|size| (size.width, size.height)),- Some((1, 1))- );- assert_eq!(- link.as_view().resource_link().map(|link| link.uri.as_str()),- Some("https://example.com/context")- );- let Some(content) = unsupported.unsupported_content() else {- panic!("expected preserved audio with a visible fallback");- };- assert_eq!(content, stored_audio);- assert!(unsupported.visible_content(cx));- assert_eq!(- blob.as_view()- .embedded_resource()- .map(|(resource, _)| resource),- Some(blob_resource)- );- assert!(blob.visible_content(cx));- assert_eq!(- thread.to_markdown(cx),- concat!(- "## Context Compaction (Completed)\n\n",- "retained context\n\n",- "Retained resource text\n\n",- "`Image`\n\n",- "https://example.com/context\n\n",- "Audio content is not supported.\n\n",- "summary://attachment\n\n",+ assert!(+ matches!(permission.await, RequestPermissionOutcome::Selected(outcome) if outcome.option_id == "selected".into())+ );+ thread.update(cx, |thread, cx| {+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("continuation")+ .status(None::<acp_v2::ToolCallStatus>),+ cx,)- );+ .expect("clear reported state, not the local decision");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.reported_status, None);+ assert_eq!(call.status(), expected);+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("continuation").status(reported),+ cx,+ )+ .expect("even repeated reported state supersedes a local outcome");+ assert_eq!(thread.tool_call(&id).expect("tool").1.local_status, None);});}-- thread.update(cx, |thread, cx| {- thread- .handle_session_update(- acp_v1::SessionUpdate::CompactionUpdate(- acp_v1::CompactionUpdate::new(- "compaction",- acp_v1::CompactionStatus::Completed,- )- .summary(vec![audio.clone()]),- ),- cx,- )- .expect("failed to replace summary with audio");- });- thread.read_with(cx, |thread, cx| {- let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.first()- else {- panic!("expected compaction entry");- };- assert!(matches!(- compaction.summary.as_slice(),- [block] if block.unsupported_content() == Some(stored_audio)- ));- assert!(- thread- .to_markdown(cx)- .contains("Audio content is not supported.")- );- });}#[gpui::test]- async fn test_context_compaction_updates_preserve_timeline_and_emit_events(- cx: &mut TestAppContext,- ) {+ async fn test_tool_location_clear_ignores_pending_resolution(cx: &mut TestAppContext) {init_test(cx);- let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;+ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(path!("/project"), json!({"file.rs": "first\nsecond\n"}))+ .await;+ let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;let connection = Rc::new(FakeAgentConnection::new());let thread = cx.update(|cx| {- connection.new_session(project, PathList::new(&[Path::new(path!("/test"))]), cx)+ connection.new_session(project, PathList::new(&[Path::new(path!("/project"))]), cx)}).await- .expect("failed to create ACP thread");- let events = Rc::new(RefCell::new(Vec::new()));- let _subscription = cx.update(|cx| {- let events = events.clone();- cx.subscribe(&thread, move |_, event, _| match event {- AcpThreadEvent::NewEntry => events.borrow_mut().push(None),- AcpThreadEvent::EntryUpdated(index) => events.borrow_mut().push(Some(*index)),- _ => {}- })- });-- thread.update(cx, |thread, cx| {- for update in [- acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(- "first",- acp_v1::CompactionStatus::InProgress,- )),- acp_v1::SessionUpdate::ToolCall(acp_v1::ToolCall::new("tool", "Unrelated tool")),- acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(- "second",- acp_v1::CompactionStatus::InProgress,- )),- acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(- "second",- acp_v1::CompactionStatus::Completed,- )),- acp_v1::SessionUpdate::CompactionSummaryChunk(acp_v1::CompactionSummaryChunk::new(- "first",- acp_v1::ContentBlock::Text(acp_v1::TextContent::new("partial summary")),- )),- ] {- thread- .handle_session_update(update, cx)- .expect("failed to apply interleaved session update");- }- assert!(thread.is_compacting());- });- assert_eq!(*events.borrow(), [None, None, None, Some(2), Some(0)]);-+ .expect("session");+ let id = acp_v1::ToolCallId::new("locations");thread.update(cx, |thread, cx| {- thread- .handle_session_update(- acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(- "first",- acp_v1::CompactionStatus::Cancelled,- )),- cx,- )- .expect("failed to cancel compaction");- assert!(!thread.is_compacting());+ thread.upsert_tool_call_patch(+ serde_json::from_value(json!({+ "toolCallId": "locations",+ "locations": [{"path": path!("/project/file.rs"), "line": 2, "_meta": {"location": true}}]+ })).expect("location patch"),+ cx,+ ).expect("new locations");+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert_eq!(call.locations[0].path, PathBuf::from(path!("/project/file.rs")));+ assert_eq!(call.locations[0].line, Some(2));+ assert_eq!(call.locations[0].meta, Some(acp_v1::Meta::from_iter([("location".into(), json!(true))])));+ thread.upsert_tool_call_patch(+ serde_json::from_value(json!({"toolCallId": "locations", "locations": null})).expect("clear locations"),+ cx,+ ).expect("clear before the previous lookup finishes");});- assert_eq!(- *events.borrow(),- [None, None, None, Some(2), Some(0), Some(0)]- );+ cx.run_until_parked();thread.read_with(cx, |thread, cx| {- let [- AgentThreadEntry::ContextCompaction(first),- AgentThreadEntry::ToolCall(_),- AgentThreadEntry::ContextCompaction(second),- ] = thread.entries.as_slice()- else {- panic!("updates must preserve the original timeline positions");- };- assert_eq!(first.id.0.as_ref(), "first");- assert_eq!(first.status, ContextCompactionStatus::Canceled);- assert_eq!(second.id.0.as_ref(), "second");- assert_eq!(second.status, ContextCompactionStatus::Completed);- assert!(- thread- .to_markdown(cx)- .starts_with("## Context Compaction (Canceled)\n\npartial summary\n\n")- );+ let (_, call) = thread.tool_call(&id).expect("tool");+ assert!(call.locations.is_empty());+ assert!(call.resolved_locations.is_empty());+ assert!(thread.project.read(cx).agent_location().is_none());});}@@ -9822,7 +11240,7 @@ mod tests {let call = cx.update(|cx| {ToolCall::from_acp(call,- ToolCallStatus::Pending,+ Some(ToolCallStatus::Pending),languages.clone(),&HashMap::default(),cx,@@ -9862,7 +11280,7 @@ mod tests {let mut call = cx.update(|cx| {ToolCall::from_acp(acp_v1::ToolCall::new("tool", ""),- ToolCallStatus::Pending,+ Some(ToolCallStatus::Pending),languages.clone(),&HashMap::default(),cx,@@ -9946,7 +11364,7 @@ mod tests {let mut created_with_raw_output = cx.update(|cx| {ToolCall::from_acp(acp_v1::ToolCall::new("created", "Tool").raw_output(serde_json::json!("first")),- ToolCallStatus::Pending,+ Some(ToolCallStatus::Pending),languages.clone(),&HashMap::default(),cx,@@ -9956,7 +11374,7 @@ mod tests {let mut updated_with_raw_output = cx.update(|cx| {ToolCall::from_acp(acp_v1::ToolCall::new("updated", "Tool"),- ToolCallStatus::Pending,+ Some(ToolCallStatus::Pending),languages.clone(),&HashMap::default(),cx,@@ -9977,7 +11395,8 @@ mod tests {.expect("first raw output update should apply");});let first_update_export = cx.read(|cx| updated_with_raw_output.to_markdown(cx));- let Some(ToolCallContent::ContentBlock(block)) = updated_with_raw_output.content().first()+ let Some(ToolCallContent::ContentBlock { block, .. }) =+ updated_with_raw_output.content().first()else {panic!("expected raw output content");};@@ -10037,7 +11456,7 @@ mod tests {acp_v1::ToolCall::new("tool", "Tool").content(vec!["structured".into()]).raw_output(serde_json::json!("raw")),- ToolCallStatus::Pending,+ Some(ToolCallStatus::Pending),languages.clone(),&HashMap::default(),cx,@@ -10336,15 +11755,15 @@ mod tests {.content(content.clone()).raw_input(json!("input")).raw_output(json!("raw fallback")),- ToolCallStatus::InProgress,+ Some(ToolCallStatus::InProgress),languages.clone(),&terminals,cx,).expect("tool");let [- ToolCallContent::ContentBlock(block),- ToolCallContent::Diff(diff),+ ToolCallContent::ContentBlock { block, .. },+ ToolCallContent::LegacyDiff { diff, .. },] = call.content()else {panic!("text and diff");@@ -10366,7 +11785,7 @@ mod tests {assert_eq!(call.raw_input_markdown.as_ref(), Some(&input));assert_eq!(input.read(cx).source(), text);assert_eq!(call.diffs().next(), Some(&diff));- let ToolCallContent::ContentBlock(block) = &call.content()[0] else {+ let ToolCallContent::ContentBlock { block, .. } = &call.content()[0] else {panic!("text content");};assert_eq!(block.markdown(), Some(&output));@@ -10552,7 +11971,9 @@ mod tests {let (_, call) = thread.tool_call(&id).expect("original tool");let label = call.label.clone();let original_content = match &call.content()[0] {- ToolCallContent::ContentBlock(block) => block.markdown().expect("text").clone(),+ ToolCallContent::ContentBlock { block, .. } => {+ block.markdown().expect("text").clone()+ }_ => panic!("text content"),};let update = acp_v1::ToolCallUpdate::new(@@ -10575,30 +11996,30 @@ mod tests {)]));let result = if upsert {thread- .upsert_tool_call_inner(update, status.into(), cx)+ .upsert_tool_call_inner(update, Some(status.into()), cx).map_err(anyhow::Error::from)} else {thread.update_tool_call(update, cx)};assert!(result.is_err(), "unknown terminal must fail conversion");let (_, call) = thread.tool_call(&id).expect("tool must remain");- assert_eq!(call.status.as_acp_status(), Some(status));+ assert_eq!(call.permission_status(), Some(status));assert_eq!(call.label, label);assert_eq!(call.label.read(cx).source(), "Original title");- assert_eq!(call.kind, acp_v1::ToolKind::Read);+ assert_eq!(call.kind(), &acp_v2::ToolKind::Read);assert_eq!(call.tool_name.as_deref(), Some("original-tool"));assert_eq!(call.raw_input, Some(json!({"original": true})));assert_eq!(call.raw_output, Some(json!("original raw")));assert!(call.subagent_session_info.is_none());assert_eq!(original_content.read(cx).source(), "original output");- let [ToolCallContent::ContentBlock(block)] = call.content() else {+ let [ToolCallContent::ContentBlock { block, .. }] = call.content() else {panic!("original content must remain");};assert_eq!(block.markdown(), Some(&original_content));if status == acp_v1::ToolCallStatus::InProgress {assert!(matches!(- call.status,- ToolCallStatus::WaitingForConfirmation { .. }+ call.status(),+ ToolCallStatus::WaitingForConfirmation));thread.authorize_tool_call(id.clone(),@@ -10609,7 +12030,7 @@ mod tests {cx,);} else {- assert!(matches!(call.status, ToolCallStatus::Completed));+ assert!(matches!(call.status(), ToolCallStatus::Completed));}});if status == acp_v1::ToolCallStatus::InProgress {@@ -10636,7 +12057,7 @@ mod tests {).expect("valid correction after failed patch");let (_, call) = thread.tool_call(&id).expect("corrected tool");- assert!(matches!(call.status, ToolCallStatus::Completed));+ assert!(matches!(call.status(), ToolCallStatus::Completed));assert_eq!(call.content()[0].to_markdown(cx), "corrected output");});}@@ -10699,8 +12120,8 @@ mod tests {.expect("tool call should exist");assert_eq!(tool_call.label.read(cx).source(), "Updated title");assert!(matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation { .. }+ tool_call.status(),+ ToolCallStatus::WaitingForConfirmation));assert_eq!(tool_call.content().len(), 1);assert_eq!(tool_call.content()[0].to_markdown(cx), "updated content");@@ -10727,8 +12148,8 @@ mod tests {.expect("tool call should exist");assert_eq!(tool_call.label.read(cx).source(), "Updated again");assert!(matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation { .. }+ tool_call.status(),+ ToolCallStatus::WaitingForConfirmation));assert_eq!(tool_call.content().len(), 1);assert_eq!(tool_call.content()[0].to_markdown(cx), "updated again");@@ -10746,7 +12167,7 @@ mod tests {let (_, tool_call) = thread.tool_call(&tool_call_id).expect("tool call should exist");- assert!(matches!(tool_call.status, ToolCallStatus::InProgress));+ assert!(matches!(tool_call.status(), ToolCallStatus::InProgress));});match permission_task.await {@@ -10780,7 +12201,7 @@ mod tests {.tool_call(&tool_call_id).expect("tool call should exist");assert_eq!(tool_call.label.read(cx).source(), "Completed");- assert!(matches!(tool_call.status, ToolCallStatus::Completed));+ assert!(matches!(tool_call.status(), ToolCallStatus::Completed));assert_eq!(tool_call.content().len(), 1);assert_eq!(tool_call.content()[0].to_markdown(cx), "done");});@@ -10836,13 +12257,11 @@ mod tests {let (_, tool_call) = thread.tool_call(&tool_call_id).expect("tool call should exist");- assert!(matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation {- current_status: acp_v1::ToolCallStatus::InProgress,- ..- }- ));+ assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);+ assert_eq!(+ tool_call.permission_status(),+ Some(acp_v1::ToolCallStatus::InProgress)+ );});thread.update(cx, |thread, cx| {@@ -10860,7 +12279,7 @@ mod tests {let (_, tool_call) = thread.tool_call(&tool_call_id).expect("tool call should exist");- assert!(matches!(tool_call.status, ToolCallStatus::InProgress));+ assert!(matches!(tool_call.status(), ToolCallStatus::InProgress));});match permission_task.await {@@ -10928,13 +12347,11 @@ mod tests {.tool_call(&tool_call_id).expect("tool call should exist");assert_eq!(tool_call.label.read(cx).source(), "Needs permission");- assert!(matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation {- current_status: acp_v1::ToolCallStatus::InProgress,- ..- }- ));+ assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);+ assert_eq!(+ tool_call.permission_status(),+ Some(acp_v1::ToolCallStatus::InProgress)+ );});thread.update(cx, |thread, cx| {@@ -11003,7 +12420,7 @@ mod tests {let (_, tool_call) = thread.tool_call(&tool_call_id).expect("tool call should exist");- assert!(matches!(tool_call.status, ToolCallStatus::Canceled));+ assert!(matches!(tool_call.status(), ToolCallStatus::Canceled));});match permission_task.await {@@ -11067,7 +12484,7 @@ mod tests {let (_, tool_call) = thread.tool_call(&tool_call_id).expect("tool call should exist");- assert!(matches!(tool_call.status, ToolCallStatus::Completed));+ assert!(matches!(tool_call.status(), ToolCallStatus::Completed));});match permission_task.await {@@ -13342,12 +14759,16 @@ mod tests {// The entry should be a failed tool callif let AgentThreadEntry::ToolCall(tool_call) = &thread.entries[0] {assert_eq!(tool_call.id, nonexistent_id);- assert!(matches!(tool_call.status, ToolCallStatus::Failed));- assert_eq!(tool_call.kind, acp_v1::ToolKind::Fetch);+ assert!(matches!(tool_call.status(), ToolCallStatus::Failed));+ assert_eq!(tool_call.kind(), &acp_v2::ToolKind::Fetch);// Check that the content contains the error messageassert_eq!(tool_call.content().len(), 1);- if let ToolCallContent::ContentBlock(content_block) = &tool_call.content()[0] {+ if let ToolCallContent::ContentBlock {+ block: content_block,+ ..+ } = &tool_call.content()[0]+ {let markdown = content_block.plain_markdown().expect("expected markdown");assert!(markdown.read(cx).source().contains("Tool call not found"));} else {@@ -14163,9 +15584,9 @@ mod tests {.expect("should have tool call entry");assert!(- matches!(tool_entry.status, ToolCallStatus::Canceled),+ matches!(tool_entry.status(), ToolCallStatus::Canceled),"tool should be marked as Canceled when response is Cancelled, got {:?}",- tool_entry.status+ tool_entry.status());});}@@ -15846,6 +17267,92 @@ mod tests {assert_failed_tool_update_resumes_sleep_prevention(true, cx).await;}+ #[gpui::test]+ async fn test_failed_v2_terminal_patch_settles_only_its_permission(cx: &mut TestAppContext) {+ init_test(cx);+ for status in [+ acp_v2::ToolCallStatus::Completed,+ acp_v2::ToolCallStatus::Failed,+ acp_v2::ToolCallStatus::Cancelled,+ ] {+ let thread = new_test_thread(cx).await;+ let (complete, request) = start_test_turn(&thread, cx);+ cx.run_until_parked();+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ let first_id = acp_v1::ToolCallId::new("first");+ let second_id = acp_v1::ToolCallId::new("second");+ let first_permission = request_test_permission(&thread, first_id.clone(), cx);+ let second_permission = request_test_permission(&thread, second_id.clone(), cx);+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ let updated_entries = Rc::new(RefCell::new(Vec::new()));+ let _subscription = cx.update(|cx| {+ cx.subscribe(&thread, {+ let updated_entries = updated_entries.clone();+ move |_, event, _| {+ if let AcpThreadEvent::EntryUpdated(index) = event {+ updated_entries.borrow_mut().push(*index);+ }+ }+ })+ });+ let first_index = thread.update(cx, |thread, cx| {+ let (index, first) = thread.tool_call(&first_id).expect("first tool");+ let original_label = first.label.clone();+ assert!(+ thread+ .upsert_tool_call_patch(+ acp_v2::ToolCallUpdate::new("first")+ .status(status.clone())+ .title("invalid replacement")+ .content(vec![acp_v2::ToolCallContent::Terminal(+ acp_v2::Terminal::new("missing")+ )]),+ cx,+ )+ .is_err()+ );+ let (_, first) = thread.tool_call(&first_id).expect("updated tool");+ assert_eq!(first.reported_status.as_ref(), Some(&status));+ assert!(first.authorization().is_none());+ assert_eq!(first.label, original_label);+ assert_eq!(first.label.read(cx).source(), "Needs permission");+ assert!(+ thread+ .tool_call(&second_id)+ .expect("second tool")+ .1+ .authorization()+ .is_some()+ );+ index+ });+ assert!(matches!(+ first_permission.await,+ RequestPermissionOutcome::Cancelled+ ));+ cx.run_until_parked();+ assert!(updated_entries.borrow().contains(&first_index));+ assert_eq!(+ cx.active_idle_sleep_preventions(),+ 0,+ "another permission still needs input"+ );+ thread.update(cx, |thread, cx| {+ thread.cancel_tool_call_authorization(&second_id, cx)+ });+ assert!(matches!(+ second_permission.await,+ RequestPermissionOutcome::Cancelled+ ));+ assert_eq!(cx.active_idle_sleep_preventions(), 1);+ complete+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))+ .expect("backend still running");+ request.await.expect("turn completes");+ assert_eq!(cx.active_idle_sleep_preventions(), 0);+ }+ }+fn start_test_turn(thread: &Entity<AcpThread>,cx: &mut TestAppContext,@@ -16050,7 +17557,7 @@ mod tests {if upsert {assert!(thread- .upsert_tool_call_inner(update, ToolCallStatus::Completed, cx)+ .upsert_tool_call_inner(update, Some(ToolCallStatus::Completed), cx).is_err());} else {@@ -16068,8 +17575,7 @@ mod tests {.tool_call(&tool_call_id).expect("tool call should remain present").1- .status- .as_acp_status(),+ .permission_status(),Some(acp_v1::ToolCallStatus::Completed));assert!(!thread.is_waiting_for_confirmation());diff --git a/crates/acp_thread/src/diff.rs b/crates/acp_thread/src/diff.rsindex 06ae8225152..da751ed9872 100644--- a/crates/acp_thread/src/diff.rs+++ b/crates/acp_thread/src/diff.rs@@ -1,14 +1,278 @@-use anyhow::Result;+mod patch;++use agent_client_protocol::schema::v2 as acp_v2;+use anyhow::{Result, anyhow, ensure};use buffer_diff::BufferDiff;-use gpui::{App, AppContext, AsyncApp, Context, Entity, Subscription, Task};+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,};+use markdown::Markdown;use multi_buffer::{MultiBuffer, PathKey, excerpt_context_lines};use std::{cmp::Reverse, ops::Range, path::Path, sync::Arc};use util::ResultExt;+#[derive(Debug)]+pub struct DiffPatch {+ pub files: Vec<DiffPatchFile>,+ pub fallback: Option<Entity<Markdown>>,+}++#[derive(Debug)]+pub struct DiffPatchFile {+ pub change_index: usize,+ pub hunks: Vec<DiffPatchHunk>,+}++#[derive(Debug)]+pub struct DiffPatchHunk {+ pub header: SharedString,+ pub buffer: Entity<MultiBuffer>,+ _update_diff: Task<()>,+}++impl DiffPatch {+ pub(crate) fn new(+ source: &acp_v2::Diff,+ language_registry: &Arc<LanguageRegistry>,+ cx: &mut App,+ ) -> Self {+ let mut files = source+ .changes+ .iter()+ .enumerate()+ .map(|(change_index, _)| DiffPatchFile {+ change_index,+ hunks: Vec::new(),+ })+ .collect::<Vec<_>>();+ if source.patch.is_none() {+ return Self {+ files,+ fallback: None,+ };+ }++ match Self::parse(source) {+ Ok(parsed) => {+ for (change_index, file) in parsed {+ let path = file.new_path.or(file.old_path).unwrap_or_default();+ if let Some(render) = files.get_mut(change_index) {+ render.hunks = file+ .hunks+ .into_iter()+ .map(|hunk| {+ DiffPatchHunk::new(hunk, &path, language_registry.clone(), cx)+ })+ .collect();+ }+ }+ Self {+ files,+ fallback: None,+ }+ }+ Err(error) => {+ let preview = format!(+ "Diff preview unavailable: {error}\n\n{}",+ crate::ToolCallContent::patch_preview(source)+ );+ Self {+ files,+ fallback: Some(crate::ContentBlock::create_markdown(+ preview,+ language_registry,+ cx,+ )),+ }+ }+ }+ }++ fn parse(source: &acp_v2::Diff) -> Result<Vec<(usize, patch::PatchFile)>> {+ let patch = source+ .patch+ .as_ref()+ .ok_or_else(|| anyhow!("no patch supplied"))?;+ ensure!(+ patch.format == acp_v2::DiffPatchFormat::GitPatch,+ "unsupported patch format"+ );+ ensure!(+ !source.changes.is_empty(),+ "patch has no reported file changes"+ );+ let mut change_indices: HashMap<_, Option<usize>> = HashMap::default();+ for (index, change) in source.changes.iter().enumerate() {+ if let Some(paths) = diff_change_paths(change) {+ change_indices+ .entry(paths)+ .and_modify(|index| *index = None)+ .or_insert(Some(index));+ }+ }+ let mut seen = HashSet::default();+ patch::parse_patch(&patch.text)?+ .into_iter()+ .map(|mut file| {+ let paths = (+ file.old_path.as_deref().map(Path::new),+ file.new_path.as_deref().map(Path::new),+ );+ let anonymous = paths == (None, None);+ let paths = if anonymous {+ let [change] = source.changes.as_slice() else {+ return Err(anyhow!(+ "patch without filenames requires exactly one file change"+ ));+ };+ diff_change_paths(change)+ .ok_or_else(|| anyhow!("unsupported file operation"))?+ } else {+ paths+ };+ let index = change_indices+ .get(&paths)+ .copied()+ .flatten()+ .ok_or_else(|| {+ anyhow!(+ "patch paths are ambiguous or do not match the reported file changes"+ )+ })?;+ ensure!(seen.insert(index), "repeated patch file");+ let change = source+ .changes+ .get(index)+ .ok_or_else(|| anyhow!("missing file change"))?;+ ensure!(+ matches!(change.file_type, None | Some(acp_v2::DiffFileType::Text)),+ "text patch supplied for a non-text file"+ );+ if anonymous && let Some((old, new)) = diff_change_paths(change) {+ file.old_path = old.map(|path| path.to_string_lossy().into_owned());+ file.new_path = new.map(|path| path.to_string_lossy().into_owned());+ }+ ensure!(+ file.hunks.iter().all(|hunk| {+ (file.old_path.is_some() || hunk.old_count == 0)+ && (file.new_path.is_some() || hunk.new_count == 0)+ }),+ "hunk contents conflict with the reported file operation"+ );+ Ok((index, file))+ })+ .collect()+ }+}++impl DiffPatchHunk {+ fn new(+ hunk: patch::PatchHunk,+ path: &str,+ language_registry: Arc<LanguageRegistry>,+ cx: &mut App,+ ) -> Self {+ let range_label = |start, count| {+ if count == 1 {+ format!("{start}")+ } else {+ format!("{start},{count}")+ }+ };+ let header = format!(+ "@@ -{} +{} @@",+ range_label(hunk.old_start, hunk.old_count),+ range_label(hunk.new_start, hunk.new_count),+ )+ .into();+ let new_buffer = cx.new(|cx| {+ let mut buffer = Buffer::local(hunk.new_text, cx);+ buffer.set_capability(Capability::ReadOnly, cx);+ buffer+ });+ let multibuffer = cx.new(|cx| {+ let mut multibuffer = MultiBuffer::without_headers(Capability::ReadOnly);+ multibuffer.set_excerpts_for_path(+ PathKey::for_buffer(&new_buffer, cx),+ new_buffer.clone(),+ [Point::new(0, 0)..new_buffer.read(cx).max_point()],+ 0,+ cx,+ );+ multibuffer+ });+ let task = cx.spawn({+ let multibuffer = multibuffer.clone();+ let path = path.to_owned();+ async move |cx| {+ let language = language_registry+ .load_language_for_file_path(Path::new(&path))+ .await+ .log_err();+ new_buffer.update(cx, |buffer, cx| buffer.set_language(language.clone(), cx));+ let snapshot = new_buffer.read_with(cx, |buffer, _| buffer.snapshot());+ let diff = cx.new(|cx| {+ // A hunk is only a snippet: it must never offer restore/apply operations.+ BufferDiff::new(&snapshot, language, Some(language_registry), cx)+ });+ diff.update(cx, |diff, cx| {+ diff.set_base_text(Some(hunk.old_text.into()), snapshot.text, cx)+ })+ .await;+ multibuffer.update(cx, |buffer, cx| {+ buffer.add_diff(diff, cx);+ buffer.set_all_diff_hunks_expanded(cx);+ });+ }+ });+ Self {+ header,+ buffer: multibuffer,+ _update_diff: task,+ }+ }+}++fn diff_change_paths(change: &acp_v2::DiffChange) -> Option<(Option<&Path>, Option<&Path>)> {+ match &change.operation {+ acp_v2::DiffChangeOperation::Add(change) => Some((None, Some(&change.path.0))),+ acp_v2::DiffChangeOperation::Delete(change) => Some((Some(&change.path.0), None)),+ acp_v2::DiffChangeOperation::Modify(change) => {+ Some((Some(&change.path.0), Some(&change.path.0)))+ }+ acp_v2::DiffChangeOperation::Move(change) | acp_v2::DiffChangeOperation::Copy(change) => {+ Some((Some(&change.old_path.0), Some(&change.path.0)))+ }+ _ => None,+ }+}++pub fn diff_change_label(change: &acp_v2::DiffChange) -> String {+ match &change.operation {+ acp_v2::DiffChangeOperation::Add(change) => format!("Added {}", change.path.0.display()),+ acp_v2::DiffChangeOperation::Delete(change) => {+ format!("Deleted {}", change.path.0.display())+ }+ acp_v2::DiffChangeOperation::Modify(change) => {+ format!("Modified {}", change.path.0.display())+ }+ acp_v2::DiffChangeOperation::Move(change) => format!(+ "Moved {} → {}",+ change.old_path.0.display(),+ change.path.0.display()+ ),+ acp_v2::DiffChangeOperation::Copy(change) => format!(+ "Copied {} → {}",+ change.old_path.0.display(),+ change.path.0.display()+ ),+ _ => "Unsupported file operation".to_owned(),+ }+}+pub enum Diff {Pending(PendingDiff),Finalized(FinalizedDiff),@@ -406,11 +670,268 @@ async fn build_buffer_diff(#[cfg(test)]mod tests {- use gpui::{AppContext as _, TestAppContext};+ use super::*;+ use gpui::TestAppContext;+ use indoc::indoc;use language::Buffer;+ use serde_json::json;use crate::Diff;+ fn source(patch: &str, changes: serde_json::Value) -> acp_v2::Diff {+ serde_json::from_value(json!({+ "changes": changes,+ "patch": {"format": "git_patch", "text": patch}+ }))+ .expect("diff fixture")+ }++ #[test]+ fn test_patch_file_association() {+ let bare = "@@ -10 +10 @@\n-before\n+after\n";+ let single = json!([{"operation": "modify", "path": "/one"}]);+ let parsed = DiffPatch::parse(&source(bare, single.clone())).expect("unique bare hunk");+ assert_eq!(parsed[0].0, 0);+ assert_eq!(parsed[0].1.new_path.as_deref(), Some("/one"));+ assert!(+ DiffPatch::parse(&source(+ bare,+ json!([+ {"operation": "modify", "path": "/one"},+ {"operation": "modify", "path": "/two"}+ ])+ ))+ .is_err(),+ "bare hunks must not guess a file"+ );+ let unified = "--- /one\n+++ /one\n@@ -10 +10 @@\n-before\n+after\n";+ assert!(DiffPatch::parse(&source(unified, single)).is_ok());+ assert!(+ DiffPatch::parse(&source(+ unified,+ json!([+ {"operation": "modify", "path": "/two"}+ ])+ ))+ .is_err(),+ "mismatched paths must fall back"+ );+ assert!(+ DiffPatch::parse(&source(+ unified,+ json!([+ {"operation": "modify", "path": "/one", "fileType": "binary"}+ ])+ ))+ .is_err(),+ "non-text file must not be rendered as a text diff"+ );+ assert!(+ DiffPatch::parse(&source(+ bare,+ json!([+ {"operation": "add", "path": "/one"}+ ])+ ))+ .is_err(),+ "added file cannot have deleted content"+ );+ let rename = "--- /old\n+++ /new\n@@ -1 +1 @@\n-before\n+after\n";+ assert!(+ DiffPatch::parse(&source(+ rename,+ json!([+ {"operation": "move", "oldPath": "/old", "path": "/new"}+ ])+ ))+ .is_ok()+ );+ }++ #[test]+ fn test_patch_file_association_rejects_ambiguity_and_unknown_types() {+ let patch = "diff --git /one /one\n--- /one\n+++ /one\n@@ -1 +1 @@\n-old\n+new\n";+ assert!(+ DiffPatch::parse(&source(+ patch,+ json!([+ {"operation": "modify", "path": "/one"},+ {"operation": "modify", "path": "/one"}+ ])+ ))+ .is_err(),+ "duplicate declared paths are ambiguous"+ );+ assert!(+ DiffPatch::parse(&source(+ &patch.repeat(2),+ json!([+ {"operation": "modify", "path": "/one"}+ ])+ ))+ .is_err(),+ "repeated patch sections must not replace each other"+ );+ for file_type in ["_future", "directory", "symlink"] {+ assert!(+ DiffPatch::parse(&source(+ patch,+ json!([+ {"operation": "modify", "path": "/one", "fileType": file_type}+ ])+ ))+ .is_err(),+ "{file_type} is not an unspecified file type"+ );+ }+ assert!(+ DiffPatch::parse(&source(+ patch,+ json!([+ {"operation": "_future", "path": "/one"}+ ])+ ))+ .is_err()+ );+ assert!(+ DiffPatch::parse(&source(+ "--- /old\n+++ /new\n@@ -1 +1 @@\n-before\n+after\n",+ json!([{"operation": "copy", "oldPath": "/old", "path": "/new"}])+ ))+ .is_ok()+ );+ }++ #[test]+ fn test_patch_file_association_preserves_declared_order_for_large_patches() {+ let changes = (0..1_000)+ .map(|index| json!({"operation": "modify", "path": format!("/file-{index}")}))+ .collect::<Vec<_>>();+ let patch = (0..1_000)+ .rev()+ .map(|index| format!(+ "diff --git /file-{index} /file-{index}\n--- /file-{index}\n+++ /file-{index}\n@@ -1 +1 @@\n-old\n+new\n"+ ))+ .collect::<String>();+ let parsed = DiffPatch::parse(&source(&patch, json!(changes))).expect("large patch");+ assert_eq!(parsed.len(), 1_000);+ for ((change_index, file), expected) in parsed.iter().zip((0..1_000).rev()) {+ assert_eq!(*change_index, expected);+ assert_eq!(file.new_path.as_ref(), Some(&format!("/file-{expected}")));+ }+ }++ #[gpui::test]+ async fn test_patch_hunks_render_read_only_snippets(cx: &mut TestAppContext) {+ let patch = indoc! {"+ diff --git /one /one+ --- /one+ +++ /one+ @@ -100,2 +100,2 @@+ context+ -before+ +after+ @@ -900 +900 @@+ -old+ +new+ diff --git /deleted /deleted+ --- /deleted+ +++ /dev/null+ @@ -1 +0,0 @@+ -deleted+ diff --git /added /added+ --- /dev/null+ +++ /added+ @@ -0,0 +1 @@+ +added+ "};+ let source = source(+ patch,+ json!([+ {"operation": "modify", "path": "/one"},+ {"operation": "delete", "path": "/deleted"},+ {"operation": "add", "path": "/added"},+ {"operation": "modify", "path": "/image", "fileType": "binary"},+ {"operation": "move", "oldPath": "/old", "path": "/new"}+ ]),+ );+ let render = cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ DiffPatch::new(&source, &languages, cx)+ });+ cx.run_until_parked();+ assert!(render.fallback.is_none());+ assert_eq!(+ render.files.len(),+ 5,+ "patchless files must remain represented"+ );+ assert_eq!(render.files[0].hunks.len(), 2);+ assert_eq!(+ render.files[0].hunks[0].header.as_ref(),+ "@@ -100,2 +100,2 @@"+ );+ assert_eq!(render.files[0].hunks[1].header.as_ref(), "@@ -900 +900 @@");+ assert!(render.files[3].hunks.is_empty());+ assert!(render.files[4].hunks.is_empty());+ cx.update(|cx| {+ for (file_index, expected) in [+ (0, "context\nbefore\nafter\n"),+ (1, "deleted\n"),+ (2, "added\n"),+ ] {+ let buffer = render.files[file_index].hunks[0].buffer.read(cx);+ assert!(buffer.read_only());+ let snapshot = buffer.snapshot(cx);+ assert_eq!(snapshot.text(), expected);+ assert!(snapshot.diff_hunks().next().is_some());+ for source_buffer in buffer.all_buffers() {+ assert_eq!(source_buffer.read(cx).capability(), Capability::ReadOnly);+ }+ }+ assert_eq!(+ render.files[0].hunks[1].buffer.read(cx).snapshot(cx).text(),+ "old\nnew\n",+ "sparse hunks must not synthesize the intervening 798 lines"+ );+ });+ }++ #[gpui::test]+ fn test_patch_fallback_retains_file_rows_and_raw_text(cx: &mut TestAppContext) {+ cx.update(|cx| {+ let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));+ let mut source = source(+ "not a patch\n```",+ json!([+ {"operation": "modify", "path": "/one"}+ ]),+ );+ let render = DiffPatch::new(&source, &languages, cx);+ assert_eq!(render.files.len(), 1);+ assert!(render.files[0].hunks.is_empty());+ let fallback = render.fallback.expect("malformed patch fallback");+ assert!(fallback.read(cx).source().contains("not a patch\n```"));+ source.patch = None;+ let render = DiffPatch::new(&source, &languages, cx);+ assert_eq!(render.files.len(), 1);+ assert!(render.files[0].hunks.is_empty());+ assert!(render.fallback.is_none());+ source.patch = Some(acp_v2::DiffPatch::new("opaque format\n``` nested"));+ source.patch.as_mut().expect("patch").format =+ acp_v2::DiffPatchFormat::Other("_future".into());+ let render = DiffPatch::new(&source, &languages, cx);+ assert!(render.fallback.is_some());+ let content = crate::ToolCallContent::DiffPatch { source, render };+ assert!(+ content+ .to_markdown(cx)+ .contains("opaque format\n``` nested"),+ "export must retain supplied text even when its format is unsupported"+ );+ });+ }+#[gpui::test]async fn test_pending_diff(cx: &mut TestAppContext) {let buffer = cx.new(|cx| Buffer::local("hello!", cx));diff --git a/crates/acp_thread/src/diff/patch.rs b/crates/acp_thread/src/diff/patch.rsnew file mode 100644index 00000000000..915ea2a33c7--- /dev/null+++ b/crates/acp_thread/src/diff/patch.rs@@ -0,0 +1,276 @@+use anyhow::{Context as _, Result, ensure};+use diffy::{Line, Patch};+use util::paths::{PathStyle, is_absolute};++#[derive(Debug, PartialEq, Eq)]+pub(super) struct PatchFile {+ pub(super) old_path: Option<String>,+ pub(super) new_path: Option<String>,+ pub(super) hunks: Vec<PatchHunk>,+}++#[derive(Debug, PartialEq, Eq)]+pub(super) struct PatchHunk {+ pub(super) old_start: u32,+ pub(super) old_count: u32,+ pub(super) new_start: u32,+ pub(super) new_count: u32,+ pub(super) old_text: String,+ pub(super) new_text: String,+}++pub(super) fn parse_patch(text: &str) -> Result<Vec<PatchFile>> {+ ensure!(+ text.starts_with("diff --git ") || text.starts_with("--- ") || text.starts_with("@@ "),+ "expected a Git or unified patch without a commit envelope"+ );+ let boundaries = std::iter::once(0)+ .chain(+ text.match_indices("\ndiff --git ")+ .map(|(offset, _)| offset + 1),+ )+ .chain(std::iter::once(text.len()))+ .collect::<Vec<_>>();+ let mut files = Vec::new();+ for section in boundaries.windows(2) {+ let section = &text[section[0]..section[1]];+ check_coordinate_bounds(section)?;+ let patch = Patch::from_str(section).context("invalid Git patch")?;+ if patch.hunks().is_empty() {+ // File operations, including binary and rename-only changes, come from ACP's+ // structured changes. They do not need to be inferred from Git's preamble.+ continue;+ }+ let (old_path, new_path) = if patch.original().is_none() && patch.modified().is_none() {+ (None, None)+ } else {+ let old_path = patch_path(patch.original(), "a/")?;+ let new_path = patch_path(patch.modified(), "b/")?;+ ensure!(+ old_path.is_some() || new_path.is_some(),+ "both patch paths are /dev/null"+ );+ (old_path, new_path)+ };+ let hunks = patch+ .hunks()+ .iter()+ .map(|hunk| {+ let mut old_text = String::new();+ let mut new_text = String::new();+ for line in hunk.lines() {+ match line {+ Line::Context(text) => {+ old_text.push_str(text);+ new_text.push_str(text);+ }+ Line::Delete(text) => old_text.push_str(text),+ Line::Insert(text) => new_text.push_str(text),+ }+ }+ Ok(PatchHunk {+ old_start: u32::try_from(hunk.old_range().start())?,+ old_count: u32::try_from(hunk.old_range().len())?,+ new_start: u32::try_from(hunk.new_range().start())?,+ new_count: u32::try_from(hunk.new_range().len())?,+ old_text,+ new_text,+ })+ })+ .collect::<Result<_>>()?;+ files.push(PatchFile {+ old_path,+ new_path,+ hunks,+ });+ }+ Ok(files)+}++fn patch_path(path: Option<&str>, prefix: &str) -> Result<Option<String>> {+ let path = path.context("missing patch filename")?;+ if path == "/dev/null" {+ return Ok(None);+ }+ let path = path.strip_prefix(prefix).unwrap_or(path);+ ensure!(+ is_absolute(path, PathStyle::Windows),+ "patch path must be absolute: {path}"+ );+ ensure!(!path.contains('\0'), "patch path contains NUL");+ Ok(Some(path.to_owned()))+}++fn check_coordinate_bounds(section: &str) -> Result<()> {+ // diffy adds usize coordinates while checking hunk ordering. Bound them before+ // parsing so an untrusted header cannot overflow there, even in a debug build.+ for line in section.lines().filter(|line| line.starts_with("@@ ")) {+ for range in line.split_whitespace().skip(1).take(2) {+ let range = range.trim_start_matches(['-', '+']);+ let (start, count) = range.split_once(',').unwrap_or((range, "1"));+ let start = start.parse::<u32>().context("invalid hunk start")?;+ let count = count.parse::<u32>().context("invalid hunk length")?;+ ensure!(start > 0 || count == 0, "nonempty hunk starts at line zero");+ start+ .checked_add(count)+ .context("hunk coordinate overflow")?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use indoc::indoc;++ #[test]+ fn parses_sparse_multi_file_hunks() {+ let files = parse_patch(indoc! {"+ diff --git a//project/one.rs b//project/one.rs+ index abc..def 100644+ --- a//project/one.rs+ +++ b//project/one.rs+ @@ -100,2 +100,3 @@ function+ context+ -old+ +new+ +added+ @@ -900,1 +901,1 @@+ -before+ +after+ diff --git /project/two.rs /project/two.rs+ --- /project/two.rs+ +++ /project/two.rs+ @@ -1 +1 @@+ -old+ +new+ "})+ .expect("multi-file patch");+ assert_eq!(files.len(), 2);+ assert_eq!(files[0].old_path.as_deref(), Some("/project/one.rs"));+ assert_eq!(files[0].hunks[0].old_start, 100);+ assert_eq!(files[0].hunks[0].new_count, 3);+ assert_eq!(files[0].hunks[0].old_text, "context\nold\n");+ assert_eq!(files[0].hunks[0].new_text, "context\nnew\nadded\n");+ assert_eq!(files[0].hunks[1].new_start, 901);+ assert_eq!(files[1].new_path.as_deref(), Some("/project/two.rs"));+ }++ #[test]+ fn parses_add_delete_and_missing_newline() {+ let files = parse_patch(indoc! {r#"+ diff --git a//new b//new+ new file mode 100644+ --- /dev/null+ +++ b//new+ @@ -0,0 +1 @@+ +added+ \ No newline at end of file+ diff --git a//old b//old+ deleted file mode 100644+ --- a//old+ +++ /dev/null+ @@ -1 +0,0 @@+ -deleted+ \ No newline at end of file+ "#})+ .expect("add and delete");+ assert_eq!(files[0].old_path, None);+ assert_eq!(files[0].hunks[0].old_text, "");+ assert_eq!(files[0].hunks[0].new_text, "added");+ assert_eq!(files[1].new_path, None);+ assert_eq!(files[1].hunks[0].old_text, "deleted");+ assert_eq!(files[1].hunks[0].new_text, "");+ }++ #[test]+ fn delegates_quoted_and_spaced_paths_to_diffy() {+ let files = parse_patch(indoc! {r#"+ diff --git "a//project/a\tfile" "b//project/a\tfile"+ --- "a//project/a\tfile"+ +++ "b//project/a\tfile"+ @@ -1 +1 @@+ -old+ +new+ diff --git a//project/a file b//project/a file+ --- a//project/a file+ +++ b//project/a file+ @@ -1 +1 @@+ -old+ +new+ "#})+ .expect("quoted and spaced paths");+ assert_eq!(files[0].old_path.as_deref(), Some("/project/a\tfile"));+ assert_eq!(files[1].old_path.as_deref(), Some("/project/a file"));+ }++ #[test]+ fn leaves_nontext_operations_to_structured_changes() {+ assert!(+ parse_patch(indoc! {"+ diff --git a//old b//new+ similarity index 100%+ rename from /old+ rename to /new+ diff --git a//image b//image+ Binary files a//image and b//image differ+ "})+ .expect("file-level changes")+ .is_empty()+ );+ }++ #[test]+ fn parses_unified_patches_without_git_headers() {+ let files = parse_patch("--- /file\n+++ /file\n@@ -10 +10 @@\n-before\n+after\n")+ .expect("unified patch");+ assert_eq!(files[0].old_path.as_deref(), Some("/file"));+ assert_eq!(files[0].hunks[0].new_text, "after\n");+ let files = parse_patch("@@ -10 +10 @@\n-before\n+after\n").expect("bare hunks");+ assert_eq!(+ (files[0].old_path.as_ref(), files[0].new_path.as_ref()),+ (None, None)+ );+ assert_eq!(files[0].hunks[0].old_start, 10);+ }++ #[test]+ fn preserves_unicode_and_documents_diffy_boundaries() {+ let unified = "--- /été.rs\n+++ /été.rs\n@@ -1 +1 @@\n-été 🦀\n+新しい 🦀\n";+ let files = parse_patch(unified).expect("Unicode patch");+ assert_eq!(files[0].old_path.as_deref(), Some("/été.rs"));+ assert_eq!(files[0].hunks[0].old_text, "été 🦀\n");+ assert_eq!(files[0].hunks[0].new_text, "新しい 🦀\n");+ assert!(+ parse_patch(&unified.repeat(2)).is_err(),+ "multiple files need Git section boundaries"+ );+ assert!(+ parse_patch("diff --git /one /one\nunrecognized preamble\n")+ .expect("diffy skips non-hunk preamble")+ .is_empty(),+ "structured changes, not Git metadata, provide non-text file rows"+ );+ assert!(+ parse_patch("--- /one\n@@ -1 +1 @@\n-old\n+new\n").is_err(),+ "a partial filename pair is not a bare hunk"+ );+ }++ #[test]+ fn rejects_malformed_or_unsupported_text_patches() {+ for patch in [+ "commit abc\ndiff --git /old /new\n",+ "diff --git /old /new\n--- /old\n+++ /new\n@@ -1,2 +1 @@\n-old\n+new\n",+ "diff --git /old /new\n--- /old\n+++ /new\n@@ -2 +2 @@\n-a\n+b\n@@ -1 +1 @@\n-c\n+d\n",+ "diff --git a/relative b/relative\n--- a/relative\n+++ b/relative\n@@ -1 +1 @@\n-a\n+b\n",+ "diff --git /old /new\n--- /old\n+++ /new\n@@ -1 +1 @@\n-a\n+b\ntrailing garbage\n",+ "diff --git /old /new\n--- /old\n+++ /new\n@@ -18446744073709551615 +1 @@\n-a\n+b\n@@ -2 +2 @@\n-c\n+d\n",+ "diff --git /old /new\n--- /old\n+++ /new\n@@ -0 +0 @@\n-a\n+b\n",+ "diff --git /old /new\n--- \"a//\\303\\251\"\n+++ /new\n@@ -1 +1 @@\n-a\n+b\n",+ ] {+ assert!(parse_patch(patch).is_err(), "{patch}");+ }+ }+}diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex f94d36aa4e3..1a961c46790 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -4791,7 +4791,7 @@ mod internal_tests {acp_thread::AgentThreadEntry::ToolCall(tool_call) => Some((tool_call.id.clone(),tool_call.tool_name.clone(),- std::mem::discriminant(&tool_call.status),+ std::mem::discriminant(&tool_call.status()),)),_ => None,})diff --git a/crates/agent_servers/src/e2e_tests.rs b/crates/agent_servers/src/e2e_tests.rsindex 7087e5b539e..e466c03fc3b 100644--- a/crates/agent_servers/src/e2e_tests.rs+++ b/crates/agent_servers/src/e2e_tests.rs@@ -1,5 +1,5 @@use crate::{AgentServer, AgentServerDelegate};-use acp_thread::{AcpThread, AgentThreadEntry, ToolCall, ToolCallStatus};+use acp_thread::{AcpThread, AgentThreadEntry, ToolCallStatus};use agent_client_protocol::schema::v1 as acp;use client::RefreshLlmTokenListener;use futures::{FutureExt, StreamExt, channel::mpsc, select};@@ -133,12 +133,9 @@ whereassert!(thread.entries().iter().any(|entry| {matches!(entry,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::Pending+ AgentThreadEntry::ToolCall(call) if matches!(call.status(), ToolCallStatus::Pending| ToolCallStatus::InProgress- | ToolCallStatus::Completed,- ..- })+ | ToolCallStatus::Completed))}));assert!(@@ -175,10 +172,7 @@ pub async fn test_tool_call_with_permission<T, F>(|entry| {matches!(entry,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::WaitingForConfirmation { .. },- ..- })+ AgentThreadEntry::ToolCall(call) if call.status() == ToolCallStatus::WaitingForConfirmation)},cx,@@ -186,12 +180,7 @@ pub async fn test_tool_call_with_permission<T, F>(.await;let tool_call_id = thread.read_with(cx, |thread, cx| {- let AgentThreadEntry::ToolCall(ToolCall {- id,- label,- status: ToolCallStatus::WaitingForConfirmation { .. },- ..- }) = &thread+ let AgentThreadEntry::ToolCall(tool_call) = &thread.entries().iter().find(|entry| matches!(entry, AgentThreadEntry::ToolCall(_)))@@ -199,11 +188,12 @@ pub async fn test_tool_call_with_permission<T, F>(else {panic!();};+ assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);- let label = label.read(cx).source();+ let label = tool_call.label.read(cx).source();assert!(label.contains("touch"), "Got: {}", label);- id.clone()+ tool_call.id.clone()});thread.update(cx, |thread, cx| {@@ -218,24 +208,16 @@ pub async fn test_tool_call_with_permission<T, F>(assert!(thread.entries().iter().any(|entry| matches!(entry,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::Pending+ AgentThreadEntry::ToolCall(call) if matches!(call.status(), ToolCallStatus::Pending| ToolCallStatus::InProgress- | ToolCallStatus::Completed,- ..- })+ | ToolCallStatus::Completed))));});full_turn.await.unwrap();thread.read_with(cx, |thread, cx| {- let AgentThreadEntry::ToolCall(tool_call @ ToolCall {- status: ToolCallStatus::Pending- | ToolCallStatus::InProgress- | ToolCallStatus::Completed,- ..- }) = thread+ let AgentThreadEntry::ToolCall(tool_call) = thread.entries().iter().find(|entry| matches!(entry, AgentThreadEntry::ToolCall(_)))@@ -243,9 +225,16 @@ pub async fn test_tool_call_with_permission<T, F>(else {panic!();};+ assert!(matches!(+ tool_call.status(),+ ToolCallStatus::Pending | ToolCallStatus::InProgress | ToolCallStatus::Completed+ ));assert!(- tool_call.content().iter().any(|content| content.to_markdown(cx).contains("Hello")),+ tool_call+ .content()+ .iter()+ .any(|content| content.to_markdown(cx).contains("Hello")),"Expected content to contain 'Hello'");});@@ -272,10 +261,7 @@ where|entry| {matches!(entry,- AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::WaitingForConfirmation { .. },- ..- })+ AgentThreadEntry::ToolCall(call) if call.status() == ToolCallStatus::WaitingForConfirmation)},cx,@@ -283,31 +269,23 @@ where.await;thread.read_with(cx, |thread, cx| {- let AgentThreadEntry::ToolCall(ToolCall {- id,- label,- status: ToolCallStatus::WaitingForConfirmation { .. },- ..- }) = &thread.entries()[first_tool_call_ix]- else {+ let AgentThreadEntry::ToolCall(tool_call) = &thread.entries()[first_tool_call_ix] else {panic!("{:?}", thread.entries()[1]);};+ assert_eq!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);- let label = label.read(cx).source();+ let label = tool_call.label.read(cx).source();assert!(label.contains("touch"), "Got: {}", label);- id.clone()+ tool_call.id.clone()});thread.update(cx, |thread, cx| thread.cancel(cx)).await;thread.read_with(cx, |thread, _cx| {- let AgentThreadEntry::ToolCall(ToolCall {- status: ToolCallStatus::Canceled,- ..- }) = &thread.entries()[first_tool_call_ix]- else {+ let AgentThreadEntry::ToolCall(tool_call) = &thread.entries()[first_tool_call_ix] else {panic!();};+ assert_eq!(tool_call.status(), ToolCallStatus::Canceled);});threaddiff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex a6c078b7939..71fc45eb0fc 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -297,10 +297,7 @@ impl Conversation {let session_id = thread_state.session_id().clone();for entry in thread_state.entries() {if let AgentThreadEntry::ToolCall(tool_call) = entry- && matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation { .. }- )+ && matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation){self.add_permission_request(&session_id, &tool_call.id);}@@ -384,10 +381,10 @@ impl Conversation {) -> Option<&'a PermissionOptions> {let thread = self.threads.get(session_id)?;let (_, tool_call) = thread.read(cx).tool_call(&tool_call_id)?;- let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {+ if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {return None;- };- Some(options)+ }+ Some(&tool_call.authorization()?.options)}pub fn pending_tool_call<'a>(@@ -408,10 +405,14 @@ impl Conversation {};let (_, tool_call) = thread.read(cx).tool_call(tool_id)?;- let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status else {+ if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {return None;- };- Some((result_session_id, tool_id.clone(), options))+ }+ Some((+ result_session_id,+ tool_id.clone(),+ &tool_call.authorization()?.options,+ ))}pub fn subagents_awaiting_permission(&self, cx: &App) -> Vec<(acp_v1::SessionId, usize)> {@@ -439,10 +440,7 @@ impl Conversation {let thread = self.threads.get(session_id)?;let tool_call_id = self.permission_requests.get(session_id)?.iter().next()?;let (_, tool_call) = thread.read(cx).tool_call(tool_call_id)?;- if !matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation { .. }- ) {+ if !matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation) {return None;}Some(tool_call_id.clone())@@ -8414,6 +8412,572 @@ pub(crate) mod tests {}}+ #[gpui::test]+ async fn test_new_patch_hunk_auto_expands_only_on_creation(cx: &mut TestAppContext) {+ use agent_client_protocol::schema::v2 as acp_v2;++ init_test(cx);+ cx.update(|cx| {+ AgentSettings::override_global(+ AgentSettings {+ expand_edit_card: true,+ ..AgentSettings::get_global(cx).clone()+ },+ cx,+ );+ });+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::default_response(), cx).await;+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let tool_call_id = acp_v1::ToolCallId::new("new-patch");++ let patch: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "new-patch",+ "title": "Edit file",+ "kind": "edit",+ "content": [{+ "type": "diff",+ "changes": [{"operation": "modify", "path": "/tmp/new-patch"}],+ "patch": {+ "format": "git_patch",+ "text": "diff --git a//tmp/new-patch b//tmp/new-patch\n--- a//tmp/new-patch\n+++ b//tmp/new-patch\n@@ -1 +1 @@\n-old patch\n+new patch\n"+ }+ }]+ }))+ .expect("new patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))+ .expect("new patch should apply");+ cx.run_until_parked();++ let (entry_index, hunk_buffer) = thread.read_with(cx, |thread, _| {+ let (entry_index, call) = thread.tool_call(&tool_call_id).expect("new tool exists");+ let [acp_thread::ToolCallContent::DiffPatch { render, .. }] = call.content() else {+ panic!("expected patch content");+ };+ (entry_index, render.files[0].hunks[0].buffer.clone())+ });+ let original_editor = thread_view.read_with(cx, |view, cx| {+ let state = view.entry_view_state.read(cx);+ assert!(state.is_tool_call_expanded(&tool_call_id));+ assert!(+ state.is_tool_call_content_visible(+ thread+ .read(cx)+ .tool_call(&tool_call_id)+ .expect("tool exists")+ .1+ )+ );+ state+ .entry(entry_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .expect("hunk editor should be renderable")+ });++ thread_view.update(cx, |view, cx| {+ view.entry_view_state.update(cx, |state, _| {+ state.collapse_tool_call(&tool_call_id);+ });+ });+ let metadata: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "new-patch",+ "title": "Renamed edit"+ }))+ .expect("metadata patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(metadata, cx))+ .expect("metadata patch should apply");+ cx.run_until_parked();+ thread_view.read_with(cx, |view, cx| {+ let state = view.entry_view_state.read(cx);+ assert!(!state.is_tool_call_expanded(&tool_call_id));+ assert_eq!(+ state+ .entry(entry_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer)),+ Some(original_editor),+ );+ });+ }++ #[gpui::test]+ async fn test_awaiting_authorization_searches_visible_patch_content(cx: &mut TestAppContext) {+ use agent_client_protocol::schema::v2 as acp_v2;++ init_test(cx);+ cx.update(|cx| {+ AgentSettings::override_global(+ AgentSettings {+ expand_edit_card: false,+ ..AgentSettings::get_global(cx).clone()+ },+ cx,+ );+ });+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::default_response(), cx).await;+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let tool_call_id = acp_v1::ToolCallId::new("authorization-patch");+ let patch: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "authorization-patch",+ "title": "Review patch",+ "content": [+ {+ "type": "diff",+ "changes": [{"operation": "modify", "path": "/tmp/review"}],+ "patch": {+ "format": "git_patch",+ "text": "diff --git a//tmp/review b//tmp/review\n--- a//tmp/review\n+++ b//tmp/review\n@@ -1 +1 @@\n-review deleted\n+review added\n"+ }+ },+ {"type": "content", "content": {"type": "text", "text": "Review markdown"}}+ ]+ }))+ .expect("patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))+ .expect("patch should apply");+ cx.run_until_parked();+ let _authorization = thread+ .update(cx, |thread, cx| {+ thread.request_tool_call_authorization(+ acp_v1::ToolCallUpdate::new(+ tool_call_id.clone(),+ acp_v1::ToolCallUpdateFields::new(),+ ),+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(+ "allow-review",+ "Allow",+ acp_v1::PermissionOptionKind::AllowOnce,+ )]),+ acp_thread::AuthorizationKind::PermissionGrant,+ cx,+ )+ })+ .expect("authorization should preserve the existing patch");+ cx.run_until_parked();++ let (entry_index, hunk_buffer) = thread.read_with(cx, |thread, _| {+ let (entry_index, call) = thread.tool_call(&tool_call_id).expect("tool exists");+ assert!(call.authorization().is_some());+ let [acp_thread::ToolCallContent::DiffPatch { render, .. }, ..] = call.content() else {+ panic!("expected patch content");+ };+ (entry_index, render.files[0].hunks[0].buffer.clone())+ });+ thread_view.read_with(cx, |view, cx| {+ let state = view.entry_view_state.read(cx);+ assert!(!state.is_tool_call_expanded(&tool_call_id));+ assert!(+ state.is_tool_call_content_visible(+ thread+ .read(cx)+ .tool_call(&tool_call_id)+ .expect("tool exists")+ .1+ )+ );+ assert!(+ state+ .entry(entry_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .is_some()+ );+ });++ thread_view.update_in(cx, |view, window, cx| {+ view.toggle_search(&crate::ToggleSearch, window, cx);+ });+ let search_bar = thread_view+ .read_with(cx, |view, _| view.thread_search_bar.clone())+ .expect("search should be open");+ for query in ["review deleted", "review added", "Review markdown"] {+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text(query, window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(+ search_bar.read_with(cx, |bar, _| bar.match_count()),+ 1,+ "{query}"+ );+ }+ assert!(+ search_bar.read_with(cx, |bar, _| bar+ .is_patch_buffer_subscribed(hunk_buffer.entity_id())),+ "visible patch buffer should remain subscribed while awaiting authorization"+ );+ }++ #[gpui::test]+ async fn test_thread_search_tracks_shared_tool_patch_content_and_raw_fallback(+ cx: &mut TestAppContext,+ ) {+ use agent_client_protocol::schema::v2 as acp_v2;++ init_test(cx);+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(StubAgentConnection::new()), cx).await;+ let thread_view = active_thread(&conversation_view, cx);+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());+ let tool_call_id = acp_v1::ToolCallId::new("shared-search-tool");++ let patch: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "shared-search-tool",+ "title": "Inspect output",+ "status": "completed",+ "content": [{+ "type": "content",+ "content": {"type": "text", "text": "Structured papaya output"}+ }],+ "rawOutput": "Raw mango output"+ }))+ .expect("initial tool patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))+ .expect("initial tool patch should apply");+ cx.run_until_parked();++ let original_index = thread.read_with(cx, |thread, _| {+ let (index, call) = thread+ .tool_call(&tool_call_id)+ .expect("tool call should exist");+ assert_eq!(call.content().len(), 1);+ index+ });++ thread_view.update_in(cx, |view, window, cx| {+ view.toggle_search(&crate::ToggleSearch, window, cx);+ });+ let search_bar = thread_view+ .read_with(cx, |view, _| view.thread_search_bar.clone())+ .expect("thread search should be open");+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("papaya", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 0);++ thread_view.update(cx, |view, cx| {+ view.entry_view_state.update(cx, |state, _| {+ state.expand_tool_call(tool_call_id.clone());+ });+ });+ search_bar.update_in(cx, |bar, window, cx| bar.update_matches(window, cx));+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 1);++ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("mango", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(+ search_bar.read_with(cx, |bar, _| bar.match_count()),+ 0,+ "structured content should hide the raw fallback",+ );++ let patch: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "shared-search-tool",+ "content": [{+ "type": "diff",+ "changes": [{"operation": "modify", "path": "/tmp/output"}],+ "patch": {+ "format": "git_patch",+ "text": "diff --git a//tmp/output b//tmp/output\n--- a//tmp/output\n+++ b//tmp/output\n@@ -1 +1 @@\n-old output\n+durian patch\n"+ }+ }]+ }))+ .expect("diff patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))+ .expect("diff patch should apply");+ cx.run_until_parked();+ cx.executor()+ .advance_clock(super::thread_search_bar::SEARCH_UPDATE_DEBOUNCE * 2);+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 0);++ thread.read_with(cx, |thread, _| {+ let (index, call) = thread+ .tool_call(&tool_call_id)+ .expect("tool call should exist");+ assert_eq!(+ index, original_index,+ "patches must reuse the existing tool row"+ );+ assert!(matches!(+ call.content(),+ [acp_thread::ToolCallContent::DiffPatch { source, .. }]+ if source+ .patch+ .as_ref()+ .is_some_and(|patch| patch.text.contains("durian patch"))+ ));+ });+ let hunk_buffer = thread_view.read_with(cx, |view, cx| {+ let (_, call) = thread+ .read(cx)+ .tool_call(&tool_call_id)+ .expect("tool exists");+ let [acp_thread::ToolCallContent::DiffPatch { render, .. }] = call.content() else {+ panic!("expected a structured patch");+ };+ assert_eq!(render.files.len(), 1);+ assert_eq!(render.files[0].hunks.len(), 1);+ let hunk = &render.files[0].hunks[0];+ assert_eq!(hunk.header.to_string(), "@@ -1 +1 @@");+ let editor = view+ .entry_view_state+ .read(cx)+ .entry(original_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk.buffer))+ .expect("patch hunk editor");+ assert!(editor.read(cx).read_only(cx));+ assert!(+ editor+ .read(cx)+ .buffer()+ .read(cx)+ .snapshot(cx)+ .text()+ .contains("durian patch")+ );+ assert!(+ editor+ .read(cx)+ .buffer()+ .read(cx)+ .snapshot(cx)+ .text()+ .contains("old output"),+ "expanded patch text must include deleted lines",+ );+ assert!(+ editor+ .read(cx)+ .buffer()+ .read(cx)+ .snapshot(cx)+ .diff_hunks()+ .next()+ .is_some(),+ "patch hunk should render as an inline diff",+ );+ hunk.buffer.clone()+ });+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("durian patch", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 1);++ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("old output", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 1);+ search_bar.update_in(cx, |bar, window, cx| {+ bar.select_next_match(&super::thread_search_bar::SelectNextThreadMatch, window, cx);+ });+ let selected_text = thread_view.update(cx, |view, cx| {+ let editor = view+ .entry_view_state+ .read(cx)+ .entry(original_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .expect("patch hunk editor");+ editor.update(cx, |editor, cx| {+ let selection = editor.selections.newest_anchor().range();+ editor+ .buffer()+ .read(cx)+ .snapshot(cx)+ .text_for_range(selection)+ .collect::<String>()+ })+ });+ assert_eq!(selected_text, "old output");++ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("durian patch", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ search_bar.update_in(cx, |bar, window, cx| {+ bar.select_next_match(&super::thread_search_bar::SelectNextThreadMatch, window, cx);+ });+ let selected_text = thread_view.update(cx, |view, cx| {+ let editor = view+ .entry_view_state+ .read(cx)+ .entry(original_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .expect("patch hunk editor");+ editor.update(cx, |editor, cx| {+ let selection = editor.selections.newest_anchor().range();+ editor+ .buffer()+ .read(cx)+ .snapshot(cx)+ .text_for_range(selection)+ .collect::<String>()+ })+ });+ assert_eq!(selected_text, "durian patch");++ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("late deleted", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 0);++ let (delayed_diff, finish_diff) = cx.update(|_, cx| {+ let mut source_buffer = None;+ hunk_buffer+ .read(cx)+ .for_each_buffer(&mut |buffer| source_buffer = Some(buffer.clone()));+ let source_buffer = source_buffer.expect("patch hunk source buffer");+ let snapshot = source_buffer.read(cx).snapshot();+ let delayed_diff = cx.new(|cx| BufferDiff::new(&snapshot, None, None, cx));+ let finish_diff = delayed_diff.update(cx, |diff, cx| {+ diff.set_base_text(Some(Arc::from("late deleted\n")), snapshot.text, cx)+ });+ (delayed_diff, finish_diff)+ });+ finish_diff.await;+ cx.update(|_, cx| {+ hunk_buffer.update(cx, |buffer, cx| {+ buffer.add_diff(delayed_diff, cx);+ buffer.set_all_diff_hunks_expanded(cx);+ });+ });+ cx.run_until_parked();+ assert_eq!(+ search_bar.read_with(cx, |bar, _| bar.match_count()),+ 0,+ "the active query should await the patch buffer's debounced refresh",+ );+ cx.executor()+ .advance_clock(super::thread_search_bar::SEARCH_UPDATE_DEBOUNCE * 2);+ cx.run_until_parked();+ let expected_start = cx.read(|cx| {+ hunk_buffer+ .read(cx)+ .snapshot(cx)+ .text()+ .find("late deleted")+ .expect("deleted text should appear in the expanded diff")+ });+ assert_eq!(+ search_bar.read_with(cx, |bar, _| bar.match_source_ranges()),+ vec![expected_start..expected_start + "late deleted".len()],+ );+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("durian patch", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ let expected_start = cx.read(|cx| {+ hunk_buffer+ .read(cx)+ .snapshot(cx)+ .text()+ .find("durian patch")+ .expect("new text should follow the deleted diff rows")+ });+ assert_eq!(+ search_bar.read_with(cx, |bar, _| bar.match_source_ranges()),+ vec![expected_start..expected_start + "durian patch".len()],+ );+ thread_view.read_with(cx, |view, cx| {+ let editor = view+ .entry_view_state+ .read(cx)+ .entry(original_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .expect("patch hunk editor should still be displayed");+ assert!(editor.read(cx).read_only(cx));+ });++ let patch: acp_v2::ToolCallUpdate = serde_json::from_value(json!({+ "toolCallId": "shared-search-tool",+ "content": null+ }))+ .expect("clear patch should deserialize");+ thread+ .update(cx, |thread, cx| thread.upsert_tool_call_patch(patch, cx))+ .expect("clear patch should apply");+ cx.run_until_parked();+ cx.executor()+ .advance_clock(super::thread_search_bar::SEARCH_UPDATE_DEBOUNCE * 2);+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 0);+ thread_view.read_with(cx, |view, cx| {+ assert!(+ view.entry_view_state+ .read(cx)+ .entry(original_index)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk_buffer))+ .is_none(),+ "clearing a patch must discard its hunk editor",+ );+ });+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("durian patch", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 0);++ thread.read_with(cx, |thread, _| {+ let (index, call) = thread+ .tool_call(&tool_call_id)+ .expect("tool call should exist");+ assert_eq!(index, original_index);+ assert_eq!(+ call.content().len(),+ 1,+ "clearing content restores raw output"+ );+ });+ search_bar.update_in(cx, |bar, window, cx| {+ bar.query_editor.update(cx, |editor, cx| {+ editor.set_text("mango", window, cx);+ });+ bar.update_matches(window, cx);+ });+ cx.run_until_parked();+ assert_eq!(search_bar.read_with(cx, |bar, _| bar.match_count()), 1);+ }+#[gpui::test]async fn test_thread_search_scrolls_to_later_user_message_match(cx: &mut TestAppContext) {init_test(cx);@@ -10933,17 +11497,16 @@ pub(crate) mod tests {// Verify it's waiting for confirmationassert!(matches!(- tool_call.status,- acp_thread::ToolCallStatus::WaitingForConfirmation { .. }+ tool_call.status(),+ acp_thread::ToolCallStatus::WaitingForConfirmation),"Expected WaitingForConfirmation status, got {:?}",- tool_call.status+ tool_call.status());// Verify the options count (granularity options only, no separate Deny option)- if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =- &tool_call.status- {+ if let Some(authorization) = tool_call.authorization() {+ let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");};@@ -11040,9 +11603,8 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =- &tool_call.status- {+ if let Some(authorization) = tool_call.authorization() {+ let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");};@@ -11130,9 +11692,8 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =- &tool_call.status- {+ if let Some(authorization) = tool_call.authorization() {+ let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");};@@ -11224,9 +11785,8 @@ pub(crate) mod tests {assert!(tool_call.is_some(), "Expected a tool call entry");let tool_call = tool_call.unwrap();- if let acp_thread::ToolCallStatus::WaitingForConfirmation { options, .. } =- &tool_call.status- {+ if let Some(authorization) = tool_call.authorization() {+ let options = &authorization.options;let PermissionOptions::Dropdown(choices) = options else {panic!("Expected dropdown permission options");};diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rsindex 437c3babb2f..18116053ca1 100644--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs@@ -15,7 +15,7 @@ use gpui::{TextStyle, WeakEntity, actions, prelude::*,};use markdown::Markdown;-use multi_buffer::{Anchor, MultiBufferOffset, MultiBufferSnapshot};+use multi_buffer::{Anchor, Event as MultiBufferEvent, MultiBufferOffset, MultiBufferSnapshot};use project::search::SearchQuery;use search::{SearchOption, SearchOptions, SearchSource};use settings::Settings as _;@@ -144,6 +144,7 @@ pub struct ThreadSearchBar {_update_matches_task: Option<Task<()>>,_search_task: Option<Task<()>>,_subscriptions: Vec<Subscription>,+ patch_buffer_subscriptions: HashMap<EntityId, Subscription>,}pub enum ThreadSearchBarEvent {@@ -221,6 +222,7 @@ impl ThreadSearchBar {_update_matches_task: None,_search_task: None,_subscriptions: vec![editor_subscription, thread_subscription],+ patch_buffer_subscriptions: HashMap::default(),}}@@ -251,6 +253,19 @@ impl ThreadSearchBar {self.matches.len()}+ #[cfg(test)]+ pub(super) fn is_patch_buffer_subscribed(&self, buffer_id: EntityId) -> bool {+ self.patch_buffer_subscriptions.contains_key(&buffer_id)+ }++ #[cfg(test)]+ pub(super) fn match_source_ranges(&self) -> Vec<Range<usize>> {+ self.matches+ .iter()+ .map(|thread_match| thread_match.source_range.clone())+ .collect()+ }+#[cfg(test)]pub(super) fn active_match_index(&self) -> Option<usize> {self.active_match@@ -318,12 +333,14 @@ impl ThreadSearchBar {self.query_error_message = err_msg;let Some(query) = query else {+ self.patch_buffer_subscriptions.clear();self.clear_results(cx);cx.notify();return;};let mut targets: Vec<SearchTarget> = Vec::new();+ let mut patch_buffers = Vec::new();let thread = self.thread.read(cx);let entry_view_state = self.entry_view_state.read(cx);for (entry_ix, entry) in thread.entries().iter().enumerate() {@@ -353,10 +370,56 @@ impl ThreadSearchBar {source,});}+ if let AgentThreadEntry::ToolCall(tool_call) = entry+ && entry_view_state.is_tool_call_content_visible(tool_call)+ {+ for content in tool_call.content() {+ if let ToolCallContent::DiffPatch { render, .. } = content {+ for hunk in render.files.iter().flat_map(|file| &file.hunks) {+ if let Some(editor) = entry_view_state+ .entry(entry_ix)+ .and_then(|entry| entry.editor_for_patch_hunk(&hunk.buffer))+ {+ patch_buffers.push(hunk.buffer.clone());+ let snapshot =+ editor.read(cx).buffer().read(cx).snapshot(cx);+ targets.push(SearchTarget::Editor {+ entry_ix,+ editor,+ snapshot,+ });+ }+ }+ }+ }+ }}}}+ let mut previous_subscriptions = std::mem::take(&mut self.patch_buffer_subscriptions);+ for buffer in patch_buffers {+ let id = buffer.entity_id();+ self.patch_buffer_subscriptions+ .entry(id)+ .or_insert_with(|| {+ previous_subscriptions.remove(&id).unwrap_or_else(|| {+ cx.subscribe_in(+ &buffer,+ window,+ |this, _, event: &MultiBufferEvent, window, cx| {+ if this.is_active+ && matches!(event, MultiBufferEvent::Edited { .. })+ {+ this.schedule_update_matches(window, cx);+ }+ },+ )+ })+ });+ }+ drop(previous_subscriptions);+if targets.is_empty() {self.clear_results(cx);cx.notify();@@ -640,6 +703,7 @@ impl ThreadSearchBar {fn clear_highlights_impl(&mut self, cx: &mut App) {self.clear_results(cx);+ self.patch_buffer_subscriptions.clear();self.is_active = false;self._update_matches_task = None;}@@ -906,15 +970,12 @@ fn collect_markdowns(}AgentThreadEntry::ToolCall(tool_call) => {out.push(tool_call.label.clone());- if entry_view_state.is_tool_call_expanded(&tool_call.id) {+ if entry_view_state.is_tool_call_content_visible(tool_call) {out.extend(tool_call.content().iter()- .filter_map(|content| match content {- ToolCallContent::ContentBlock(content) => content.markdown().cloned(),- ToolCallContent::Diff(_) | ToolCallContent::Terminal(_) => None,- }),+ .filter_map(|content| content.markdown().cloned()),);}}diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex da1fcf9a658..ad3870abd41 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -2855,9 +2855,8 @@ impl ThreadView {.find_map(|entry| {if let AgentThreadEntry::ToolCall(call) = entry {if call.id == tool_call_id {- if let ToolCallStatus::WaitingForConfirmation { options, .. } =- &call.status- {+ if let Some(authorization) = call.authorization() {+ let options = &authorization.options;if let PermissionOptions::DropdownWithPatterns {patterns,..@@ -4219,7 +4218,7 @@ impl ThreadView {.tool_call_for_subagent(&my_session_id).is_some_and(|tc| {matches!(- tc.status,+ tc.status(),ToolCallStatus::Canceled| ToolCallStatus::Failed| ToolCallStatus::Rejected@@ -6383,11 +6382,24 @@ impl ThreadView {// A canceled tool call that produced visible output is still worth// showing, but one that was canceled before producing anything just// renders as a useless "Canceled" card — hide those entirely.- if matches!(tool_call.status, ToolCallStatus::Canceled) {+ if matches!(tool_call.status(), ToolCallStatus::Canceled) {let has_visible_content =tool_call.content().iter().any(|content| match content {- ToolCallContent::ContentBlock(block) => block.visible_content(cx),- ToolCallContent::Diff(_) | ToolCallContent::Terminal(_) => true,+ ToolCallContent::ContentBlock { block, .. } => {+ block.visible_content(cx)+ }+ ToolCallContent::Diff(_)+ | ToolCallContent::LegacyDiff { .. }+ | ToolCallContent::Terminal { .. } => true,+ ToolCallContent::DiffPatch { render, .. } => {+ !render.files.is_empty()+ || render.fallback.as_ref().is_some_and(|markdown| {+ !markdown.read(cx).source().is_empty()+ })+ }+ ToolCallContent::Other { markdown, .. } => {+ !markdown.read(cx).source().is_empty()+ }});if !has_visible_content {return Empty.into_any();@@ -7740,11 +7752,11 @@ impl ThreadView {AgentThreadEntry::UserMessage(_) => break,AgentThreadEntry::ToolCall(tool_call)if matches!(- tool_call.status,+ tool_call.status(),ToolCallStatus::InProgress | ToolCallStatus::Pending) =>{- if matches!(tool_call.kind, acp_v1::ToolKind::Execute) {+ if matches!(tool_call.kind(), acp_v2::ToolKind::Execute) {has_running_terminal_call = true;} else {return false;@@ -7843,20 +7855,19 @@ impl ThreadView {let started_at = terminal_data.started_at();let tool_failed = matches!(- &tool_call.status,+ tool_call.status(),ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed);- let confirmation_options = match &tool_call.status {- ToolCallStatus::WaitingForConfirmation { options, .. } => Some(options),- _ => None,- };+ let confirmation_options = tool_call+ .authorization()+ .map(|authorization| &authorization.options);let needs_confirmation = confirmation_options.is_some();let output = terminal_data.output();let command_finished = output.is_some()&& !matches!(- tool_call.status,+ tool_call.status(),ToolCallStatus::InProgress | ToolCallStatus::Pending);let truncated_output =@@ -8181,21 +8192,23 @@ impl ThreadView {let has_location = tool_call.locations.len() == 1;let card_header_id = SharedString::from(format!("inner-tool-call-header-{entry_ix}"));- let failed_or_canceled = match &tool_call.status {+ let failed_or_canceled = match tool_call.status() {ToolCallStatus::Rejected | ToolCallStatus::Canceled | ToolCallStatus::Failed => true,_ => false,};- let needs_confirmation = matches!(- tool_call.status,- ToolCallStatus::WaitingForConfirmation { .. }- );- let is_terminal_tool = matches!(tool_call.kind, acp_v1::ToolKind::Execute);+ let needs_confirmation =+ matches!(tool_call.status(), ToolCallStatus::WaitingForConfirmation);+ let is_terminal_tool = matches!(tool_call.kind(), acp_v2::ToolKind::Execute);- let is_edit =- matches!(tool_call.kind, acp_v1::ToolKind::Edit) || tool_call.diffs().next().is_some();+ let is_edit = matches!(tool_call.kind(), acp_v2::ToolKind::Edit)+ || tool_call.diffs().next().is_some()+ || tool_call+ .content()+ .iter()+ .any(|content| matches!(content, ToolCallContent::DiffPatch { .. }));- let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);+ 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.diffs().next()@@ -8222,12 +8235,10 @@ impl ThreadView {|| (should_show_raw_input && tool_call.raw_input.is_some());let is_collapsible = has_content && !needs_confirmation;- let mut is_open = self+ let is_open = self.entry_view_state.read(cx)- .is_tool_call_expanded(&tool_call.id);-- is_open |= needs_confirmation;+ .is_tool_call_content_visible(tool_call);let input_output_header = |label: SharedString| {Label::new(label)@@ -8237,8 +8248,8 @@ impl ThreadView {};let tool_output_display = if is_open {- match &tool_call.status {- ToolCallStatus::WaitingForConfirmation { .. } => {+ match tool_call.status() {+ ToolCallStatus::WaitingForConfirmation => {let confirmation_content = v_flex().w_full().children(tool_call.content().iter().enumerate().map(@@ -8446,21 +8457,21 @@ impl ThreadView {None};- let permission_buttons =- if let ToolCallStatus::WaitingForConfirmation { options, .. } = &tool_call.status {- Some(self.render_permission_buttons(- self.thread.read(cx).session_id().clone(),- self.is_first_tool_call(active_session_id, &tool_call.id, cx),- options,- entry_ix,- tool_call.id.clone(),- focus_handle,- self.sandbox_confusables_block_allow(tool_call, cx),- cx,- ))- } else {- None- };+ let permission_buttons = if let Some(authorization) = tool_call.authorization() {+ let options = &authorization.options;+ Some(self.render_permission_buttons(+ self.thread.read(cx).session_id().clone(),+ self.is_first_tool_call(active_session_id, &tool_call.id, cx),+ options,+ entry_ix,+ tool_call.id.clone(),+ focus_handle,+ self.sandbox_confusables_block_allow(tool_call, cx),+ cx,+ ))+ } else {+ None+ };let body = v_flex().map(|this| {@@ -9991,7 +10002,7 @@ impl ThreadView {cx: &Context<Self>,) -> Div {let has_location = tool_call.locations.len() == 1;- let is_file = tool_call.kind == acp_v1::ToolKind::Edit && has_location;+ let is_file = matches!(tool_call.kind(), acp_v2::ToolKind::Edit) && has_location;let is_subagent_tool_call = tool_call.is_subagent();let file_icon = if has_location {@@ -10029,17 +10040,17 @@ impl ThreadView {.color(Color::Muted).into_any_element()} else {- Icon::new(match tool_call.kind {- acp_v1::ToolKind::Read => IconName::ToolSearch,- acp_v1::ToolKind::Edit => IconName::ToolPencil,- acp_v1::ToolKind::Delete => IconName::ToolDeleteFile,- acp_v1::ToolKind::Move => IconName::ArrowRightLeft,- acp_v1::ToolKind::Search => IconName::ToolSearch,- acp_v1::ToolKind::Execute => IconName::ToolTerminal,- acp_v1::ToolKind::Think => IconName::ToolThink,- acp_v1::ToolKind::Fetch => IconName::ToolWeb,- acp_v1::ToolKind::SwitchMode => IconName::ArrowRightLeft,- acp_v1::ToolKind::Other | _ => IconName::ToolHammer,+ Icon::new(match tool_call.kind() {+ acp_v2::ToolKind::Read => IconName::ToolSearch,+ acp_v2::ToolKind::Edit => IconName::ToolPencil,+ acp_v2::ToolKind::Delete => IconName::ToolDeleteFile,+ acp_v2::ToolKind::Move => IconName::ArrowRightLeft,+ acp_v2::ToolKind::Search => IconName::ToolSearch,+ acp_v2::ToolKind::Execute => IconName::ToolTerminal,+ acp_v2::ToolKind::Think => IconName::ToolThink,+ acp_v2::ToolKind::Fetch => IconName::ToolWeb,+ acp_v2::ToolKind::SwitchMode => IconName::ArrowRightLeft,+ _ => IconName::ToolHammer,}).size(IconSize::Small).color(Color::Muted)@@ -10222,19 +10233,19 @@ impl ThreadView {cx: &Context<Self>,) -> AnyElement {match content {- ToolCallContent::ContentBlock(content) => self.render_output_content_block(+ ToolCallContent::ContentBlock { block, .. } => self.render_output_content_block(entry_ix,context_ix,- content.as_view(),+ block.as_view(),Some(tool_call),card_layout,window,cx,),- ToolCallContent::Diff(diff) => {+ ToolCallContent::Diff(diff) | ToolCallContent::LegacyDiff { diff, .. } => {self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)}- ToolCallContent::Terminal(terminal) => self.render_terminal_tool_call(+ ToolCallContent::Terminal { terminal, .. } => self.render_terminal_tool_call(session_id,entry_ix,terminal,@@ -10244,6 +10255,79 @@ impl ThreadView {window,cx,),+ ToolCallContent::DiffPatch { source, render } => {+ let files = render.files.iter().filter_map(|file| {+ let change = source.changes.get(file.change_index)?;+ Some(+ v_flex()+ .gap_1()+ .p_2()+ .when(context_ix > 0, |this| {+ this.border_t_1()+ .border_color(self.tool_card_border_color(cx))+ })+ .child(+ Label::new(acp_thread::diff_change_label(change))+ .size(LabelSize::XSmall)+ .color(Color::Muted),+ )+ .when(file.hunks.is_empty(), |this| {+ this.child(+ Label::new("No text preview available")+ .size(LabelSize::XSmall)+ .color(Color::Muted),+ )+ })+ .children(file.hunks.iter().map(|hunk| {+ v_flex()+ .child(+ Label::new(hunk.header.clone())+ .size(LabelSize::XSmall)+ .color(Color::Muted),+ )+ .when_some(+ self.entry_view_state.read(cx).entry(entry_ix).and_then(+ |entry| entry.editor_for_patch_hunk(&hunk.buffer),+ ),+ |this, editor| this.child(editor),+ )+ })),+ )+ });+ v_flex()+ .children(files)+ .when(+ render.files.is_empty() && render.fallback.is_none(),+ |this| {+ this.p_2().child(+ Label::new("No text preview available")+ .size(LabelSize::XSmall)+ .color(Color::Muted),+ )+ },+ )+ .when_some(render.fallback.as_ref(), |this, markdown| {+ this.child(self.render_markdown_output(+ markdown.clone(),+ entry_ix,+ context_ix,+ tool_call,+ card_layout,+ window,+ cx,+ ))+ })+ .into_any_element()+ }+ ToolCallContent::Other { markdown, .. } => self.render_markdown_output(+ markdown.clone(),+ entry_ix,+ context_ix,+ tool_call,+ card_layout,+ window,+ cx,+ ),}}@@ -10415,7 +10499,7 @@ impl ThreadView {cx: &Context<Self>,) -> AnyElement {let tool_progress = matches!(- &tool_call.status,+ tool_call.status(),ToolCallStatus::InProgress | ToolCallStatus::Pending);@@ -10631,20 +10715,20 @@ impl ThreadView {let diff_stats = DiffStats::all_files(changed_buffers, cx);let is_running = matches!(- tool_call.status,+ tool_call.status(),ToolCallStatus::Pending| ToolCallStatus::InProgress- | ToolCallStatus::WaitingForConfirmation { .. }+ | ToolCallStatus::WaitingForConfirmation);let is_failed = matches!(- tool_call.status,+ tool_call.status(),ToolCallStatus::Failed | ToolCallStatus::Rejected);- let is_cancelled = matches!(tool_call.status, ToolCallStatus::Canceled)+ let is_cancelled = matches!(tool_call.status(), ToolCallStatus::Canceled)|| tool_call.content().iter().any(|c| match c {- ToolCallContent::ContentBlock(block) => {+ ToolCallContent::ContentBlock { block, .. } => {block.text_content(cx) == Some("User canceled")}_ => false,@@ -10726,7 +10810,7 @@ impl ThreadView {"Click to Preview"};- let error_message = self.subagent_error_message(&tool_call.status, tool_call, cx);+ let error_message = self.subagent_error_message(&tool_call.status(), tool_call, cx);v_flex().w_full()@@ -10971,7 +11055,7 @@ impl ThreadView {let session_id = subagent_view.thread.read(cx).session_id().clone();let is_canceled_or_failed = matches!(- tool_call.status,+ tool_call.status(),ToolCallStatus::Canceled | ToolCallStatus::Failed | ToolCallStatus::Rejected);@@ -11059,7 +11143,7 @@ impl ThreadView {) -> Option<SharedString> {if matches!(status, ToolCallStatus::Failed) {tool_call.content().iter().find_map(|content| {- if let ToolCallContent::ContentBlock(block) = content {+ if let ToolCallContent::ContentBlock { block, .. } = content {if let Some(source) = block.text_content(cx).filter(|source| !source.is_empty()){if source == "User canceled" {diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex c648aa967d9..df5c8bcfeaf 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -1,6 +1,6 @@use std::{ops::Range, sync::Arc};-use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk};+use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk, ToolCall};use agent::ThreadStore;use agent_client_protocol::schema::v1 as acp_v1;use agent_settings::AgentSettings;@@ -14,6 +14,7 @@ use gpui::{Focusable, ScrollHandle, TextStyleRefinement, WeakEntity, Window,};use language::language_settings::SoftWrap;+use multi_buffer::MultiBuffer;use project::{AgentId, Project, project_settings::DiagnosticSeverity};use rope::Point;use settings::{Settings as _, ThinkingBlockDisplay};@@ -77,6 +78,10 @@ impl EntryViewState {self.expanded_tool_calls.contains(tool_call_id)}+ pub(crate) fn is_tool_call_content_visible(&self, tool_call: &ToolCall) -> bool {+ self.is_tool_call_expanded(&tool_call.id) || tool_call.authorization().is_some()+ }+pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp_v1::ToolCallId) {self.expanded_tool_calls.insert(tool_call_id);}@@ -309,6 +314,22 @@ impl EntryViewState {let id = tool_call.id.clone();let terminals = tool_call.terminals().cloned().collect::<Vec<_>>();let diffs = tool_call.diffs().cloned().collect::<Vec<_>>();+ let patch_hunk_buffers = tool_call+ .content()+ .iter()+ .filter_map(|content| match content {+ acp_thread::ToolCallContent::DiffPatch { render, .. } => {+ Some(&render.files)+ }+ _ => None,+ })+ .flat_map(|files| files.iter().flat_map(|file| &file.hunks))+ .map(|hunk| hunk.buffer.clone())+ .collect::<Vec<_>>();+ let patch_hunk_ids: HashSet<_> = patch_hunk_buffers+ .iter()+ .map(|buffer| buffer.entity_id())+ .collect();let views = if let Some(Entry::ToolCall(tool_call)) = self.entries.get_mut(index) {&mut tool_call.content@@ -317,6 +338,7 @@ impl EntryViewState {index,Entry::ToolCall(ToolCallEntry {content: HashMap::default(),+ patch_hunk_ids: HashSet::default(),focus_handle: cx.focus_handle(),}),);@@ -327,7 +349,7 @@ impl EntryViewState {};let is_tool_call_completed =- matches!(tool_call.status, acp_thread::ToolCallStatus::Completed);+ matches!(tool_call.status(), acp_thread::ToolCallStatus::Completed);for terminal in terminals {match views.entry(terminal.entity_id()) {@@ -407,6 +429,22 @@ impl EntryViewState {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()+ });+ }+ 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.patch_hunk_ids = patch_hunk_ids;+ }}AgentThreadEntry::Elicitation(_) => {if !matches!(self.entries.get(index), Some(Entry::Elicitation { .. })) {@@ -555,6 +593,7 @@ impl AssistantMessageEntry {#[derive(Debug)]pub struct ToolCallEntry {content: HashMap<EntityId, AnyEntity>,+ patch_hunk_ids: HashSet<EntityId>,focus_handle: FocusHandle,}@@ -600,6 +639,13 @@ impl Entry {.and_then(|entity| entity.downcast::<Editor>().ok())}+ pub fn editor_for_patch_hunk(&self, buffer: &Entity<MultiBuffer>) -> Option<Entity<Editor>> {+ self.content_map()?+ .get(&buffer.entity_id())+ .cloned()+ .and_then(|entity| entity.downcast::<Editor>().ok())+ }+pub fn terminal(&self,terminal: &Entity<acp_thread::Terminal>,@@ -703,6 +749,14 @@ 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,+ cx: &mut App,) -> Entity<Editor> {cx.new(|cx| {let mut editor = Editor::new(@@ -711,7 +765,7 @@ fn create_editor_diff(show_active_line_background: false,sizing_behavior: SizingBehavior::SizeByContent,},- diff.read(cx).multibuffer().clone(),+ multibuffer,None,window,cx,diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rsindex 1df0194b64a..61844188f9c 100644--- a/crates/eval_cli/src/main.rs+++ b/crates/eval_cli/src/main.rs@@ -974,7 +974,7 @@ fn log_acp_thread_event(let entries = acp_thread.read(cx).entries();if let Some(acp_thread::AgentThreadEntry::ToolCall(tool_call)) = entries.get(*index) {if let Some(name) = &tool_call.tool_name {- match &tool_call.status {+ match tool_call.status() {acp_thread::ToolCallStatus::Completed => {eprintln!("[tool] {name} ✓");}diff --git a/crates/language/Cargo.toml b/crates/language/Cargo.tomlindex 2fbe198048a..bfc9c5ac24e 100644--- a/crates/language/Cargo.toml+++ b/crates/language/Cargo.toml@@ -34,6 +34,7 @@ async-trait.workspace = trueclock.workspace = truechardetng.workspace = truecollections.workspace = true+diffy.workspace = trueec4rs.workspace = trueencoding_rs.workspace = truefs.workspace = true@@ -79,7 +80,6 @@ util.workspace = truewatch.workspace = truezlog.workspace = trueztracing.workspace = true-diffy = "0.4.2"[dev-dependencies]collections = { workspace = true, features = ["test-support"] }