diff --git a/Cargo.toml b/Cargo.toml index 042039709a9..7a48f0ff58f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -520,7 +520,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] } accesskit_macos = "0.26.0" accesskit_unix = "0.22" accesskit_windows = "0.34" -agent-client-protocol = { version = "=2.2.0", features = ["unstable"] } +agent-client-protocol = { version = "=2.2.0", features = ["unstable", "unstable_protocol_v2"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" } any_vec = "0.14" diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index 9409a68d99f..91814582145 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -1,10 +1,11 @@ mod connection; +pub mod content; mod diff; mod mention; mod terminal; pub use ::terminal::HeadlessTerminal; use action_log::{ActionLog, ActionLogTelemetry}; -use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1}; +use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2}; use agent_settings::AgentSettings; use anyhow::{Context as _, Result, anyhow}; use collections::HashSet; @@ -795,9 +796,19 @@ impl ContextCompaction { update: acp_v1::CompactionUpdate, language_registry: &Arc, cx: &mut App, - ) { + ) -> Result<()> { + let summary = match update.summary { + MaybeUndefined::Undefined => MaybeUndefined::Undefined, + MaybeUndefined::Null => MaybeUndefined::Null, + MaybeUndefined::Value(blocks) => MaybeUndefined::Value( + blocks + .into_iter() + .map(content::from_v1) + .collect::>>()?, + ), + }; self.status = update.status.into(); - match update.summary { + match summary { MaybeUndefined::Undefined => {} MaybeUndefined::Null => self.summary.clear(), MaybeUndefined::Value(blocks) => { @@ -818,15 +829,16 @@ impl ContextCompaction { } } } + Ok(()) } fn append_summary( &mut self, - content: acp_v1::ContentBlock, + content: acp_v2::ContentBlock, language_registry: &Arc, cx: &mut App, ) { - if let acp_v1::ContentBlock::Text(text) = &content + if let acp_v2::ContentBlock::Text(text) = &content && let Some(markdown) = self.summary.last().and_then(ContentBlock::plain_markdown) { markdown.update(cx, |markdown, cx| markdown.append(&text.text, cx)); @@ -1487,7 +1499,7 @@ fn elicitation_status_for_response( #[derive(Debug, Default, PartialEq)] pub struct MessageContent { - source_blocks: Vec, + source_blocks: Vec, blocks: Vec, } @@ -1499,7 +1511,7 @@ struct RenderedMessageBlock { impl MessageContent { pub fn new( - block: acp_v1::ContentBlock, + block: acp_v2::ContentBlock, language_registry: &Arc, path_style: PathStyle, cx: &mut App, @@ -1510,7 +1522,7 @@ impl MessageContent { } /// Original content blocks, including text not yet revealed by streaming. - pub fn source_blocks(&self) -> &[acp_v1::ContentBlock] { + pub fn source_blocks(&self) -> &[acp_v2::ContentBlock] { &self.source_blocks } @@ -1551,7 +1563,7 @@ impl MessageContent { pub fn append( &mut self, - block: acp_v1::ContentBlock, + block: acp_v2::ContentBlock, language_registry: &Arc, path_style: PathStyle, cx: &mut App, @@ -1562,14 +1574,14 @@ impl MessageContent { fn append_rendered( &mut self, - block: &acp_v1::ContentBlock, + block: &acp_v2::ContentBlock, language_registry: &Arc, path_style: PathStyle, cx: &mut App, ) { match block { - acp_v1::ContentBlock::Text(text) => self.append_text(&text.text, language_registry, cx), - acp_v1::ContentBlock::ResourceLink(resource) => { + acp_v2::ContentBlock::Text(text) => self.append_text(&text.text, language_registry, cx), + acp_v2::ContentBlock::ResourceLink(resource) => { let mut text = ContentBlock::resource_link_md(&resource.uri, path_style); if self.blocks.is_empty() { // Legacy leading links separated the next chunk. Include that separator @@ -1581,7 +1593,9 @@ impl MessageContent { _ => { let render = ContentBlock::render_from_source(block, language_registry, cx); let source_index = match render { - RenderBlock::EmbeddedResource { .. } => Some(self.source_blocks.len()), + RenderBlock::EmbeddedResource { .. } | RenderBlock::Unsupported { .. } => { + Some(self.source_blocks.len()) + } _ => None, }; self.blocks.push(RenderedMessageBlock { @@ -1608,15 +1622,15 @@ impl MessageContent { } } - fn append_deferred_text(&mut self, text: acp_v1::TextContent) -> usize { + fn append_deferred_text(&mut self, text: acp_v2::TextContent) -> usize { let index = self.source_blocks.len(); - self.source_blocks.push(acp_v1::ContentBlock::Text(text)); + self.source_blocks.push(acp_v2::ContentBlock::Text(text)); index } fn append_prompt( &mut self, - block: acp_v1::ContentBlock, + block: acp_v2::ContentBlock, language_registry: &Arc, path_style: PathStyle, cx: &mut App, @@ -1624,10 +1638,10 @@ impl MessageContent { // Prompt text resources are mentions, not output previews. Keep their text // inline while retaining the original payloads in the source blocks. match &block { - acp_v1::ContentBlock::Resource(resource) + acp_v2::ContentBlock::Resource(resource) if matches!( resource.resource, - acp_v1::EmbeddedResourceResource::TextResourceContents(_) + acp_v2::EmbeddedResourceResource::TextResourceContents(_) ) => { let text = ContentBlock::embedded_resource_string_contents(resource, path_style); @@ -1642,7 +1656,7 @@ impl MessageContent { #[derive(Debug, PartialEq, Clone)] pub struct ContentBlock { render: RenderBlock, - source: Option, + source: Option, } #[derive(Debug, PartialEq, Clone)] @@ -1666,7 +1680,7 @@ enum RenderBlock { #[derive(Clone, Copy)] pub struct ContentBlockView<'a> { render: &'a RenderBlock, - source: Option<&'a acp_v1::ContentBlock>, + source: Option<&'a acp_v2::ContentBlock>, } impl ContentBlock { @@ -1685,17 +1699,17 @@ impl ContentBlock { } #[cfg(test)] - fn unsupported_content(&self) -> Option<&acp_v1::ContentBlock> { + fn unsupported_content(&self) -> Option<&acp_v2::ContentBlock> { self.as_view().unsupported_content() } pub fn new_output( - block: acp_v1::ContentBlock, + block: acp_v2::ContentBlock, language_registry: &Arc, cx: &mut App, ) -> Self { match block { - acp_v1::ContentBlock::Text(text) => { + acp_v2::ContentBlock::Text(text) => { Self::create_markdown_block(text.text, language_registry, cx) } block => { @@ -1712,19 +1726,19 @@ impl ContentBlock { } fn render_from_source( - block: &acp_v1::ContentBlock, + block: &acp_v2::ContentBlock, language_registry: &Arc, cx: &mut App, ) -> RenderBlock { match block { - acp_v1::ContentBlock::Resource(resource) => { + acp_v2::ContentBlock::Resource(resource) => { if let Some((image, dimensions)) = Self::decode_embedded_resource_image(resource) { return RenderBlock::Image { image, dimensions }; } if matches!( &resource.resource, - acp_v1::EmbeddedResourceResource::TextResourceContents(_) - | acp_v1::EmbeddedResourceResource::BlobResourceContents(_) + acp_v2::EmbeddedResourceResource::TextResourceContents(_) + | acp_v2::EmbeddedResourceResource::BlobResourceContents(_) ) { let markdown = Self::embedded_resource_markdown(resource, language_registry, cx); @@ -1733,7 +1747,7 @@ impl ContentBlock { Self::unsupported(block, language_registry, cx) } } - acp_v1::ContentBlock::Image(image) => { + acp_v2::ContentBlock::Image(image) => { if let Some((image, dimensions)) = Self::decode_image(image) { RenderBlock::Image { image, dimensions } } else { @@ -1746,23 +1760,24 @@ impl ContentBlock { } } } - acp_v1::ContentBlock::ResourceLink(_) => RenderBlock::ResourceLink, - acp_v1::ContentBlock::Text(text) => RenderBlock::Markdown { + acp_v2::ContentBlock::ResourceLink(_) => RenderBlock::ResourceLink, + acp_v2::ContentBlock::Text(text) => RenderBlock::Markdown { markdown: Self::create_markdown(text.text.clone(), language_registry, cx), }, + acp_v2::ContentBlock::Other(_) => Self::unsupported(block, language_registry, cx), _ => Self::unsupported(block, language_registry, cx), } } fn unsupported( - content: &acp_v1::ContentBlock, + content: &acp_v2::ContentBlock, language_registry: &Arc, cx: &mut App, ) -> RenderBlock { - let description = if matches!(content, acp_v1::ContentBlock::Audio(_)) { - "Audio content is not supported." - } else { - "This content is not supported." + let description = match content { + acp_v2::ContentBlock::Audio(_) => "Audio content is not supported.", + acp_v2::ContentBlock::Other(_) => "Unknown content type is not supported.", + _ => "This content is not supported.", }; RenderBlock::Unsupported { markdown: Self::create_markdown(description.into(), language_registry, cx), @@ -1777,11 +1792,11 @@ impl ContentBlock { /// /// Recreating the entity on every streamed snapshot causes the rendered /// element to tear down and rebuild, which flickers badly. - pub fn update_text_in_place(&mut self, block: &acp_v1::ContentBlock, cx: &mut App) -> bool { + pub fn update_text_in_place(&mut self, block: &acp_v2::ContentBlock, cx: &mut App) -> bool { let RenderBlock::Markdown { markdown } = &self.render else { return false; }; - let acp_v1::ContentBlock::Text(text_content) = block else { + let acp_v2::ContentBlock::Text(text_content) = block else { return false; }; let new_content = &text_content.text; @@ -1797,19 +1812,19 @@ impl ContentBlock { } fn decode_image( - image_content: &acp_v1::ImageContent, + image_content: &acp_v2::ImageContent, ) -> Option<(Arc, Option>)> { - Self::decode_image_data(&image_content.data, &image_content.mime_type) + Self::decode_image_data(&image_content.data, image_content.mime_type.as_ref()) } fn decode_embedded_resource_image( - resource: &acp_v1::EmbeddedResource, + resource: &acp_v2::EmbeddedResource, ) -> Option<(Arc, Option>)> { - let acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) = &resource.resource + let acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) = &resource.resource else { return None; }; - let mime_type = blob.mime_type.as_deref()?; + let mime_type = blob.mime_type.as_ref()?.as_ref(); Self::decode_image_data(&blob.blob, mime_type) } @@ -1880,21 +1895,21 @@ impl ContentBlock { } fn embedded_resource_markdown( - resource: &acp_v1::EmbeddedResource, + resource: &acp_v2::EmbeddedResource, language_registry: &Arc, cx: &mut App, ) -> Option> { match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => Some( + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => Some( Self::create_markdown(Self::text_resource_markdown(text), language_registry, cx), ), - acp_v1::EmbeddedResourceResource::BlobResourceContents(_) => None, + acp_v2::EmbeddedResourceResource::BlobResourceContents(_) => None, _ => None, } } - fn text_resource_markdown(resource: &acp_v1::TextResourceContents) -> String { - match text_resource_render_mode(resource.mime_type.as_deref()) { + fn text_resource_markdown(resource: &acp_v2::TextResourceContents) -> String { + match text_resource_render_mode(resource.mime_type.as_ref().map(AsRef::as_ref)) { TextResourceRenderMode::Markdown => resource.text.clone(), TextResourceRenderMode::CodeBlock(language) => { Self::fenced_code_block(&resource.text, language) @@ -1940,7 +1955,7 @@ impl ContentBlock { impl<'a> ContentBlockView<'a> { #[cfg(test)] - fn unsupported_content(&self) -> Option<&'a acp_v1::ContentBlock> { + fn unsupported_content(&self) -> Option<&'a acp_v2::ContentBlock> { match self.render { RenderBlock::Unsupported { .. } => self.source, _ => None, @@ -1955,7 +1970,7 @@ impl<'a> ContentBlockView<'a> { RenderBlock::EmbeddedResource { .. } => { self.embedded_resource() .and_then(|(resource, _)| match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => { + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => { Some(text.text.as_str()) } _ => None, @@ -1993,32 +2008,32 @@ impl ContentBlock { } fn embedded_resource_string_contents( - resource: &acp_v1::EmbeddedResource, + resource: &acp_v2::EmbeddedResource, path_style: PathStyle, ) -> String { match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => { + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => { Self::resource_link_md(&text.uri, path_style) } - acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => { + acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => { Self::resource_link_md(&blob.uri, path_style) } _ => String::new(), } } - fn embedded_resource_text(resource: &acp_v1::EmbeddedResource) -> &str { + fn embedded_resource_text(resource: &acp_v2::EmbeddedResource) -> &str { match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => &text.text, - acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri, + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => &text.text, + acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri, _ => "", } } - fn embedded_resource_label(resource: &acp_v1::EmbeddedResource) -> &str { + fn embedded_resource_label(resource: &acp_v2::EmbeddedResource) -> &str { match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => &text.uri, - acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri, + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => &text.uri, + acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri, _ => "", } } @@ -2027,10 +2042,10 @@ impl ContentBlock { impl<'a> ContentBlockView<'a> { pub fn embedded_resource( &self, - ) -> Option<(&'a acp_v1::EmbeddedResource, Option<&'a Entity>)> { + ) -> Option<(&'a acp_v2::EmbeddedResource, Option<&'a Entity>)> { match &self.render { RenderBlock::EmbeddedResource { markdown } => match self.source { - Some(acp_v1::ContentBlock::Resource(resource)) => { + Some(acp_v2::ContentBlock::Resource(resource)) => { Some((resource, markdown.as_ref())) } _ => None, @@ -2071,7 +2086,7 @@ impl<'a> ContentBlockView<'a> { } } RenderBlock::ResourceLink => match self.source { - Some(acp_v1::ContentBlock::ResourceLink(resource_link)) => &resource_link.uri, + Some(acp_v2::ContentBlock::ResourceLink(resource_link)) => &resource_link.uri, _ => "", }, RenderBlock::Image { .. } => "`Image`", @@ -2088,10 +2103,10 @@ impl<'a> ContentBlockView<'a> { } } - pub fn resource_link(&self) -> Option<&'a acp_v1::ResourceLink> { + pub fn resource_link(&self) -> Option<&'a acp_v2::ResourceLink> { match &self.render { RenderBlock::ResourceLink => match self.source { - Some(acp_v1::ContentBlock::ResourceLink(resource_link)) => Some(resource_link), + Some(acp_v2::ContentBlock::ResourceLink(resource_link)) => Some(resource_link), _ => None, }, _ => None, @@ -2176,9 +2191,13 @@ impl ToolCallContent { cx: &mut App, ) -> Result> { match content { - acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => Ok(Some( - Self::ContentBlock(ContentBlock::new_output(content, &language_registry, cx)), - )), + acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => { + Ok(Some(Self::ContentBlock(ContentBlock::new_output( + content::from_v1(content)?, + &language_registry, + cx, + )))) + } acp_v1::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| { Diff::finalized( diff.path.to_string_lossy().into_owned(), @@ -2204,16 +2223,21 @@ impl ToolCallContent { terminals: &HashMap>, cx: &mut App, ) -> Result { - // Update streaming text in place so the rendered markdown element is - // reused across snapshots instead of being recreated (which flickers). - if let ( - Self::ContentBlock(block), - acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }), - ) = (&mut *self, &new) - && block.update_text_in_place(content, cx) - { - return Ok(true); - } + let new = match new { + acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => { + let content = content::from_v1(content)?; + // Keep Markdown identity across text snapshots to avoid flicker. + if let Self::ContentBlock(block) = self + && block.update_text_in_place(&content, cx) + { + return Ok(true); + } + *self = + Self::ContentBlock(ContentBlock::new_output(content, &language_registry, cx)); + return Ok(true); + } + new => new, + }; let needs_update = match (&self, &new) { (Self::Diff(old_diff), acp_v1::ToolCallContent::Diff(new_diff)) => { @@ -2492,11 +2516,11 @@ struct TextCursor { } impl TextCursor { - fn take(&mut self, sources: &[acp_v1::ContentBlock], max_bytes: usize) -> Option { + fn take(&mut self, sources: &[acp_v2::ContentBlock], max_bytes: usize) -> Option { let max_bytes = max_bytes.min(self.pending_bytes); let mut revealed = String::with_capacity(max_bytes); while revealed.len() < max_bytes { - let acp_v1::ContentBlock::Text(text) = sources.get(self.source_index)? else { + let acp_v2::ContentBlock::Text(text) = sources.get(self.source_index)? else { return None; }; let pending = text.text.get(self.byte_offset..)?; @@ -3030,6 +3054,7 @@ impl AcpThread { message_id, .. }) => { + let content = content::from_v1(content).map_err(acp_v1::Error::from)?; // We optimistically add the full user prompt before calling `prompt`. // Some ACP servers echo user chunks back over updates. Skip echoed // chunks only when they match the local optimistic message. @@ -3062,7 +3087,11 @@ impl AcpThread { .. }) => { self.push_assistant_content_block_with_message_id( - message_id, content, false, false, cx, + message_id, + content::from_v1(content).map_err(acp_v1::Error::from)?, + false, + false, + cx, ); } acp_v1::SessionUpdate::AgentThoughtChunk(acp_v1::ContentChunk { @@ -3071,7 +3100,11 @@ impl AcpThread { .. }) => { self.push_assistant_content_block_with_message_id( - message_id, content, true, false, cx, + message_id, + content::from_v1(content).map_err(acp_v1::Error::from)?, + true, + false, + cx, ); } acp_v1::SessionUpdate::ToolCall(tool_call) => { @@ -3081,10 +3114,12 @@ impl AcpThread { self.update_tool_call(tool_call_update, cx)?; } acp_v1::SessionUpdate::CompactionUpdate(compaction_update) => { - self.upsert_context_compaction_update(compaction_update, cx); + self.upsert_context_compaction_update(compaction_update, cx) + .map_err(acp_v1::Error::from)?; } acp_v1::SessionUpdate::CompactionSummaryChunk(summary_chunk) => { - self.append_context_compaction_summary(summary_chunk, cx); + self.append_context_compaction_summary(summary_chunk, cx) + .map_err(acp_v1::Error::from)?; } acp_v1::SessionUpdate::Plan(plan) => { self.update_plan(plan, cx); @@ -3143,7 +3178,7 @@ impl AcpThread { pub fn push_user_content_block( &mut self, client_id: Option, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, cx: &mut Context, ) { self.push_user_content_block_with_indent(client_id, chunk, false, cx) @@ -3152,7 +3187,7 @@ impl AcpThread { pub fn push_user_content_block_with_indent( &mut self, client_id: Option, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, indented: bool, cx: &mut Context, ) { @@ -3169,7 +3204,7 @@ impl AcpThread { fn push_user_content_block_from_agent( &mut self, id: Option, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, cx: &mut Context, ) { self.push_user_content_block_with_protocol_id(None, false, id, chunk, false, cx) @@ -3180,7 +3215,7 @@ impl AcpThread { incoming_client_id: Option, is_optimistic: bool, protocol_id: Option, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, indented: bool, cx: &mut Context, ) { @@ -3234,7 +3269,7 @@ impl AcpThread { pub fn push_assistant_content_block( &mut self, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, is_thought: bool, cx: &mut Context, ) { @@ -3243,7 +3278,7 @@ impl AcpThread { pub fn push_assistant_content_block_with_indent( &mut self, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, is_thought: bool, indented: bool, cx: &mut Context, @@ -3254,7 +3289,7 @@ impl AcpThread { fn push_assistant_content_block_with_message_id( &mut self, message_id: Option, - chunk: acp_v1::ContentBlock, + chunk: acp_v2::ContentBlock, is_thought: bool, indented: bool, cx: &mut Context, @@ -3264,7 +3299,7 @@ impl AcpThread { // For text chunks going to an existing Markdown block, buffer for smooth // streaming instead of appending all at once which may feel more choppy. let chunk = match chunk { - acp_v1::ContentBlock::Text(text) => { + acp_v2::ContentBlock::Text(text) => { if let Some((content, target)) = self.streaming_content_target(message_id.as_ref(), is_thought, indented) { @@ -3274,7 +3309,7 @@ impl AcpThread { self.buffer_streaming_text(target, source_index, text_len, cx); return; } - acp_v1::ContentBlock::Text(text) + acp_v2::ContentBlock::Text(text) } chunk => chunk, }; @@ -3524,7 +3559,7 @@ impl AcpThread { &mut self, update: acp_v1::CompactionUpdate, cx: &mut Context, - ) { + ) -> Result<()> { let id = ContextCompactionId(update.compaction_id.0.clone()); let language_registry = self.project.read(cx).languages().clone(); @@ -3540,9 +3575,9 @@ impl AcpThread { _ => None, }) { - compaction.apply_update(update, &language_registry, cx); + compaction.apply_update(update, &language_registry, cx)?; cx.emit(AcpThreadEvent::EntryUpdated(entry_index)); - return; + return Ok(()); } let mut compaction = ContextCompaction { @@ -3551,15 +3586,16 @@ impl AcpThread { error: None, summary: Vec::new(), }; - compaction.apply_update(update, &language_registry, cx); + compaction.apply_update(update, &language_registry, cx)?; self.push_entry(AgentThreadEntry::ContextCompaction(compaction), cx); + Ok(()) } fn append_context_compaction_summary( &mut self, chunk: acp_v1::CompactionSummaryChunk, cx: &mut Context, - ) { + ) -> Result<()> { let language_registry = self.project.read(cx).languages().clone(); if let Some((entry_index, compaction)) = self.entries @@ -3576,9 +3612,10 @@ impl AcpThread { _ => None, }) { - compaction.append_summary(chunk.content, &language_registry, cx); + compaction.append_summary(content::from_v1(chunk.content)?, &language_registry, cx); cx.emit(AcpThreadEvent::EntryUpdated(entry_index)); } + Ok(()) } pub fn update_context_compaction( @@ -3602,7 +3639,7 @@ impl AcpThread { if !update.summary_delta.is_empty() { compaction.append_summary( - acp_v1::ContentBlock::Text(acp_v1::TextContent::new(update.summary_delta)), + acp_v2::ContentBlock::Text(acp_v2::TextContent::new(update.summary_delta)), &language_registry, cx, ); @@ -4212,7 +4249,11 @@ impl AcpThread { let path_style = self.project.read(cx).path_style(cx); let mut block = MessageContent::default(); for chunk in &message { - block.append_prompt(chunk.clone(), &language_registry, path_style, cx); + let chunk = match content::from_v1(chunk.clone()) { + Ok(chunk) => chunk, + Err(error) => return futures::future::ready(Err(error)).boxed(), + }; + block.append_prompt(chunk, &language_registry, path_style, cx); } let request = acp_v1::PromptRequest::new(self.session_id.clone(), message); let git_store = self.project.read(cx).git_store().clone(); @@ -5410,7 +5451,7 @@ mod tests { #[test] fn test_text_cursor_reads_source_on_utf8_boundaries() { let sources = - ["visible", "", "aé", "", "🦀b", "", "日本語"].map(acp_v1::ContentBlock::from); + ["visible", "", "aé", "", "🦀b", "", "日本語"].map(acp_v2::ContentBlock::from); let whole = "aé🦀b日本語"; for max_bytes in 1..=whole.len() + 1 { let mut cursor = TextCursor { @@ -5579,8 +5620,8 @@ mod tests { }); } - fn message_test_image() -> acp_v1::ContentBlock { - acp_v1::ContentBlock::Image(acp_v1::ImageContent::new( + fn message_test_image() -> acp_v2::ContentBlock { + acp_v2::ContentBlock::Image(acp_v2::ImageContent::new( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "image/png", )) @@ -5591,23 +5632,23 @@ mod tests { init_test(cx); cx.update(|cx| { let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); - let annotations = acp_v1::Annotations::new().priority(0.5); + let annotations = acp_v2::Annotations::new().priority(0.5); let blocks = vec![ - acp_v1::ContentBlock::Text( - acp_v1::TextContent::new("") + acp_v2::ContentBlock::Text( + acp_v2::TextContent::new("") .annotations(annotations.clone()) .meta(acp_v1::Meta::from_iter([("empty".into(), json!(true))])), ), - acp_v1::ContentBlock::Text( - acp_v1::TextContent::new("hello ") + acp_v2::ContentBlock::Text( + acp_v2::TextContent::new("hello ") .meta(acp_v1::Meta::from_iter([("part".into(), json!(1))])), ), - acp_v1::ContentBlock::Text( - acp_v1::TextContent::new("world") + acp_v2::ContentBlock::Text( + acp_v2::TextContent::new("world") .meta(acp_v1::Meta::from_iter([("part".into(), json!(2))])), ), match message_test_image() { - acp_v1::ContentBlock::Image(image) => acp_v1::ContentBlock::Image( + acp_v2::ContentBlock::Image(image) => acp_v2::ContentBlock::Image( image .uri("file:///original.png".to_string()) .annotations(annotations) @@ -5615,8 +5656,8 @@ mod tests { ), _ => unreachable!("fixture is an image"), }, - acp_v1::ContentBlock::ResourceLink( - acp_v1::ResourceLink::new("original name", "https://example.com/file") + acp_v2::ContentBlock::ResourceLink( + acp_v2::ResourceLink::new("original name", "https://example.com/file") .description("original description".to_string()) .title("original title".to_string()) .meta(acp_v1::Meta::from_iter([( @@ -5705,25 +5746,25 @@ mod tests { let mut content = MessageContent::default(); for chunk in [ "before".into(), - acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::TextResourceContents( - acp_v1::TextResourceContents::new("resource text", "tool://preview"), + acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new("resource text", "tool://preview"), ), )), - acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new( + acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new( "link", "https://example.com/resource", )), - acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::BlobResourceContents( - acp_v1::BlobResourceContents::new( + acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::BlobResourceContents( + acp_v2::BlobResourceContents::new( "private-blob-data", "tool://archive.bin", ), ), )), - acp_v1::ContentBlock::Image(acp_v1::ImageContent::new("not-base64", "image/png")), - acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new( + acp_v2::ContentBlock::Image(acp_v2::ImageContent::new("not-base64", "image/png")), + acp_v2::ContentBlock::Audio(acp_v2::AudioContent::new( "private-audio-data", "audio/wav", )), @@ -5788,6 +5829,54 @@ mod tests { }); } + #[gpui::test] + fn test_v2_other_content_preserves_raw_source_and_renders_fallback(cx: &mut TestAppContext) { + init_test(cx); + cx.update(|cx| { + let language_registry = + Arc::new(LanguageRegistry::test(cx.background_executor().clone())); + let raw_fields = std::collections::BTreeMap::from([ + ( + "payload".to_string(), + json!({"nested": [1, {"value": "original"}]}), + ), + ("_meta".to_string(), json!({"source": "future-agent"})), + ]); + let source = acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new( + "_custom_payload", + raw_fields.clone(), + )); + + let content = + MessageContent::new(source.clone(), &language_registry, PathStyle::local(), cx); + let rendered_blocks = content.blocks().collect::>(); + let [rendered] = rendered_blocks.as_slice() else { + panic!("expected one fallback block"); + }; + assert_eq!(content.source_blocks(), std::slice::from_ref(&source)); + assert!(std::ptr::eq( + rendered.source.expect("fallback source"), + &content.source_blocks()[0], + )); + assert_eq!(rendered.unsupported_content(), Some(&source)); + assert_eq!( + rendered.to_markdown(cx), + "Unknown content type is not supported." + ); + + let output = ContentBlock::new_output(source, &language_registry, cx); + let Some(acp_v2::ContentBlock::Other(other)) = output.unsupported_content() else { + panic!("expected original unknown source"); + }; + assert_eq!(other.type_, "_custom_payload"); + assert_eq!(other.fields, raw_fields); + assert_eq!( + output.to_markdown(cx), + "Unknown content type is not supported." + ); + }); + } + #[gpui::test] async fn test_message_content_preserves_streaming_entities(cx: &mut TestAppContext) { init_test(cx); @@ -5802,14 +5891,14 @@ mod tests { let source_blocks = [ "before".into(), - acp_v1::ContentBlock::Text( - acp_v1::TextContent::new(" image") + acp_v2::ContentBlock::Text( + acp_v2::TextContent::new(" image") .meta(acp_v1::Meta::from_iter([("sequence".into(), json!(2))])), ), message_test_image(), "after".into(), - acp_v1::ContentBlock::Text( - acp_v1::TextContent::new(" image") + acp_v2::ContentBlock::Text( + acp_v2::TextContent::new(" image") .meta(acp_v1::Meta::from_iter([("sequence".into(), json!(5))])), ), ]; @@ -5913,16 +6002,16 @@ mod tests { for (content, preview) in [ ( - acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::TextResourceContents( - acp_v1::TextResourceContents::new("Resource preview", "tool://preview") + acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new("Resource preview", "tool://preview") .mime_type("text/markdown".to_string()), ), )), "Resource preview", ), ( - acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new( + acp_v2::ContentBlock::Audio(acp_v2::AudioContent::new( "private-audio-data", "audio/wav", )), @@ -5967,7 +6056,7 @@ mod tests { let path_style = thread.project.read(cx).path_style(cx); let languages = thread.project.read(cx).languages().clone(); let uri = "file:///project/report.md"; - let link = acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new("report", uri)); + let link = acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new("report", uri)); let expected = format!( "{}\n## Details\n", ContentBlock::resource_link_md(uri, path_style), @@ -6016,16 +6105,16 @@ mod tests { .expect("session should be created"); let chunks = vec![ "read ".into(), - acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::TextResourceContents( - acp_v1::TextResourceContents::new( + acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new( "attached file contents", "https://example.com/file", ), ), )), " and ".into(), - acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new( + acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new( "link", "https://example.com/link", )), @@ -6067,7 +6156,7 @@ mod tests { #[test] fn text_resource_markdown_uses_mime_type_for_code_blocks() { let shell = - acp_v1::TextResourceContents::new("echo 'hello from exec test'", "tool://preview") + acp_v2::TextResourceContents::new("echo 'hello from exec test'", "tool://preview") .mime_type("text/x-shellscript".to_string()); assert_eq!( ContentBlock::text_resource_markdown(&shell), @@ -6075,28 +6164,28 @@ mod tests { ); let markdown = - acp_v1::TextResourceContents::new("**approval** requested", "tool://preview") + acp_v2::TextResourceContents::new("**approval** requested", "tool://preview") .mime_type("text/markdown".to_string()); assert_eq!( ContentBlock::text_resource_markdown(&markdown), "**approval** requested" ); - let plain = acp_v1::TextResourceContents::new("plain preview", "tool://preview") + let plain = acp_v2::TextResourceContents::new("plain preview", "tool://preview") .mime_type("text/plain".to_string()); assert_eq!( ContentBlock::text_resource_markdown(&plain), "```\nplain preview\n```" ); - let cpp = acp_v1::TextResourceContents::new("int main() {}", "tool://preview") + let cpp = acp_v2::TextResourceContents::new("int main() {}", "tool://preview") .mime_type("text/x-c++; charset=utf-8".to_string()); assert_eq!( ContentBlock::text_resource_markdown(&cpp), "```cpp\nint main() {}\n```" ); - let untyped = acp_v1::TextResourceContents::new("# plain preview", "tool://preview"); + let untyped = acp_v2::TextResourceContents::new("# plain preview", "tool://preview"); assert_eq!( ContentBlock::text_resource_markdown(&untyped), "```\n# plain preview\n```" @@ -6112,9 +6201,9 @@ mod tests { cx.update(|cx| { let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); - let content = acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::TextResourceContents( - acp_v1::TextResourceContents::new( + let content = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new( "echo 'hello from exec test'", "tool://preview", ) @@ -6128,10 +6217,13 @@ mod tests { panic!("expected embedded resource block, got {block:?}"); }; match &resource.resource { - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => { + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => { assert_eq!(text.text, "echo 'hello from exec test'"); assert_eq!(text.uri, "tool://preview"); - assert_eq!(text.mime_type.as_deref(), Some("text/x-shellscript")); + assert_eq!( + text.mime_type.as_ref().map(AsRef::as_ref), + Some("text/x-shellscript") + ); } other => panic!("expected text resource contents, got {other:?}"), } @@ -6150,9 +6242,9 @@ mod tests { assert_eq!(block.text_content(cx), Some("echo 'hello from exec test'")); let untyped = ContentBlock::new_output( - acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::TextResourceContents( - acp_v1::TextResourceContents::new("# plain preview", "tool://preview"), + acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new("# plain preview", "tool://preview"), ), )), &language_registry, @@ -6172,9 +6264,9 @@ mod tests { cx.update(|cx| { let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); - let image_blob = acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::BlobResourceContents( - acp_v1::BlobResourceContents::new( + let image_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::BlobResourceContents( + acp_v2::BlobResourceContents::new( "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "tool://preview.png", ) @@ -6210,9 +6302,9 @@ mod tests { cx.update(|cx| { let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); - let archive_blob = acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::BlobResourceContents( - acp_v1::BlobResourceContents::new("not an image", "tool://archive.bin") + let archive_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::BlobResourceContents( + acp_v2::BlobResourceContents::new("not an image", "tool://archive.bin") .mime_type("application/octet-stream".to_string()), ), )); @@ -6224,18 +6316,21 @@ mod tests { }; assert!(markdown.is_none()); match &resource.resource { - acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => { + acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => { assert_eq!(blob.uri, "tool://archive.bin"); - assert_eq!(blob.mime_type.as_deref(), Some("application/octet-stream")); + assert_eq!( + blob.mime_type.as_ref().map(AsRef::as_ref), + Some("application/octet-stream") + ); } other => panic!("expected blob resource contents, got {other:?}"), } assert_eq!(block.to_markdown(cx), "tool://archive.bin"); assert_eq!(block.text_content(cx), None); - let invalid_image_blob = acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new( - acp_v1::EmbeddedResourceResource::BlobResourceContents( - acp_v1::BlobResourceContents::new("not-base64", "tool://preview.png") + let invalid_image_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new( + acp_v2::EmbeddedResourceResource::BlobResourceContents( + acp_v2::BlobResourceContents::new("not-base64", "tool://preview.png") .mime_type("image/png".to_string()), ), )); @@ -7870,15 +7965,33 @@ mod tests { let blocks = vec![ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("retained ")), acp_v1::ContentBlock::Text(acp_v1::TextContent::new("context")), - acp_v1::ContentBlock::Resource(text_resource.clone()), + acp_v1::ContentBlock::Resource(text_resource), acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(image_data, "image/png")), acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new( "Reference", "https://example.com/context", )), audio.clone(), - acp_v1::ContentBlock::Resource(blob_resource.clone()), + acp_v1::ContentBlock::Resource(blob_resource), ]; + let source_blocks = blocks + .iter() + .cloned() + .map(content::from_v1) + .collect::>>() + .expect("convert retained content"); + let [ + _, + _, + acp_v2::ContentBlock::Resource(text_resource), + _, + _, + stored_audio, + acp_v2::ContentBlock::Resource(blob_resource), + ] = source_blocks.as_slice() + else { + panic!("expected retained summary content"); + }; thread.update(cx, |thread, cx| { thread @@ -7931,7 +8044,7 @@ mod tests { .as_view() .embedded_resource() .map(|(resource, _)| resource), - Some(&text_resource) + Some(text_resource) ); assert_eq!(resource.to_markdown(cx), "Retained resource text"); assert_eq!( @@ -7948,13 +8061,13 @@ mod tests { let Some(content) = unsupported.unsupported_content() else { panic!("expected preserved audio with a visible fallback"); }; - assert_eq!(content, &audio); + assert_eq!(content, stored_audio); assert!(unsupported.visible_content(cx)); assert_eq!( blob.as_view() .embedded_resource() .map(|(resource, _)| resource), - Some(&blob_resource) + Some(blob_resource) ); assert!(blob.visible_content(cx)); assert_eq!( @@ -7993,7 +8106,7 @@ mod tests { }; assert!(matches!( compaction.summary.as_slice(), - [block] if block.unsupported_content() == Some(&audio) + [block] if block.unsupported_content() == Some(stored_audio) )); assert!( thread @@ -13482,9 +13595,9 @@ mod tests { ) { init_test(cx); let thread = new_test_thread(cx).await; - let text = acp_v1::ContentBlock::Text( - acp_v1::TextContent::new("before") - .meta(acp_v1::Meta::from_iter([("sequence".into(), json!(1))])), + let text = acp_v2::ContentBlock::Text( + acp_v2::TextContent::new("before") + .meta(acp_v2::Meta::from_iter([("sequence".into(), json!(1))])), ); let image = message_test_image(); diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs index e145f0e51df..11d3edf436c 100644 --- a/crates/acp_thread/src/connection.rs +++ b/crates/acp_thread/src/connection.rs @@ -767,6 +767,7 @@ mod test_support { sessions: Arc>>, permission_requests: HashMap, next_prompt_updates: Arc>>, + next_truncate: Arc>>>, supports_load_session: bool, supports_session_additional_directories: bool, agent_id: AgentId, @@ -788,6 +789,7 @@ mod test_support { pub fn new() -> Self { Self { next_prompt_updates: Default::default(), + next_truncate: Default::default(), permission_requests: HashMap::default(), sessions: Arc::default(), supports_load_session: false, @@ -801,6 +803,12 @@ mod test_support { *self.next_prompt_updates.lock() = updates; } + pub fn defer_next_truncate(&self) -> oneshot::Sender<()> { + let (sender, receiver) = oneshot::channel(); + assert!(self.next_truncate.lock().replace(receiver).is_none()); + sender + } + pub fn with_permission_requests( mut self, permission_requests: HashMap, @@ -1060,7 +1068,10 @@ mod test_support { _session_id: &acp_v1::SessionId, _cx: &App, ) -> Option> { - Some(Rc::new(StubAgentSessionEditor)) + // Capability checks also call this; only run may consume the gate. + Some(Rc::new(StubAgentSessionEditor { + next_truncate: self.next_truncate.clone(), + })) } fn into_any(self: Rc) -> Rc { @@ -1091,11 +1102,20 @@ mod test_support { } } - struct StubAgentSessionEditor; + struct StubAgentSessionEditor { + next_truncate: Arc>>>, + } impl AgentSessionTruncate for StubAgentSessionEditor { - fn run(&self, _: ClientUserMessageId, _: &mut App) -> Task> { - Task::ready(Ok(())) + fn run(&self, _: ClientUserMessageId, cx: &mut App) -> Task> { + if let Some(receiver) = self.next_truncate.lock().take() { + cx.foreground_executor().spawn(async move { + receiver.await?; + Ok(()) + }) + } else { + Task::ready(Ok(())) + } } } diff --git a/crates/acp_thread/src/content.rs b/crates/acp_thread/src/content.rs new file mode 100644 index 00000000000..4bcb120cb8f --- /dev/null +++ b/crates/acp_thread/src/content.rs @@ -0,0 +1,348 @@ +use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2}; +use anyhow::{Result, bail}; + +pub fn from_v1(block: acp_v1::ContentBlock) -> Result { + Ok(match block { + acp_v1::ContentBlock::Text(content) => acp_v2::ContentBlock::Text( + acp_v2::TextContent::new(content.text) + .annotations(annotations_from_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v1::ContentBlock::Image(content) => acp_v2::ContentBlock::Image( + acp_v2::ImageContent::new(content.data, content.mime_type) + .uri(content.uri) + .annotations(annotations_from_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v1::ContentBlock::Audio(content) => acp_v2::ContentBlock::Audio( + acp_v2::AudioContent::new(content.data, content.mime_type) + .annotations(annotations_from_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v1::ContentBlock::ResourceLink(content) => acp_v2::ContentBlock::ResourceLink( + acp_v2::ResourceLink::new(content.name, content.uri) + .title(content.title) + .description(content.description) + .mime_type(content.mime_type.map(acp_v2::MediaType::new)) + .size(content.size) + .annotations(annotations_from_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v1::ContentBlock::Resource(content) => { + let resource = match content.resource { + acp_v1::EmbeddedResourceResource::TextResourceContents(resource) => { + acp_v2::EmbeddedResourceResource::TextResourceContents( + acp_v2::TextResourceContents::new(resource.text, resource.uri) + .mime_type(resource.mime_type.map(acp_v2::MediaType::new)) + .meta(resource.meta), + ) + } + acp_v1::EmbeddedResourceResource::BlobResourceContents(resource) => { + acp_v2::EmbeddedResourceResource::BlobResourceContents( + acp_v2::BlobResourceContents::new(resource.blob, resource.uri) + .mime_type(resource.mime_type.map(acp_v2::MediaType::new)) + .meta(resource.meta), + ) + } + _ => bail!("unsupported v1 embedded resource variant"), + }; + acp_v2::ContentBlock::Resource( + acp_v2::EmbeddedResource::new(resource) + .annotations(annotations_from_v1(content.annotations)?) + .meta(content.meta), + ) + } + _ => bail!("unsupported v1 content block variant"), + }) +} + +pub fn to_v1(block: acp_v2::ContentBlock) -> Result { + Ok(match block { + acp_v2::ContentBlock::Text(content) => acp_v1::ContentBlock::Text( + acp_v1::TextContent::new(content.text) + .annotations(annotations_to_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v2::ContentBlock::Image(content) => acp_v1::ContentBlock::Image( + acp_v1::ImageContent::new(content.data, content.mime_type.0.to_string()) + .uri(content.uri) + .annotations(annotations_to_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v2::ContentBlock::Audio(content) => acp_v1::ContentBlock::Audio( + acp_v1::AudioContent::new(content.data, content.mime_type.0.to_string()) + .annotations(annotations_to_v1(content.annotations)?) + .meta(content.meta), + ), + acp_v2::ContentBlock::ResourceLink(content) => { + if content.icons.is_some() { + bail!("v2 resource link icons cannot be represented in v1"); + } + acp_v1::ContentBlock::ResourceLink( + acp_v1::ResourceLink::new(content.name, content.uri) + .title(content.title) + .description(content.description) + .mime_type(content.mime_type.map(|mime_type| mime_type.0.to_string())) + .size(content.size) + .annotations(annotations_to_v1(content.annotations)?) + .meta(content.meta), + ) + } + acp_v2::ContentBlock::Resource(content) => { + let resource = match content.resource { + acp_v2::EmbeddedResourceResource::TextResourceContents(resource) => { + acp_v1::EmbeddedResourceResource::TextResourceContents( + acp_v1::TextResourceContents::new(resource.text, resource.uri) + .mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string())) + .meta(resource.meta), + ) + } + acp_v2::EmbeddedResourceResource::BlobResourceContents(resource) => { + acp_v1::EmbeddedResourceResource::BlobResourceContents( + acp_v1::BlobResourceContents::new(resource.blob, resource.uri) + .mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string())) + .meta(resource.meta), + ) + } + _ => bail!("unsupported v2 embedded resource variant"), + }; + acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(resource) + .annotations(annotations_to_v1(content.annotations)?) + .meta(content.meta), + ) + } + acp_v2::ContentBlock::Other(_) => { + bail!("v2 custom content block cannot be represented in v1") + } + _ => bail!("unsupported v2 content block variant"), + }) +} + +pub fn can_convert_to_v1(block: &acp_v2::ContentBlock) -> bool { + let annotations = match block { + acp_v2::ContentBlock::Text(content) => &content.annotations, + acp_v2::ContentBlock::Image(content) => &content.annotations, + acp_v2::ContentBlock::Audio(content) => &content.annotations, + acp_v2::ContentBlock::ResourceLink(content) if content.icons.is_none() => { + &content.annotations + } + acp_v2::ContentBlock::Resource(content) + if matches!( + content.resource, + acp_v2::EmbeddedResourceResource::TextResourceContents(_) + | acp_v2::EmbeddedResourceResource::BlobResourceContents(_) + ) => + { + &content.annotations + } + _ => return false, + }; + annotations + .as_ref() + .and_then(|annotations| annotations.audience.as_ref()) + .is_none_or(|audience| { + audience + .iter() + .all(|role| matches!(role, acp_v2::Role::Assistant | acp_v2::Role::User)) + }) +} + +fn annotations_from_v1( + annotations: Option, +) -> Result> { + annotations + .map(|annotations| { + let audience = annotations + .audience + .map(|audience| { + audience + .into_iter() + .map(|role| match role { + acp_v1::Role::Assistant => Ok(acp_v2::Role::Assistant), + acp_v1::Role::User => Ok(acp_v2::Role::User), + _ => bail!("unsupported v1 annotation role"), + }) + .collect::>>() + }) + .transpose()?; + Ok(acp_v2::Annotations::new() + .audience(audience) + .last_modified(annotations.last_modified) + .priority(annotations.priority) + .meta(annotations.meta)) + }) + .transpose() +} + +fn annotations_to_v1( + annotations: Option, +) -> Result> { + annotations + .map(|annotations| { + let audience = annotations + .audience + .map(|audience| { + audience + .into_iter() + .map(|role| match role { + acp_v2::Role::Assistant => Ok(acp_v1::Role::Assistant), + acp_v2::Role::User => Ok(acp_v1::Role::User), + acp_v2::Role::Other(_) => { + bail!("v2 annotation role cannot be represented in v1") + } + _ => bail!("unsupported v2 annotation role"), + }) + .collect::>>() + }) + .transpose()?; + Ok(acp_v1::Annotations::new() + .audience(audience) + .last_modified(annotations.last_modified) + .priority(annotations.priority) + .meta(annotations.meta)) + }) + .transpose() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::{Value, json}; + use std::collections::BTreeMap; + + fn meta() -> serde_json::Map { + serde_json::Map::from_iter([("origin".to_owned(), json!({"nested": [0, null, "value"]}))]) + } + + fn annotations() -> acp_v1::Annotations { + acp_v1::Annotations::new() + .audience(vec![acp_v1::Role::User, acp_v1::Role::Assistant]) + .last_modified("2025-01-02T03:04:05Z") + .priority(0.75) + .meta(meta()) + } + + fn round_trip(block: acp_v1::ContentBlock) { + let original = block.clone(); + let upgraded = from_v1(block).expect("v1 block should convert to v2"); + assert!(can_convert_to_v1(&upgraded)); + assert_eq!( + serde_json::to_value(&upgraded).expect("serialize v2 block"), + serde_json::to_value(&original).expect("serialize original block") + ); + let restored = to_v1(upgraded).expect("converted block should convert back to v1"); + assert_eq!(restored, original); + } + + fn rejects(block: acp_v2::ContentBlock) { + assert!(!can_convert_to_v1(&block)); + assert!(to_v1(block).is_err()); + } + + #[test] + fn preserves_all_v1_content_variants_and_metadata() { + round_trip(acp_v1::ContentBlock::Text( + acp_v1::TextContent::new("Hello \0 世界") + .annotations(annotations()) + .meta(meta()), + )); + round_trip(acp_v1::ContentBlock::Image( + acp_v1::ImageContent::new("AAECA/8=", "not/a valid mime ; 😀") + .uri("") + .annotations(annotations()) + .meta(meta()), + )); + round_trip(acp_v1::ContentBlock::Audio( + acp_v1::AudioContent::new("///+", "") + .annotations(annotations()) + .meta(meta()), + )); + round_trip(acp_v1::ContentBlock::ResourceLink( + acp_v1::ResourceLink::new("name", "file:///some/resource") + .title("") + .description("description") + .mime_type("??") + .size(0) + .annotations(annotations()) + .meta(meta()), + )); + round_trip(acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents( + acp_v1::TextResourceContents::new("source text", "file:///text") + .mime_type("") + .meta(meta()), + )) + .annotations(annotations()) + .meta(meta()), + )); + round_trip(acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents( + acp_v1::BlobResourceContents::new("AAECA/8=", "file:///blob") + .mime_type("bad mime") + .meta(meta()), + )) + .annotations(annotations()) + .meta(meta()), + )); + } + + #[test] + fn preserves_absent_and_empty_optional_fields() { + round_trip(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(""))); + round_trip(acp_v1::ContentBlock::Text( + acp_v1::TextContent::new("") + .annotations(acp_v1::Annotations::new().audience(Vec::new())), + )); + round_trip(acp_v1::ContentBlock::Text( + acp_v1::TextContent::new("") + .annotations(acp_v1::Annotations::new()) + .meta(acp_v1::Meta::new()), + )); + round_trip(acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents( + acp_v1::TextResourceContents::new("", "").meta(acp_v1::Meta::new()), + )) + .annotations(acp_v1::Annotations::new().meta(acp_v1::Meta::new())) + .meta(acp_v1::Meta::new()), + )); + round_trip(acp_v1::ContentBlock::Image(acp_v1::ImageContent::new( + "", "", + ))); + round_trip(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new( + "", "", + ))); + round_trip(acp_v1::ContentBlock::ResourceLink( + acp_v1::ResourceLink::new("", ""), + )); + round_trip(acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents( + acp_v1::TextResourceContents::new("", ""), + )), + )); + round_trip(acp_v1::ContentBlock::Resource( + acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents( + acp_v1::BlobResourceContents::new("", ""), + )), + )); + } + + #[test] + fn rejects_v2_only_content_and_annotations() { + rejects(acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new( + "_custom", + BTreeMap::from([("payload".to_owned(), json!({"opaque": [1, 2]}))]), + ))); + rejects(acp_v2::ContentBlock::Image( + acp_v2::ImageContent::new("AAE=", "image/png").annotations( + acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_custom".into())]), + ), + )); + rejects(acp_v2::ContentBlock::ResourceLink( + acp_v2::ResourceLink::new("name", "uri").icons(Vec::new()), + )); + rejects(acp_v2::ContentBlock::ResourceLink( + acp_v2::ResourceLink::new("name", "uri").icons(vec![acp_v2::Icon::new("file:///icon")]), + )); + } +} diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs index 0f22991990e..f64fb289965 100644 --- a/crates/agent/src/agent.rs +++ b/crates/agent/src/agent.rs @@ -1981,6 +1981,7 @@ impl NativeAgent { for message in prompt.messages { let context_server::types::PromptMessage { role, content } = message; let block = mcp_message_content_to_acp_content_block(content); + let display_block = acp_thread::content::from_v1(block.clone())?; match role { context_server::types::Role::User => { @@ -1989,7 +1990,7 @@ impl NativeAgent { acp_thread.update(cx, |acp_thread, cx| { acp_thread.push_user_content_block_with_indent( Some(id.clone()), - block.clone(), + display_block, true, cx, ); @@ -2002,7 +2003,7 @@ impl NativeAgent { context_server::types::Role::Assistant => { acp_thread.update(cx, |acp_thread, cx| { acp_thread.push_assistant_content_block_with_indent( - block.clone(), + display_block, false, true, cx, @@ -2154,10 +2155,11 @@ impl NativeAgent { // user's own typed message is already rendered by the normal // prompt flow, so we don't push it to the UI again here. let injected_id = acp_thread::ClientUserMessageId::new(); + let display_block = acp_thread::content::from_v1(envelope_block.clone())?; acp_thread.update(cx, |acp_thread, cx| { acp_thread.push_user_content_block_with_indent( Some(injected_id), - envelope_block.clone(), + display_block, true, cx, ); @@ -2288,11 +2290,14 @@ impl NativeAgentConnection { match event { ThreadEvent::UserMessage(message) => { + let content = message.content.iter().cloned() + .map(|content| acp_thread::content::from_v1(content.into())) + .collect::>>()?; acp_thread.update(cx, |thread, cx| { - for content in &*message.content { + for content in content { thread.push_user_content_block( Some(message.id.clone()), - content.clone().into(), + content, cx, ); } diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 6e53713a66e..271f6c657c3 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -1674,6 +1674,12 @@ impl ConversationView { }); list_state.remeasure_items(*index..*index + 1); active.update(cx, |active, cx| { + if active.editing_message == Some(*index) + && !active.can_edit_user_message(*index, cx) + { + active.editing_message = None; + cx.notify(); + } active.sync_elicitation_state_for_entry(*index, window, cx); active.auto_expand_streaming_thought(cx); active.sync_generating_indicator(cx); @@ -9103,6 +9109,221 @@ pub(crate) mod tests { ); } + async fn assert_unsupported_source_message_cannot_regenerate( + unsupported: agent_client_protocol::schema::v2::ContentBlock, + cx: &mut TestAppContext, + ) { + use agent_client_protocol::schema::v2 as acp_v2; + + init_test(cx); + let (conversation_view, cx) = + setup_conversation_view(StubAgentServer::default_response(), cx).await; + add_to_workspace(conversation_view.clone(), cx); + + let thread_view = active_thread(&conversation_view, cx); + let thread = thread_view.read_with(cx, |view, _| view.thread.clone()); + thread + .update(cx, |thread, cx| thread.send_raw("original", cx)) + .await + .expect("send initial message"); + cx.run_until_parked(); + + let client_id = ClientUserMessageId::new(); + thread.update(cx, |thread, cx| { + thread.push_user_content_block( + Some(client_id.clone()), + acp_v2::ContentBlock::Text(acp_v2::TextContent::new("still visible")), + cx, + ); + }); + cx.run_until_parked(); + + let index = thread.read_with(cx, |thread, _| thread.entries().len() - 1); + let entry_view_state = thread_view.read_with(cx, |view, _| view.entry_view_state.clone()); + let editor = entry_view_state.read_with(cx, |state, _| { + state + .entry(index) + .and_then(|entry| entry.message_editor()) + .cloned() + .expect("user message editor") + }); + cx.focus(&editor); + thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, Some(index))); + thread.update(cx, |thread, cx| { + thread.push_user_content_block(Some(client_id), unsupported.clone(), cx); + }); + cx.run_until_parked(); + + thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None)); + let rendered = editor.update(cx, |editor, cx| editor.text(cx)); + assert!(rendered.contains("still visible")); + assert!(rendered.contains("Unsupported message content")); + cx.simulate_input("attempted edit"); + assert_eq!(editor.update(cx, |editor, cx| editor.text(cx)), rendered); + + thread_view.update_in(cx, |view, window, cx| { + view.handle_entry_view_event( + &entry_view_state, + &EntryViewEvent { + entry_index: index, + view_event: ViewEvent::MessageEditorEvent( + editor.clone(), + MessageEditorEvent::Send, + ), + }, + window, + cx, + ); + view.regenerate(index, editor.clone(), window, cx); + }); + let other_editor = entry_view_state.read_with(cx, |state, _| { + state + .entry(0) + .and_then(|entry| entry.message_editor()) + .cloned() + .expect("original editor") + }); + cx.focus(&other_editor); + other_editor.update_in(cx, |editor, window, cx| { + assert!(editor.focus_handle(cx).is_focused(window)); + }); + let composer = message_editor(&conversation_view, cx); + cx.focus(&composer); + cx.run_until_parked(); + thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None)); + thread.read_with(cx, |thread, _| { + assert_eq!( + thread.entries()[index] + .user_message() + .expect("user message") + .content + .source_blocks()[1], + unsupported + ); + assert_eq!(thread.entries().len(), index + 1); + }); + } + + #[gpui::test] + async fn test_unsupported_source_message_cannot_regenerate(cx: &mut TestAppContext) { + use agent_client_protocol::schema::v2 as acp_v2; + + assert_unsupported_source_message_cannot_regenerate( + acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new( + "_future", + Default::default(), + )), + cx, + ) + .await; + } + + #[gpui::test] + async fn test_unknown_annotation_source_message_cannot_regenerate(cx: &mut TestAppContext) { + use agent_client_protocol::schema::v2 as acp_v2; + + assert_unsupported_source_message_cannot_regenerate( + acp_v2::ContentBlock::Text(acp_v2::TextContent::new("annotated text").annotations( + acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_future".into())]), + )), + cx, + ) + .await; + } + + #[gpui::test] + async fn test_regenerate_does_not_resend_fallback_after_delayed_rewind( + cx: &mut TestAppContext, + ) { + use agent_client_protocol::schema::v2 as acp_v2; + + init_test(cx); + for (cancel_before_update, cancel_after_update) in + [(false, false), (true, false), (false, true)] + { + let connection = StubAgentConnection::new(); + let (conversation_view, cx) = + setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await; + add_to_workspace(conversation_view.clone(), cx); + let thread_view = active_thread(&conversation_view, cx); + let thread = thread_view.read_with(cx, |view, _| view.thread.clone()); + let prompt = thread.update(cx, |thread, cx| thread.send_raw("original", cx)); + cx.run_until_parked(); + let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone()); + connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn); + prompt.await.expect("initial prompt should finish"); + cx.run_until_parked(); + + let client_id = thread.read_with(cx, |thread, _| { + thread + .entries() + .first() + .and_then(|entry| entry.user_message()) + .and_then(|message| message.client_id.clone()) + .expect("initial user message") + }); + let editor = thread_view.read_with(cx, |view, cx| { + view.entry_view_state + .read(cx) + .entry(0) + .and_then(|entry| entry.message_editor()) + .cloned() + .expect("initial message editor") + }); + cx.focus(&editor); + editor.update_in(cx, |editor, window, cx| { + editor.set_text("edited", window, cx); + }); + let finish_truncate = connection.defer_next_truncate(); + thread_view.update_in(cx, |view, window, cx| { + view.regenerate(0, editor.clone(), window, cx); + }); + cx.run_until_parked(); + assert_eq!(thread.read_with(cx, |thread, _| thread.entries().len()), 1); + + if cancel_before_update { + thread_view.update_in(cx, |view, window, cx| { + view.cancel_editing(&Default::default(), window, cx); + }); + } + thread.update(cx, |thread, cx| { + thread.push_user_content_block( + Some(client_id), + acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new( + "_future", + Default::default(), + )), + cx, + ); + }); + cx.run_until_parked(); + if cancel_after_update { + thread_view.update_in(cx, |view, window, cx| { + view.cancel_editing(&Default::default(), window, cx); + }); + } + assert!( + editor + .update(cx, |editor, cx| editor.text(cx)) + .contains("Unsupported message content") + ); + finish_truncate + .send(()) + .expect("truncate should be pending"); + cx.run_until_parked(); + + let resent = + thread.read_with(cx, |thread, _| thread.status() == ThreadStatus::Generating); + if resent { + connection.end_turn(session_id, acp_v1::StopReason::EndTurn); + cx.run_until_parked(); + } + assert!(!resent, "regeneration must not submit a read-only fallback"); + thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty())); + thread_view.read_with(cx, |view, _| assert!(view.thread_error.is_some())); + } + } + #[gpui::test] async fn test_message_editing_regenerate(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs index cf4f8072e65..d0b66a70dc6 100644 --- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs +++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs @@ -957,7 +957,11 @@ mod tests { let error = cx.new(|cx| Markdown::new("error match".into(), None, None, cx)); let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); let unsupported_block = ContentBlock::new_output( - acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new("YXVkaW8=", "audio/wav")), + acp_thread::content::from_v1(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new( + "YXVkaW8=", + "audio/wav", + ))) + .expect("known v1 audio content"), &language_registry, cx, ); diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 6ef01f6e75b..68dd31305ef 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -5,7 +5,7 @@ use crate::{ open_abs_path_at_point, thread_metadata_store::{ThreadId, ThreadMetadataStore}, }; -use agent_client_protocol::schema::v1 as acp_v1; +use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2}; use std::cell::RefCell; use acp_thread::{ @@ -1234,6 +1234,25 @@ impl ThreadView { self.parent_session_id.is_some() } + pub(super) fn can_edit_user_message(&self, index: usize, cx: &App) -> bool { + let thread = self.thread.read(cx); + let Some(message) = thread + .entries() + .get(index) + .and_then(|entry| entry.user_message()) + else { + return false; + }; + !self.is_subagent() + && thread.supports_truncate(cx) + && message.client_id.is_some() + && message + .content + .source_blocks() + .iter() + .all(acp_thread::content::can_convert_to_v1) + } + /// Returns the currently active editor, either for a message that is being /// edited or the editor for a new message. pub(crate) fn active_editor(&self, cx: &App) -> Entity { @@ -1285,12 +1304,7 @@ impl ThreadView { }); } ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => { - if let Some(AgentThreadEntry::UserMessage(user_message)) = - self.thread.read(cx).entries().get(event.entry_index) - && self.thread.read(cx).supports_truncate(cx) - && user_message.client_id.is_some() - && !self.is_subagent() - { + if self.can_edit_user_message(event.entry_index, cx) { self.editing_message = Some(event.entry_index); cx.notify(); } @@ -1298,9 +1312,7 @@ impl ThreadView { ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => { if let Some(AgentThreadEntry::UserMessage(user_message)) = self.thread.read(cx).entries().get(event.entry_index) - && self.thread.read(cx).supports_truncate(cx) - && user_message.client_id.is_some() - && !self.is_subagent() + && self.can_edit_user_message(event.entry_index, cx) { if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) { self.editing_message = None; @@ -1310,7 +1322,7 @@ impl ThreadView { } ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {} ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => { - if !self.is_subagent() { + if self.can_edit_user_message(event.entry_index, cx) { self.regenerate(event.entry_index, editor.clone(), window, cx); } } @@ -2011,7 +2023,7 @@ impl ThreadView { window: &mut Window, cx: &mut Context, ) { - if self.is_loading_contents { + if self.is_loading_contents || !self.can_edit_user_message(entry_ix, cx) { return; } let thread = self.thread.clone(); @@ -2061,6 +2073,16 @@ impl ThreadView { .update(cx, |thread, cx| thread.rewind(client_id, cx)) .await?; this.update_in(cx, |thread, window, cx| { + // Rewind can outlive a source update that replaces the editor with a fallback. + if message_editor.read(cx).editor().read(cx).read_only(cx) { + thread.handle_thread_error( + anyhow!( + "The conversation was rewound, but the message became read-only and was not resent." + ), + cx, + ); + return; + } cx.emit(AcpThreadViewEvent::Interacted); thread.send_impl(message_editor, window, cx); thread.activation_focus_handle(cx).focus(window, cx); @@ -2473,7 +2495,11 @@ impl ThreadView { .get(index) .and_then(|e| e.user_message()) { - editor.set_message(user_message.content.source_blocks().to_vec(), window, cx); + editor.set_source_message( + user_message.content.source_blocks().to_vec(), + window, + cx, + ); } }) }; @@ -6194,8 +6220,15 @@ impl ThreadView { .is_some_and(|checkpoint| checkpoint.show); let is_subagent = self.is_subagent(); - let can_rewind = self.thread.read(cx).supports_truncate(cx); - let is_editable = can_rewind && message.client_id.is_some() && !is_subagent; + let can_restore_checkpoint = self.thread.read(cx).supports_truncate(cx) + && message.client_id.is_some() + && !is_subagent; + let source_is_representable = message + .content + .source_blocks() + .iter() + .all(acp_thread::content::can_convert_to_v1); + let is_editable = can_restore_checkpoint && source_is_representable; let agent_name = if is_subagent { "subagents".into() } else { @@ -6215,7 +6248,7 @@ impl ThreadView { .px_2() .gap_1p5() .w_full() - .when(is_editable && has_checkpoint_button, |this| { + .when(can_restore_checkpoint && has_checkpoint_button, |this| { this.children(message.client_id.clone().map(|client_id| { h_flex() .px_3() @@ -6335,10 +6368,14 @@ impl ThreadView { .child(Label::new("Unavailable Editing")) .child( div().max_w_64().child( - Label::new(format!( - "Editing previous messages is not available for {} yet.", - agent_name - )) + Label::new(if source_is_representable { + format!( + "Editing previous messages is not available for {} yet.", + agent_name + ) + } else { + "This message contains unsupported content and cannot be edited or resent.".to_string() + }) .size(LabelSize::Small) .color(Color::Muted), ), @@ -10336,7 +10373,7 @@ impl ThreadView { fn render_embedded_resource_output( &self, - resource: &acp_v1::EmbeddedResource, + resource: &acp_v2::EmbeddedResource, context_ix: usize, card_layout: bool, cx: &Context, @@ -10360,10 +10397,10 @@ impl ThreadView { .into_any_element() } - fn render_embedded_resource_label(&self, resource: &acp_v1::EmbeddedResource) -> AnyElement { + fn render_embedded_resource_label(&self, resource: &acp_v2::EmbeddedResource) -> AnyElement { let uri = match &resource.resource { - acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(), - acp_v1::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(), + acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(), + acp_v2::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(), _ => "", }; if uri.is_empty() { @@ -10378,7 +10415,7 @@ impl ThreadView { fn render_resource_link( &self, - resource_link: &acp_v1::ResourceLink, + resource_link: &acp_v2::ResourceLink, cx: &Context, ) -> AnyElement { let uri: SharedString = resource_link.uri.clone().into(); diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs index f58657fcf7a..31f9e5b56af 100644 --- a/crates/agent_ui/src/entry_view_state.rs +++ b/crates/agent_ui/src/entry_view_state.rs @@ -240,16 +240,26 @@ impl EntryViewState { let can_rewind = thread.read(cx).supports_truncate(cx); let has_client_id = message.client_id.is_some(); let is_subagent = thread.read(cx).parent_session_id().is_some(); - let chunks = message.content.source_blocks().to_vec(); + let source_blocks = message.content.source_blocks(); + let source_is_representable = source_blocks + .iter() + .all(acp_thread::content::can_convert_to_v1); + let is_editable = + can_rewind && has_client_id && !is_subagent && source_is_representable; if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) { - if !editor.focus_handle(cx).is_focused(window) { - // Only update if we are not editing. - // If we are, cancelling the edit will set the message to the newest content. + // Keep focused drafts unless newly unsupported content makes + // the message read-only and needs its fallback shown. + let refreshed_source = (!source_is_representable + || !editor.focus_handle(cx).is_focused(window)) + .then(|| source_blocks.to_vec()); + editor.update(cx, |editor, cx| editor.set_read_only(!is_editable, cx)); + if let Some(source_blocks) = refreshed_source { editor.update(cx, |editor, cx| { - editor.set_message(chunks, window, cx); + editor.set_source_message(source_blocks, window, cx); }); } } else { + let source_blocks = source_blocks.to_vec(); let message_editor = cx.new(|cx| { let mut editor = MessageEditor::new( self.workspace.clone(), @@ -265,10 +275,10 @@ impl EntryViewState { window, cx, ); - if !can_rewind || !has_client_id || is_subagent { + if !is_editable { editor.set_read_only(true, cx); } - editor.set_message(chunks, window, cx); + editor.set_source_message(source_blocks, window, cx); editor }); cx.subscribe(&message_editor, move |_, editor, event, cx| { diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs index a6eca45c6cd..1f05167adaf 100644 --- a/crates/agent_ui/src/message_editor.rs +++ b/crates/agent_ui/src/message_editor.rs @@ -1695,6 +1695,57 @@ impl MessageEditor { self.insert_message_blocks(message, false, window, cx); } + pub fn set_source_message( + &mut self, + source_blocks: Vec, + window: &mut Window, + cx: &mut Context, + ) { + use agent_client_protocol::schema::v2::ContentBlock; + + if source_blocks + .iter() + .all(acp_thread::content::can_convert_to_v1) + { + match source_blocks + .into_iter() + .map(acp_thread::content::to_v1) + .collect::, _>>() + { + Ok(message) => self.set_message(message, window, cx), + Err(error) => { + log::error!("failed to display representable source message: {error}"); + self.set_message( + vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new( + "[Unsupported message content — this message cannot be edited or resent]", + ))], + window, + cx, + ); + } + } + return; + } + + let mut visible = Vec::new(); + for block in source_blocks { + if acp_thread::content::can_convert_to_v1(&block) { + match acp_thread::content::to_v1(block) { + Ok(block) => visible.push(block), + Err(error) => log::error!("failed to display source content: {error}"), + } + } else if let ContentBlock::Text(text) = block { + visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new( + text.text, + ))); + } + } + visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new( + "\n[Unsupported message content — this message cannot be edited or resent]", + ))); + self.set_message(visible, window, cx); + } + pub fn append_message( &mut self, message: Vec, @@ -2266,7 +2317,7 @@ mod tests { use futures::{FutureExt as _, StreamExt as _}; use gpui::{ AppContext, ClipboardEntry, ClipboardItem, Entity, EventEmitter, ExternalPaths, - FocusHandle, Focusable, Task, TestAppContext, VisualTestContext, + FocusHandle, Focusable, Task, TestAppContext, VisualContext, VisualTestContext, }; use language_model::LanguageModelRegistry; use lsp::{CompletionContext, CompletionTriggerKind}; @@ -5579,6 +5630,93 @@ mod tests { assert!(!message_editor.update(cx, |editor, cx| editor.is_empty(cx))); } + #[gpui::test] + async fn test_source_message_known_text_remains_editable(cx: &mut TestAppContext) { + init_test(cx); + let (message_editor, cx) = setup_message_editor(cx).await; + + message_editor.update_in(cx, |editor, window, cx| { + editor.set_source_message( + vec![agent_client_protocol::schema::v2::ContentBlock::Text( + agent_client_protocol::schema::v2::TextContent::new("original"), + )], + window, + cx, + ); + }); + let workspace = message_editor.read_with(cx, |editor, _| { + editor.workspace.upgrade().expect("message workspace") + }); + workspace.update_in(cx, |workspace, window, cx| { + workspace.active_pane().update(cx, |pane, cx| { + pane.add_item( + Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))), + true, + true, + None, + window, + cx, + ); + }); + }); + cx.focus(&message_editor); + cx.simulate_input("edited"); + assert!( + message_editor + .update(cx, |editor, cx| editor.text(cx)) + .contains("edited") + ); + } + + #[gpui::test] + async fn test_source_message_unknown_content_indicated_with_known_text( + cx: &mut TestAppContext, + ) { + use agent_client_protocol::schema::v2 as acp_v2; + + init_test(cx); + let (message_editor, cx) = setup_message_editor(cx).await; + message_editor.update_in(cx, |editor, window, cx| { + editor.set_read_only(true, cx); + editor.set_source_message( + vec![ + acp_v2::ContentBlock::Text(acp_v2::TextContent::new("visible text")), + acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new( + "_future", + Default::default(), + )), + ], + window, + cx, + ); + assert!(editor.text(cx).contains("visible text")); + assert!(editor.text(cx).contains("Unsupported message content")); + }); + } + + #[gpui::test] + async fn test_source_message_unknown_annotation_indicated_with_text(cx: &mut TestAppContext) { + use agent_client_protocol::schema::v2 as acp_v2; + + init_test(cx); + let (message_editor, cx) = setup_message_editor(cx).await; + message_editor.update_in(cx, |editor, window, cx| { + editor.set_read_only(true, cx); + editor.set_source_message( + vec![acp_v2::ContentBlock::Text( + acp_v2::TextContent::new("annotated text").annotations( + acp_v2::Annotations::new() + .audience(vec![acp_v2::Role::Other("_future".into())]), + ), + )], + window, + cx, + ); + assert!(editor.text(cx).contains("annotated text")); + assert!(editor.text(cx).contains("Unsupported message content")); + }); + } + #[gpui::test] async fn test_set_message_normalizes_crlf_before_mention(cx: &mut TestAppContext) { init_test(cx);