Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp: Add ACP context compaction support (#64081)
Ben Brandtd1dae815f230
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex f7b8140f969..0905f5826ec 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -754,11 +754,26 @@ impl ElicitationStore {#[derive(Debug, Clone, PartialEq, Eq)]pub struct ContextCompactionId(pub Arc<str>);-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq)]pub enum ContextCompactionStatus {InProgress,Completed,+ Failed,Canceled,+ Other(Arc<str>),+}++impl From<acp::CompactionStatus> for ContextCompactionStatus {+ fn from(status: acp::CompactionStatus) -> Self {+ match status {+ acp::CompactionStatus::InProgress => Self::InProgress,+ acp::CompactionStatus::Completed => Self::Completed,+ acp::CompactionStatus::Failed => Self::Failed,+ acp::CompactionStatus::Cancelled => Self::Canceled,+ acp::CompactionStatus::Other(status) => Self::Other(status.into()),+ _ => Self::Other("unknown".into()),+ }+ }}/// A point in the thread where the conversation history was compacted to free@@ -768,15 +783,66 @@ pub enum ContextCompactionStatus {pub struct ContextCompaction {pub id: ContextCompactionId,pub status: ContextCompactionStatus,- /// The compaction summary, streamed in as the model produces it. This is- /// `None` for provider-native compaction, which produces no summary to show.- pub summary: Option<Entity<Markdown>>,+ pub error: Option<Entity<Markdown>>,+ pub summary: Vec<ContentBlock>,}impl ContextCompaction {pub fn is_in_progress(&self) -> bool {self.status == ContextCompactionStatus::InProgress}++ fn apply_update(+ &mut self,+ update: acp::CompactionUpdate,+ language_registry: &Arc<LanguageRegistry>,+ path_style: PathStyle,+ cx: &mut App,+ ) {+ self.status = update.status.into();+ match update.summary {+ MaybeUndefined::Undefined => {}+ MaybeUndefined::Null => self.summary.clear(),+ MaybeUndefined::Value(blocks) => {+ self.summary.clear();+ for block in blocks {+ self.append_summary(block, language_registry, path_style, cx);+ }+ }+ }+ match update.error {+ MaybeUndefined::Undefined => {}+ MaybeUndefined::Null => self.error = None,+ MaybeUndefined::Value(error) => {+ if let Some(markdown) = &self.error {+ markdown.update(cx, |markdown, cx| markdown.reset(error.into(), cx));+ } else {+ self.error = Some(cx.new(|cx| Markdown::new_text(error.into(), cx)));+ }+ }+ }+ }++ fn append_summary(+ &mut self,+ content: acp::ContentBlock,+ language_registry: &Arc<LanguageRegistry>,+ path_style: PathStyle,+ cx: &mut App,+ ) {+ if let acp::ContentBlock::Text(text) = &content+ && let Some(ContentBlock::Markdown { markdown }) = self.summary.last()+ {+ markdown.update(cx, |markdown, cx| markdown.append(&text.text, cx));+ } else {+ self.summary.push(ContentBlock::new_output(+ content,+ language_registry,+ path_style,+ cx,+ ));+ }+ }}#[derive(Debug)]@@ -812,7 +878,27 @@ impl AgentThreadEntry {}md}- Self::ContextCompaction(_) => "--- Context Compacted ---\n\n".to_string(),+ Self::ContextCompaction(compaction) => {+ let status = match &compaction.status {+ ContextCompactionStatus::InProgress => "In Progress",+ ContextCompactionStatus::Completed => "Completed",+ ContextCompactionStatus::Failed => "Failed",+ ContextCompactionStatus::Canceled => "Canceled",+ ContextCompactionStatus::Other(status) => status,+ };+ let mut markdown =+ format!("## Context Compaction ({})\n\n", MarkdownEscaped(status));+ for block in &compaction.summary {+ markdown.push_str(block.to_markdown(cx));+ markdown.push_str("\n\n");+ }+ if let Some(error) = &compaction.error {+ markdown.push_str("**Error:** ");+ markdown.push_str(&MarkdownEscaped(error.read(cx).source()).to_string());+ markdown.push_str("\n\n");+ }+ markdown+ }}}@@ -1373,6 +1459,10 @@ pub enum ContentBlock {image: Arc<gpui::Image>,dimensions: Option<gpui::Size<u32>>,},+ Unsupported {+ content: acp::ContentBlock,+ markdown: Entity<Markdown>,+ },}impl ContentBlock {@@ -1400,14 +1490,20 @@ impl ContentBlock {this}- pub fn new_tool_call_content(+ pub fn new_output(block: acp::ContentBlock,language_registry: &Arc<LanguageRegistry>,path_style: PathStyle,cx: &mut App,) -> Self {match block {- acp::ContentBlock::Resource(resource) => {+ acp::ContentBlock::Resource(resource)+ if matches!(+ &resource.resource,+ acp::EmbeddedResourceResource::TextResourceContents(_)+ | acp::EmbeddedResourceResource::BlobResourceContents(_)+ ) =>+ {if let Some((image, dimensions)) = Self::decode_embedded_resource_image(&resource) {Self::Image { image, dimensions }} else {@@ -1416,7 +1512,34 @@ impl ContentBlock {Self::EmbeddedResource { resource, markdown }}}- block => Self::new(block, language_registry, path_style, cx),+ acp::ContentBlock::Image(image) => {+ if let Some((image, dimensions)) = Self::decode_image(&image) {+ Self::Image { image, dimensions }+ } else {+ Self::Unsupported {+ content: acp::ContentBlock::Image(image),+ markdown: Self::create_markdown(+ "Image content could not be displayed.".into(),+ language_registry,+ cx,+ ),+ }+ }+ }+ block @ (acp::ContentBlock::Text(_) | acp::ContentBlock::ResourceLink(_)) => {+ Self::new(block, language_registry, path_style, cx)+ }+ content => {+ let description = if matches!(&content, acp::ContentBlock::Audio(_)) {+ "Audio content is not supported."+ } else {+ "This content is not supported."+ };+ Self::Unsupported {+ content,+ markdown: Self::create_markdown(description.into(), language_registry, cx),+ }+ }}}@@ -1467,6 +1590,11 @@ impl ContentBlock {let combined = format!("`Image`\n{}", new_content);*self = Self::create_markdown_block(combined, language_registry, cx);}+ (ContentBlock::Unsupported { markdown, .. }, _) => {+ let new_content = Self::block_string_contents(&block, path_style);+ let combined = format!("{}\n{}", markdown.read(cx).source(), new_content);+ *self = Self::create_markdown_block(combined, language_registry, cx);+ }}}@@ -1601,7 +1729,9 @@ impl ContentBlock {pub fn text_content<'a>(&'a self, cx: &'a App) -> Option<&'a str> {match self {- ContentBlock::Markdown { markdown } => Some(markdown.read(cx).source()),+ ContentBlock::Markdown { markdown } | ContentBlock::Unsupported { markdown, .. } => {+ Some(markdown.read(cx).source())+ }ContentBlock::EmbeddedResource { resource, .. } => match &resource.resource {acp::EmbeddedResourceResource::TextResourceContents(text) => Some(&text.text),acp::EmbeddedResourceResource::BlobResourceContents(_) => None,@@ -1681,7 +1811,9 @@ impl ContentBlock {pub fn visible_content(&self, cx: &App) -> bool {match self {ContentBlock::Empty => false,- ContentBlock::Markdown { markdown } => !markdown.read(cx).source().trim().is_empty(),+ ContentBlock::Markdown { markdown } | ContentBlock::Unsupported { markdown, .. } => {+ !markdown.read(cx).source().trim().is_empty()+ }ContentBlock::EmbeddedResource { resource, markdown } => match markdown {Some(markdown) => !markdown.read(cx).source().trim().is_empty(),None => !Self::embedded_resource_text(resource).trim().is_empty(),@@ -1724,7 +1856,9 @@ impl ContentBlock {pub fn to_markdown<'a>(&'a self, cx: &'a App) -> &'a str {match self {ContentBlock::Empty => "",- ContentBlock::Markdown { markdown } => markdown.read(cx).source(),+ ContentBlock::Markdown { markdown } | ContentBlock::Unsupported { markdown, .. } => {+ markdown.read(cx).source()+ }ContentBlock::EmbeddedResource { resource, markdown } => {if let Some(markdown) = markdown {markdown.read(cx).source()@@ -1740,7 +1874,9 @@ impl ContentBlock {pub fn markdown(&self) -> Option<&Entity<Markdown>> {match self {ContentBlock::Empty => None,- ContentBlock::Markdown { markdown } => Some(markdown),+ ContentBlock::Markdown { markdown } | ContentBlock::Unsupported { markdown, .. } => {+ Some(markdown)+ }ContentBlock::EmbeddedResource { markdown, .. } => markdown.as_ref(),ContentBlock::ResourceLink { .. } => None,ContentBlock::Image { .. } => None,@@ -1833,14 +1969,14 @@ impl ToolCallContent {cx: &mut App,) -> Result<Option<Self>> {match content {- acp::ToolCallContent::Content(acp::Content { content, .. }) => Ok(Some(- Self::ContentBlock(ContentBlock::new_tool_call_content(+ acp::ToolCallContent::Content(acp::Content { content, .. }) => {+ Ok(Some(Self::ContentBlock(ContentBlock::new_output(content,&language_registry,path_style,cx,- )),- )),+ ))))+ }acp::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {Diff::finalized(diff.path.to_string_lossy().into_owned(),@@ -2450,7 +2586,7 @@ impl AcpThread {}pub fn is_compacting(&self) -> bool {- self.entries.last().is_some_and(|entry| {+ self.entries.iter().rev().any(|entry| {matches!(entry,AgentThreadEntry::ContextCompaction(compaction) if compaction.is_in_progress()@@ -2662,6 +2798,12 @@ impl AcpThread {acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {self.update_tool_call(tool_call_update, cx)?;}+ acp::SessionUpdate::CompactionUpdate(compaction_update) => {+ self.upsert_context_compaction_update(compaction_update, cx);+ }+ acp::SessionUpdate::CompactionSummaryChunk(summary_chunk) => {+ self.append_context_compaction_summary(summary_chunk, cx);+ }acp::SessionUpdate::Plan(plan) => {self.update_plan(plan, cx);}@@ -3080,12 +3222,76 @@ impl AcpThread {}}+ fn upsert_context_compaction_update(+ &mut self,+ update: acp::CompactionUpdate,+ cx: &mut Context<Self>,+ ) {+ let id = ContextCompactionId(update.compaction_id.0.clone());+ let language_registry = self.project.read(cx).languages().clone();+ let path_style = self.project.read(cx).path_style(cx);++ if let Some((entry_index, compaction)) =+ self.entries+ .iter_mut()+ .enumerate()+ .rev()+ .find_map(|(entry_index, entry)| match entry {+ AgentThreadEntry::ContextCompaction(compaction) if compaction.id == id => {+ Some((entry_index, compaction))+ }+ _ => None,+ })+ {+ compaction.apply_update(update, &language_registry, path_style, cx);+ cx.emit(AcpThreadEvent::EntryUpdated(entry_index));+ return;+ }++ let mut compaction = ContextCompaction {+ id,+ status: update.status.clone().into(),+ error: None,+ summary: Vec::new(),+ };+ compaction.apply_update(update, &language_registry, path_style, cx);+ self.push_entry(AgentThreadEntry::ContextCompaction(compaction), cx);+ }++ fn append_context_compaction_summary(+ &mut self,+ chunk: acp::CompactionSummaryChunk,+ cx: &mut Context<Self>,+ ) {+ let language_registry = self.project.read(cx).languages().clone();+ let path_style = self.project.read(cx).path_style(cx);+ if let Some((entry_index, compaction)) =+ self.entries+ .iter_mut()+ .enumerate()+ .rev()+ .find_map(|(entry_index, entry)| match entry {+ AgentThreadEntry::ContextCompaction(compaction)+ if compaction.id.0 == chunk.compaction_id.0+ && compaction.is_in_progress() =>+ {+ Some((entry_index, compaction))+ }+ _ => None,+ })+ {+ compaction.append_summary(chunk.content, &language_registry, path_style, cx);+ cx.emit(AcpThreadEvent::EntryUpdated(entry_index));+ }+ }+pub fn update_context_compaction(&mut self,update: ContextCompactionUpdate,cx: &mut Context<Self>,) {let language_registry = self.project.read(cx).languages().clone();+ let path_style = self.project.read(cx).path_style(cx);let Some((ix, compaction)) =self.entries.iter_mut()@@ -3100,20 +3306,12 @@ impl AcpThread {};if !update.summary_delta.is_empty() {- if compaction.summary.is_none() {- compaction.summary = Some(cx.new(|cx| {- Markdown::new(- update.summary_delta.into(),- Some(language_registry),- None,- cx,- )- }));- } else if let Some(summary) = compaction.summary.clone() {- summary.update(cx, |markdown, cx| {- markdown.append(&update.summary_delta, cx)- });- }+ compaction.append_summary(+ acp::ContentBlock::Text(acp::TextContent::new(update.summary_delta)),+ &language_registry,+ path_style,+ cx,+ );}if let Some(status) = update.status {@@ -5014,12 +5212,8 @@ mod tests {),));- let block = ContentBlock::new_tool_call_content(- content,- &language_registry,- PathStyle::local(),- cx,- );+ let block =+ ContentBlock::new_output(content, &language_registry, PathStyle::local(), cx);let ContentBlock::EmbeddedResource { resource, markdown } = &block else {panic!("expected embedded resource block, got {block:?}");@@ -5046,7 +5240,7 @@ mod tests {);assert_eq!(block.text_content(cx), Some("echo 'hello from exec test'"));- let untyped = ContentBlock::new_tool_call_content(+ let untyped = ContentBlock::new_output(acp::ContentBlock::Resource(acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new("# plain preview", "tool://preview"),@@ -5080,7 +5274,7 @@ mod tests {),));- let block = ContentBlock::new_tool_call_content(+ let block = ContentBlock::new_output(image_blob,&language_registry,PathStyle::local(),@@ -5116,12 +5310,8 @@ mod tests {),));- let block = ContentBlock::new_tool_call_content(- archive_blob,- &language_registry,- PathStyle::local(),- cx,- );+ let block =+ ContentBlock::new_output(archive_blob, &language_registry, PathStyle::local(), cx);let ContentBlock::EmbeddedResource { resource, markdown } = &block else {panic!("expected embedded resource block, got {block:?}");@@ -5143,7 +5333,7 @@ mod tests {.mime_type("image/png".to_string()),),));- let invalid = ContentBlock::new_tool_call_content(+ let invalid = ContentBlock::new_output(invalid_image_blob,&language_registry,PathStyle::local(),@@ -5994,7 +6184,8 @@ mod tests {ContextCompaction {id: ContextCompactionId("c1".into()),status: ContextCompactionStatus::Completed,- summary: None,+ error: None,+ summary: Vec::new(),},cx,);@@ -6457,6 +6648,385 @@ mod tests {});}+ #[gpui::test]+ async fn test_context_compaction_session_updates(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ let project = Project::test(fs, [], 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");++ thread.update(cx, |thread, cx| {+ for summary in ["retained context", "replacement summary"] {+ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionUpdate(+ acp::CompactionUpdate::new(+ "compaction",+ acp::CompactionStatus::Completed,+ )+ .summary(vec![acp::ContentBlock::Text(+ acp::TextContent::new(summary),+ )]),+ ),+ cx,+ )+ .expect("failed to set context compaction summary");+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.last()+ else {+ panic!("compaction entry must exist");+ };+ assert_eq!(compaction.status, ContextCompactionStatus::Completed);+ assert!(compaction.error.is_none());+ assert_eq!(+ compaction+ .summary+ .first()+ .map(|block| block.to_markdown(cx)),+ Some(summary)+ );+ assert_eq!(+ thread.to_markdown(cx),+ format!("## Context Compaction (Completed)\n\n{summary}\n\n")+ );+ }++ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionUpdate(+ acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Failed)+ .summary(None::<Vec<acp::ContentBlock>>)+ .error("model unavailable"),+ ),+ cx,+ )+ .expect("failed to record context compaction failure");+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.last()+ else {+ panic!("compaction entry must still exist");+ };+ assert_eq!(compaction.status, ContextCompactionStatus::Failed);+ assert!(compaction.summary.is_empty());+ assert_eq!(+ compaction+ .error+ .as_ref()+ .map(|error| error.read(cx).source().as_ref()),+ Some("model unavailable")+ );+ assert_eq!(+ thread.to_markdown(cx),+ "## Context Compaction (Failed)\n\n**Error:** model unavailable\n\n"+ );++ for error in [+ MaybeUndefined::Undefined,+ MaybeUndefined::Value("model *still* unavailable".to_string()),+ MaybeUndefined::Null,+ ] {+ let expected_error = match &error {+ MaybeUndefined::Undefined => Some("model unavailable".to_string()),+ MaybeUndefined::Value(error) => Some(error.clone()),+ MaybeUndefined::Null => None,+ };+ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionUpdate(+ acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Failed)+ .error(error),+ ),+ cx,+ )+ .expect("failed to patch compaction error");+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.last()+ else {+ panic!("compaction entry must still exist");+ };+ assert_eq!(+ compaction+ .error+ .as_ref()+ .map(|error| error.read(cx).source().to_string()),+ expected_error+ );+ if let Some(error) = expected_error {+ assert!(+ thread+ .to_markdown(cx)+ .contains(&format!("**Error:** {}", MarkdownEscaped(&error)))+ );+ }+ }++ for summary in [+ vec![acp::ContentBlock::Text(acp::TextContent::new(""))],+ Vec::new(),+ ] {+ let expected_length = summary.len();+ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionUpdate(+ acp::CompactionUpdate::new(+ "compaction",+ acp::CompactionStatus::Completed,+ )+ .summary(summary),+ ),+ cx,+ )+ .expect("failed to patch compaction summary");+ let Some(AgentThreadEntry::ContextCompaction(compaction)) = thread.entries.last()+ else {+ panic!("compaction entry must still exist");+ };+ assert_eq!(compaction.summary.len(), expected_length);+ }+ });+ }++ #[gpui::test]+ async fn test_context_compaction_preserves_summary_content(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 image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";+ let text_resource =+ acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(+ acp::TextResourceContents::new("Retained resource text", "summary://context")+ .mime_type("text/markdown".to_string()),+ ));+ let blob_resource =+ acp::EmbeddedResource::new(acp::EmbeddedResourceResource::BlobResourceContents(+ acp::BlobResourceContents::new("c3VtbWFyeQ==", "summary://attachment")+ .mime_type("application/octet-stream".to_string()),+ ));+ let audio = acp::ContentBlock::Audio(acp::AudioContent::new("YXVkaW8=", "audio/wav"));+ let blocks = vec![+ acp::ContentBlock::Text(acp::TextContent::new("retained ")),+ acp::ContentBlock::Text(acp::TextContent::new("context")),+ acp::ContentBlock::Resource(text_resource.clone()),+ acp::ContentBlock::Image(acp::ImageContent::new(image_data, "image/png")),+ acp::ContentBlock::ResourceLink(acp::ResourceLink::new(+ "Reference",+ "https://example.com/context",+ )),+ audio.clone(),+ acp::ContentBlock::Resource(blob_resource.clone()),+ ];++ thread.update(cx, |thread, cx| {+ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(+ "compaction",+ acp::CompactionStatus::InProgress,+ )),+ cx,+ )+ .expect("failed to start compaction");+ for block in &blocks {+ thread+ .handle_session_update(+ acp::SessionUpdate::CompactionSummaryChunk(+ acp::CompactionSummaryChunk::new("compaction", block.clone()),+ ),+ cx,+ )+ .expect("failed to append summary block");+ }+ });++ for replace_summary in [false, true] {+ thread.update(cx, |thread, cx| {+ let mut update =+ acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Completed);+ if replace_summary {+ update = update.summary(blocks.clone());+ }+ thread+ .handle_session_update(acp::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.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.resource_link().map(|link| link.uri.as_str()),+ Some("https://example.com/context")+ );+ let ContentBlock::Unsupported { content, .. } = unsupported else {+ panic!("expected preserved audio with a visible fallback");+ };+ assert_eq!(content, &audio);+ assert!(unsupported.visible_content(cx));+ assert_eq!(+ blob.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::SessionUpdate::CompactionUpdate(+ acp::CompactionUpdate::new("compaction", acp::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(),+ [ContentBlock::Unsupported { content, .. }] if content == &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::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(+ "first",+ acp::CompactionStatus::InProgress,+ )),+ acp::SessionUpdate::ToolCall(acp::ToolCall::new("tool", "Unrelated tool")),+ acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(+ "second",+ acp::CompactionStatus::InProgress,+ )),+ acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(+ "second",+ acp::CompactionStatus::Completed,+ )),+ acp::SessionUpdate::CompactionSummaryChunk(acp::CompactionSummaryChunk::new(+ "first",+ acp::ContentBlock::Text(acp::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::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(+ "first",+ acp::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")+ );+ });+ }+#[gpui::test]async fn test_tool_call_name_precedence_and_updates(cx: &mut TestAppContext) {init_test(cx);@@ -6599,6 +7169,31 @@ mod tests {});}+ #[gpui::test]+ fn test_context_compaction_exports_status(cx: &mut App) {+ for (status, expected_label) in [+ (acp::CompactionStatus::InProgress, "In Progress"),+ (acp::CompactionStatus::Completed, "Completed"),+ (acp::CompactionStatus::Failed, "Failed"),+ (acp::CompactionStatus::Cancelled, "Canceled"),+ (+ acp::CompactionStatus::Other("interrupted".into()),+ "interrupted",+ ),+ ] {+ let entry = AgentThreadEntry::ContextCompaction(ContextCompaction {+ id: ContextCompactionId("compaction".into()),+ status: status.into(),+ error: None,+ summary: Vec::new(),+ });+ assert_eq!(+ entry.to_markdown(cx),+ format!("## Context Compaction ({expected_label})\n\n")+ );+ }+ }+#[gpui::test]async fn test_tool_call_location_resolves_external_file(cx: &mut TestAppContext) {init_test(cx);@@ -9263,6 +9858,9 @@ mod tests {ContentBlock::Image { .. } => {panic!("Expected markdown content, got image")}+ ContentBlock::Unsupported { .. } => {+ panic!("Expected markdown content, got unsupported content")+ }}} else {panic!("Expected ContentBlock, got: {:?}", tool_call.content[0]);@@ -9905,7 +10503,8 @@ mod tests {ContextCompaction {id: compaction_id,status: ContextCompactionStatus::InProgress,- summary: None,+ error: None,+ summary: Vec::new(),},cx,);@@ -10273,7 +10872,8 @@ mod tests {ContextCompaction {id: ContextCompactionId("compaction-1".into()),status: ContextCompactionStatus::InProgress,- summary: None,+ error: None,+ summary: Vec::new(),},cx,);diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex 14b8c9882e6..96eea557c53 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -3874,8 +3874,8 @@ mod internal_tests {use indoc::formatdoc;use language_model::fake_provider::{FakeLanguageModel, FakeLanguageModelProvider};use language_model::{- CompletionIntent, LanguageModelCompletionEvent, LanguageModelProviderId,- LanguageModelProviderName,+ CompletionIntent, LanguageModelCompletionError, LanguageModelCompletionEvent,+ LanguageModelProviderId, LanguageModelProviderName,};use serde_json::json;use settings::SettingsStore;@@ -4084,6 +4084,10 @@ mod internal_tests {#[gpui::test]async fn test_compact_prompt_routes_to_manual_compaction(cx: &mut TestAppContext) {+ use feature_flags::{+ AcpBetaFeatureFlag, FeatureFlag as _, FeatureFlagAppExt as _, FeatureFlagsSettings,+ };+init_test(cx);let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());@@ -4092,6 +4096,16 @@ mod internal_tests {let old_message_id = ClientUserMessageId::new();cx.update(|cx| {+ cx.update_flags(true, Vec::new());+ FeatureFlagsSettings::override_global(+ FeatureFlagsSettings {+ overrides: HashMap::from_iter([(+ AcpBetaFeatureFlag::NAME.into(),+ "off".into(),+ )]),+ },+ cx,+ );let path_style = project.read(cx).path_style(cx);thread.update(cx, |thread, cx| {thread.set_model(model.clone(), cx);@@ -4107,6 +4121,7 @@ mod internal_tests {let compact_message_id = ClientUserMessageId::new();let prompt_task = cx.update(|cx| {+ assert!(!cx.has_flag::<AcpBetaFeatureFlag>());acp_thread::AgentSessionClientUserMessageIds::prompt(connection.as_ref(),compact_message_id,@@ -4130,10 +4145,434 @@ mod internal_tests {]);- model.send_completion_stream_text_chunk(&request, "summary");+ let compaction_id = acp_thread.read_with(cx, |thread, _| {+ let Some(acp_thread::AgentThreadEntry::ContextCompaction(compaction)) =+ thread.entries().last()+ else {+ panic!("native compaction should create an ACP-visible entry");+ };+ assert!(thread.is_compacting());+ assert!(compaction.is_in_progress());+ assert!(compaction.summary.is_empty());+ compaction.id.clone()+ });++ model.send_completion_stream_text_chunk(&request, "retained ");+ cx.run_until_parked();+ let summary = acp_thread.read_with(cx, |thread, cx| {+ let Some(acp_thread::AgentThreadEntry::ContextCompaction(compaction)) =+ thread.entries().last()+ else {+ panic!("native compaction entry should remain in the timeline");+ };+ assert_eq!(compaction.id, compaction_id);+ assert!(compaction.is_in_progress());+ let [acp_thread::ContentBlock::Markdown { markdown }] = compaction.summary.as_slice()+ else {+ panic!("native text chunks should create one retained Markdown block");+ };+ assert_eq!(markdown.read(cx).source().as_ref(), "retained ");+ markdown.clone()+ });+ model.send_completion_stream_text_chunk(&request, "context");model.end_completion_stream(&request);cx.run_until_parked();- prompt_task.await.unwrap();+ prompt_task+ .await+ .expect("native compaction should complete");+ acp_thread.read_with(cx, |thread, cx| {+ let Some(acp_thread::AgentThreadEntry::ContextCompaction(compaction)) =+ thread.entries().last()+ else {+ panic!("completed native compaction should remain in the timeline");+ };+ assert_eq!(compaction.id, compaction_id);+ assert!(!thread.is_compacting());+ assert_eq!(+ compaction.status,+ acp_thread::ContextCompactionStatus::Completed+ );+ assert!(compaction.error.is_none());+ assert_eq!(compaction.summary.len(), 1);+ assert_eq!(+ compaction+ .summary+ .first()+ .and_then(|block| block.markdown()),+ Some(&summary)+ );+ assert_eq!(summary.read(cx).source().as_ref(), "retained context");+ });++ agent.update(cx, |agent, cx| agent.save_thread(thread.clone(), cx));+ cx.run_until_parked();+ drop(thread);+ drop(acp_thread);+ release_dropped_entities(cx);+ agent.read_with(cx, |agent, _| {+ assert!(!agent.sessions.contains_key(&session_id));+ });+ let restored = cx+ .update(|cx| {+ connection.clone().load_session(+ session_id,+ project,+ PathList::new(&[Path::new("/a")]),+ None,+ cx,+ )+ })+ .await+ .expect("compacted native session should reload");+ cx.run_until_parked();+ restored.read_with(cx, |thread, cx| {+ let compactions = thread+ .entries()+ .iter()+ .filter_map(|entry| match entry {+ acp_thread::AgentThreadEntry::ContextCompaction(compaction) => Some(compaction),+ _ => None,+ })+ .collect::<Vec<_>>();+ let [compaction] = compactions.as_slice() else {+ panic!("replay should restore exactly one compaction");+ };+ assert_eq!(+ compaction.status,+ acp_thread::ContextCompactionStatus::Completed+ );+ assert!(!thread.is_compacting());+ assert_eq!(+ compaction+ .summary+ .first()+ .map(|block| block.to_markdown(cx)),+ Some("retained context")+ );+ });+ }++ #[gpui::test]+ async fn test_load_session_replays_provider_native_compaction(cx: &mut TestAppContext) {+ init_test(cx);+ let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;+ let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));+ let mut saved_thread = thread.read_with(cx, |thread, cx| thread.to_db(cx)).await;+ saved_thread.messages.push(Arc::new(Message::Compaction(+ CompactionInfo::ProviderNative {+ provider: LanguageModelProviderId::from("openai".to_string()),+ items: vec![json!({"type": "compaction", "encrypted_content": "opaque state"})],+ },+ )));+ let restored_session_id = acp::SessionId::new("provider-native-compaction");+ let database = cx+ .update(|cx| ThreadsDatabase::connect(cx))+ .await+ .expect("thread database should connect");+ database+ .save_thread(+ restored_session_id.clone(),+ saved_thread,+ PathList::new(&[Path::new("/a")]),+ )+ .await+ .expect("provider-native compaction should save");++ let restored = cx+ .update(|cx| {+ connection.load_session(+ restored_session_id,+ project,+ PathList::new(&[Path::new("/a")]),+ None,+ cx,+ )+ })+ .await+ .expect("provider-native compaction should load");+ cx.run_until_parked();+ restored.read_with(cx, |thread, _| {+ let Some(acp_thread::AgentThreadEntry::ContextCompaction(compaction)) =+ thread.entries().last()+ else {+ panic!("provider-native replay should create a compaction entry");+ };+ assert_eq!(+ compaction.status,+ acp_thread::ContextCompactionStatus::Completed+ );+ assert!(compaction.summary.is_empty());+ assert!(compaction.error.is_none());+ assert!(!thread.is_compacting());+ });+ }++ #[gpui::test]+ async fn test_retried_auto_compaction_terminalizes_each_attempt(cx: &mut TestAppContext) {+ init_test(cx);+ let (connection, agent, _project, acp_thread) = setup_native_agent_session(cx).await;+ let session_id = cx.update(|cx| acp_thread.read(cx).session_id().clone());+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));+ let model = Arc::new(FakeLanguageModel::default());+ model.set_max_token_count(1_000_000);++ cx.update(|cx| {+ let mut settings = agent_settings::AgentSettings::get_global(cx).clone();+ settings.auto_compact = agent_settings::AutoCompactSettings {+ enabled: true,+ threshold: agent_settings::AutoCompactThreshold::Percentage(0.5),+ };+ agent_settings::AgentSettings::override_global(settings, cx);+ thread.update(cx, |thread, cx| thread.set_model(model.clone(), cx));+ });++ let first_prompt = cx.update(|cx| {+ acp_thread::AgentSessionClientUserMessageIds::prompt(+ connection.as_ref(),+ ClientUserMessageId::new(),+ acp::PromptRequest::new(session_id.clone(), vec!["old user".into()]),+ cx,+ )+ });+ cx.run_until_parked();++ let first_request = model+ .pending_completions()+ .pop()+ .expect("first user prompt should start a model request");+ model.send_completion_stream_event(+ &first_request,+ LanguageModelCompletionEvent::UsageUpdate(language_model::TokenUsage {+ input_tokens: 750_000,+ ..Default::default()+ }),+ );+ model.send_completion_stream_text_chunk(&first_request, "old assistant");+ model.end_completion_stream(&first_request);+ cx.run_until_parked();+ first_prompt+ .await+ .expect("first user prompt should complete");++ let second_prompt = cx.update(|cx| {+ acp_thread::AgentSessionClientUserMessageIds::prompt(+ connection.as_ref(),+ ClientUserMessageId::new(),+ acp::PromptRequest::new(session_id, vec!["new user".into()]),+ cx,+ )+ });+ cx.run_until_parked();++ let first_compaction_request = model+ .pending_completions()+ .pop()+ .expect("token threshold should start automatic compaction");+ assert_eq!(+ first_compaction_request.intent,+ Some(CompletionIntent::ThreadContextSummarization)+ );+ model.send_completion_stream_error(+ &first_compaction_request,+ LanguageModelCompletionError::from_provider_response(+ language_model::ANTHROPIC_PROVIDER_NAME,+ None,+ Some("rate_limit_error".to_string()),+ "Rate limit exceeded".to_string(),+ Some(Duration::ZERO),+ language_model::ProviderErrorCategory::RateLimit,+ ),+ );+ model.end_completion_stream(&first_compaction_request);+ cx.run_until_parked();++ let second_compaction_request = model+ .pending_completions()+ .pop()+ .expect("retryable error should start another compaction attempt");+ assert_eq!(+ second_compaction_request.intent,+ Some(CompletionIntent::ThreadContextSummarization)+ );+ acp_thread.read_with(cx, |thread, _cx| {+ let statuses = thread+ .entries()+ .iter()+ .filter_map(|entry| match entry {+ acp_thread::AgentThreadEntry::ContextCompaction(compaction) => {+ Some(compaction.status.clone())+ }+ _ => None,+ })+ .collect::<Vec<_>>();+ assert_eq!(+ statuses,+ [+ acp_thread::ContextCompactionStatus::Failed,+ acp_thread::ContextCompactionStatus::InProgress,+ ]+ );+ assert!(thread.is_compacting());+ });++ model.send_completion_stream_text_chunk(&second_compaction_request, "summary");+ model.end_completion_stream(&second_compaction_request);+ cx.run_until_parked();++ acp_thread.read_with(cx, |thread, _cx| {+ let statuses = thread+ .entries()+ .iter()+ .filter_map(|entry| match entry {+ acp_thread::AgentThreadEntry::ContextCompaction(compaction) => {+ Some(compaction.status.clone())+ }+ _ => None,+ })+ .collect::<Vec<_>>();+ assert_eq!(+ statuses,+ [+ acp_thread::ContextCompactionStatus::Failed,+ acp_thread::ContextCompactionStatus::Completed,+ ]+ );+ assert!(+ !thread.is_compacting(),+ "a successful retry must not leave an older attempt in progress"+ );+ });++ let final_request = model+ .pending_completions()+ .pop()+ .expect("successful compaction should continue the user turn");+ assert_eq!(final_request.intent, Some(CompletionIntent::UserPrompt));+ model.send_completion_stream_text_chunk(&final_request, "new assistant");+ model.end_completion_stream(&final_request);+ cx.run_until_parked();+ second_prompt+ .await+ .expect("user prompt should complete after the compaction retry");+ }++ #[gpui::test]+ async fn test_native_compaction_cancellation_is_bridged_before_stop(cx: &mut TestAppContext) {+ init_test(cx);++ for (scenario, cancel_before_first_poll, partial_summary) in [+ ("before first poll", true, None),+ ("after initial update", false, None),+ (+ "after partial summary",+ false,+ Some("retained partial summary"),+ ),+ ] {+ let (connection, agent, project, acp_thread) = setup_native_agent_session(cx).await;+ let session_id = acp_thread.read_with(cx, |thread, _| thread.session_id().clone());+ let thread = cx.update(|cx| native_thread_for_session(&agent, &session_id, cx));+ let model = Arc::new(FakeLanguageModel::default());++ cx.update(|cx| {+ let path_style = project.read(cx).path_style(cx);+ thread.update(cx, |thread, cx| {+ thread.set_model(model.clone(), cx);+ thread.push_acp_user_block(+ ClientUserMessageId::new(),+ [acp::ContentBlock::from("old user")],+ path_style,+ cx,+ );+ thread.push_acp_agent_block("old assistant".into(), cx);+ });+ });++ let (response_stream, cancellation_task) = if cancel_before_first_poll {+ thread.update(cx, |thread, cx| {+ let response_stream = thread+ .compact(ClientUserMessageId::new(), cx)+ .expect("manual compaction should start");+ let cancellation_task = thread.cancel(cx);+ (response_stream, cancellation_task)+ })+ } else {+ let response_stream = thread+ .update(cx, |thread, cx| {+ thread.compact(ClientUserMessageId::new(), cx)+ })+ .expect("manual compaction should start");+ cx.run_until_parked();++ let request = model+ .pending_completions()+ .pop()+ .expect("manual compaction should reach the model");+ if let Some(partial_summary) = partial_summary {+ model.send_completion_stream_text_chunk(&request, partial_summary);+ cx.run_until_parked();+ }++ let cancellation_task = thread.update(cx, |thread, cx| thread.cancel(cx));+ (response_stream, cancellation_task)+ };+ cancellation_task.await;++ let response = cx+ .update(|cx| {+ NativeAgentConnection::handle_thread_events(+ response_stream,+ acp_thread.downgrade(),+ Some(connection.as_ref().clone()),+ cx,+ )+ })+ .await+ .expect("canceled compaction events should be bridged");+ assert_eq!(+ response.stop_reason,+ acp::StopReason::Cancelled,+ "{scenario}"+ );++ acp_thread.read_with(cx, |thread, cx| {+ let compactions = thread+ .entries()+ .iter()+ .filter_map(|entry| match entry {+ acp_thread::AgentThreadEntry::ContextCompaction(compaction) => {+ Some(compaction)+ }+ _ => None,+ })+ .collect::<Vec<_>>();++ if cancel_before_first_poll {+ assert!(+ compactions.is_empty(),+ "{scenario}: cancellation before the task's first poll must not create a late compaction"+ );+ assert!(!thread.is_compacting(), "{scenario}");+ return;+ }++ let [compaction] = compactions.as_slice() else {+ panic!("{scenario}: expected exactly one visible compaction");+ };+ assert_eq!(+ compaction.status,+ acp_thread::ContextCompactionStatus::Canceled,+ "{scenario}"+ );+ assert!(!thread.is_compacting(), "{scenario}");+ assert_eq!(+ compaction.summary.first().map(|block| block.to_markdown(cx)),+ partial_summary,+ "{scenario}"+ );+ });+ }}#[gpui::test]diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex 7afb710d2d7..a1a5409ee1c 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -267,7 +267,12 @@ impl Message {Message::User(message) => message.to_markdown(),Message::Agent(message) => message.to_markdown(),Message::Resume => "[resume]\n".into(),- Message::Compaction(_) => "--- Context Compacted ---\n".into(),+ Message::Compaction(CompactionInfo::Summary(summary)) => {+ format!("## Context Compaction (Completed)\n\n{summary}\n\n")+ }+ Message::Compaction(CompactionInfo::ProviderNative { .. }) => {+ "## Context Compaction (Completed)\n\n".into()+ }}}@@ -1532,7 +1537,7 @@ impl Thread {cx: &mut Context<Self>,) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {let (tx, rx) = mpsc::unbounded();- let stream = ThreadEventStream(tx);+ let stream = ThreadEventStream::new(tx);for (message_ix, message) in self.messages.iter().enumerate() {match &**message {Message::User(user_message) => stream.send_user_message(user_message),@@ -1637,7 +1642,7 @@ impl Thread {// We need to send both ToolCall and ToolCallUpdate events because the UI// only converts raw_output to displayable content in update_fields, not from_acp.stream- .0+ .sender.unbounded_send(Ok(ThreadEvent::ToolCall(acp::ToolCall::new(tool_call_id.clone(), tool_use.name.to_string()).name(tool_use.name.to_string())@@ -2589,7 +2594,7 @@ impl Thread {cx.notify();let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();- let event_stream = ThreadEventStream(events_tx);+ let event_stream = ThreadEventStream::new(events_tx);let (cancellation_tx, mut cancellation_rx) = watch::channel(false);let task = cx.spawn({let event_stream = event_stream.clone();@@ -2698,7 +2703,7 @@ impl Thread {self.cancel(cx).detach();let (events_tx, events_rx) = mpsc::unbounded::<Result<ThreadEvent>>();- let event_stream = ThreadEventStream(events_tx);+ let event_stream = ThreadEventStream::new(events_tx);let message_ix = self.messages.len().saturating_sub(1);self.clear_summary();let tools = self.enabled_tools(cx);@@ -3176,103 +3181,119 @@ impl Thread {insertion: CompactionInsertion,cx: &mut AsyncApp,) -> Result<ControlFlow<()>> {+ if *cancellation_rx.borrow() {+ return Ok(ControlFlow::Break(()));+ }+log::debug!("Running compaction");let compaction_id = acp_thread::ContextCompactionId(Uuid::new_v4().to_string().into());event_stream.send_context_compaction(compaction_id.clone(),acp_thread::ContextCompactionStatus::InProgress,);- let stream = futures::select! {- result = model.stream_completion(request, cx).fuse() => result,- _ = cancellation_rx.changed().fuse() => {- if *cancellation_rx.borrow() {- log::debug!("Compaction cancelled before request started");- return Ok(ControlFlow::Break(()));- }- return Ok(ControlFlow::Continue(()));- }- };- let mut stream = stream?;-- let mut summary = String::new();- loop {- let event = futures::select! {- event = stream.next().fuse() => event,+ let result: Result<ControlFlow<()>> = async {+ let stream = futures::select! {+ result = model.stream_completion(request, cx).fuse() => result,_ = cancellation_rx.changed().fuse() => {if *cancellation_rx.borrow() {- log::debug!("Compaction cancelled while summarizing");+ log::debug!("Compaction cancelled before request started");return Ok(ControlFlow::Break(()));}- continue;+ return Ok(ControlFlow::Continue(()));}};+ let mut stream = stream?;- let Some(event) = event else {- break;- };+ let mut summary = String::new();+ loop {+ let event = futures::select! {+ event = stream.next().fuse() => event,+ _ = cancellation_rx.changed().fuse() => {+ if *cancellation_rx.borrow() {+ log::debug!("Compaction cancelled while summarizing");+ return Ok(ControlFlow::Break(()));+ }+ continue;+ }+ };- match event? {- LanguageModelCompletionEvent::Text(text) => {- summary.push_str(&text);- event_stream.send_context_compaction_update(compaction_id.clone(), &text);- }- LanguageModelCompletionEvent::UsageUpdate(usage) => {- this.update(cx, |this, _cx| {- this.accumulate_token_usage(usage);- })?;+ let Some(event) = event else {+ break;+ };++ match event? {+ LanguageModelCompletionEvent::Text(text) => {+ summary.push_str(&text);+ event_stream.send_context_compaction_update(compaction_id.clone(), &text);+ }+ LanguageModelCompletionEvent::UsageUpdate(usage) => {+ this.update(cx, |this, _cx| {+ this.accumulate_token_usage(usage);+ })?;+ }+ LanguageModelCompletionEvent::Stop(_)+ | LanguageModelCompletionEvent::Started+ | LanguageModelCompletionEvent::Queued { .. }+ | LanguageModelCompletionEvent::Thinking { .. }+ | LanguageModelCompletionEvent::RedactedThinking { .. }+ | LanguageModelCompletionEvent::ReasoningDetails(_)+ | LanguageModelCompletionEvent::ToolUse(_)+ | LanguageModelCompletionEvent::ToolUseJsonParseError { .. }+ | LanguageModelCompletionEvent::StartMessage { .. }+ | LanguageModelCompletionEvent::Compaction(_) => {}}- LanguageModelCompletionEvent::Stop(_)- | LanguageModelCompletionEvent::Started- | LanguageModelCompletionEvent::Queued { .. }- | LanguageModelCompletionEvent::Thinking { .. }- | LanguageModelCompletionEvent::RedactedThinking { .. }- | LanguageModelCompletionEvent::ReasoningDetails(_)- | LanguageModelCompletionEvent::ToolUse(_)- | LanguageModelCompletionEvent::ToolUseJsonParseError { .. }- | LanguageModelCompletionEvent::StartMessage { .. }- | LanguageModelCompletionEvent::Compaction(_) => {}}- }- if *cancellation_rx.borrow() {- log::debug!("Compaction cancelled after summarizing");- return Ok(ControlFlow::Break(()));- }+ if *cancellation_rx.borrow() {+ log::debug!("Compaction cancelled after summarizing");+ return Ok(ControlFlow::Break(()));+ }- let summary = summary.trim().to_string();- if summary.is_empty() {- log::warn!("Compaction produced an empty summary");- return Err(anyhow::anyhow!("Compaction produced an empty summary"));- }+ let summary = summary.trim().to_string();+ if summary.is_empty() {+ log::warn!("Compaction produced an empty summary");+ return Err(anyhow::anyhow!("Compaction produced an empty summary"));+ }- log::debug!("Compaction succeeded:\n{summary}");- event_stream.update_context_compaction_status(- compaction_id,- acp_thread::ContextCompactionStatus::Completed,- );+ log::debug!("Compaction succeeded:\n{summary}");+ event_stream.update_context_compaction_status(+ compaction_id.clone(),+ acp_thread::ContextCompactionStatus::Completed,+ );- this.update(cx, |this, cx| {- let compaction = Arc::new(Message::Compaction(CompactionInfo::Summary(summary.into())));- match insertion {- CompactionInsertion::Auto { insertion_ix } => {- if insertion_ix <= this.messages.len() {- this.messages.insert(insertion_ix, compaction);- } else {+ this.update(cx, |this, cx| {+ let compaction =+ Arc::new(Message::Compaction(CompactionInfo::Summary(summary.into())));+ match insertion {+ CompactionInsertion::Auto { insertion_ix } => {+ if insertion_ix <= this.messages.len() {+ this.messages.insert(insertion_ix, compaction);+ } else {+ this.messages.push(compaction);+ }+ }+ CompactionInsertion::Manual { marker_id } => {+ this.messages.push(Arc::new(Message::User(UserMessage {+ id: marker_id,+ content: Arc::from([]),+ })));this.messages.push(compaction);}}- CompactionInsertion::Manual { marker_id } => {- this.messages.push(Arc::new(Message::User(UserMessage {- id: marker_id,- content: Arc::from([]),- })));- this.messages.push(compaction);- }- }- cx.notify();- })?;+ cx.notify();+ })?;- Ok(ControlFlow::Continue(()))+ Ok(ControlFlow::Continue(()))+ }+ .await;++ if result.is_err() {+ event_stream.update_context_compaction_status(+ compaction_id,+ acp_thread::ContextCompactionStatus::Failed,+ );+ }+ result}fn process_tool_result(@@ -5276,23 +5297,33 @@ pub(crate) fn scoped_tool_call_id(}#[derive(Clone)]-struct ThreadEventStream(mpsc::UnboundedSender<Result<ThreadEvent>>);+struct ThreadEventStream {+ sender: mpsc::UnboundedSender<Result<ThreadEvent>>,+ active_compaction: Rc<RefCell<Option<acp_thread::ContextCompactionId>>>,+}impl ThreadEventStream {+ fn new(sender: mpsc::UnboundedSender<Result<ThreadEvent>>) -> Self {+ Self {+ sender,+ active_compaction: Rc::default(),+ }+ }+fn send_user_message(&self, message: &UserMessage) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::UserMessage(message.clone()))).ok();}fn send_text(&self, text: &str) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::AgentText(text.to_string()))).ok();}fn send_thinking(&self, text: &str) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::AgentThinking(text.to_string()))).ok();}@@ -5305,7 +5336,7 @@ impl ThreadEventStream {kind: acp::ToolKind,input: serde_json::Value,) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::ToolCall(Self::initial_tool_call(id,tool_name,@@ -5335,7 +5366,7 @@ impl ThreadEventStream {fields: acp::ToolCallUpdateFields,meta: Option<acp::Meta>,) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::ToolCallUpdate(acp::ToolCallUpdate::new(tool_call_id.clone(), fields).meta(meta)@@ -5349,7 +5380,7 @@ impl ThreadEventStream {tool_call_id: &acp::ToolCallId,outcome: acp_thread::SelectedPermissionOutcome,) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::ToolCallAuthorizationResolved {tool_call_id: tool_call_id.clone(),outcome,@@ -5358,7 +5389,9 @@ impl ThreadEventStream {}fn send_retry(&self, status: acp_thread::RetryStatus) {- self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();+ self.sender+ .unbounded_send(Ok(ThreadEvent::Retry(status)))+ .ok();}fn send_context_compaction(@@ -5366,12 +5399,16 @@ impl ThreadEventStream {id: acp_thread::ContextCompactionId,status: acp_thread::ContextCompactionStatus,) {- self.0+ if status == acp_thread::ContextCompactionStatus::InProgress {+ self.active_compaction.replace(Some(id.clone()));+ }+ self.sender.unbounded_send(Ok(ThreadEvent::ContextCompaction(acp_thread::ContextCompaction {id,status,- summary: None,+ error: None,+ summary: Vec::new(),},))).ok();@@ -5382,7 +5419,7 @@ impl ThreadEventStream {id: acp_thread::ContextCompactionId,summary_delta: &str,) {- self.0+ self.sender.unbounded_send(Ok(ThreadEvent::ContextCompactionUpdate(acp_thread::ContextCompactionUpdate {id,@@ -5398,7 +5435,12 @@ impl ThreadEventStream {id: acp_thread::ContextCompactionId,status: acp_thread::ContextCompactionStatus,) {- self.0+ if status != acp_thread::ContextCompactionStatus::InProgress+ && self.active_compaction.borrow().as_ref() == Some(&id)+ {+ self.active_compaction.replace(None);+ }+ self.sender.unbounded_send(Ok(ThreadEvent::ContextCompactionUpdate(acp_thread::ContextCompactionUpdate {id,@@ -5410,17 +5452,26 @@ impl ThreadEventStream {}fn send_stop(&self, reason: acp::StopReason) {- self.0.unbounded_send(Ok(ThreadEvent::Stop(reason))).ok();+ self.sender+ .unbounded_send(Ok(ThreadEvent::Stop(reason)))+ .ok();}fn send_canceled(&self) {- self.0- .unbounded_send(Ok(ThreadEvent::Stop(acp::StopReason::Cancelled)))- .ok();+ // The bridge stops consuming at Stop, and its entry cancellation scan+ // may have run before the queued compaction-start event was applied.+ let compaction_id = self.active_compaction.replace(None);+ if let Some(compaction_id) = compaction_id {+ self.update_context_compaction_status(+ compaction_id,+ acp_thread::ContextCompactionStatus::Canceled,+ );+ }+ self.send_stop(acp::StopReason::Cancelled);}fn send_error(&self, error: impl Into<anyhow::Error>) {- self.0.unbounded_send(Err(error.into())).ok();+ self.sender.unbounded_send(Err(error.into())).ok();}}@@ -5480,7 +5531,7 @@ impl ToolCallEventStream {let stream = ToolCallEventStream::new("test_id".into(),acp::ToolCallId::new("0:test_id"),- ThreadEventStream(events_tx),+ ThreadEventStream::new(events_tx),None,cancellation_rx,sandbox_grants,@@ -5501,7 +5552,7 @@ impl ToolCallEventStream {let stream = ToolCallEventStream::new("test_id".into(),acp::ToolCallId::new("0:test_id"),- ThreadEventStream(events_tx),+ ThreadEventStream::new(events_tx),None,cancellation_rx,Rc::new(RefCell::new(ThreadSandboxGrants::default())),@@ -5614,7 +5665,7 @@ impl ToolCallEventStream {pub fn update_diff(&self, diff: Entity<acp_thread::Diff>) {self.stream- .0+ .sender.unbounded_send(Ok(ThreadEvent::ToolCallUpdate(acp_thread::ToolCallUpdateDiff {id: self.tool_call_id.clone(),@@ -5627,7 +5678,7 @@ impl ToolCallEventStream {pub fn subagent_spawned(&self, id: acp::SessionId) {self.stream- .0+ .sender.unbounded_send(Ok(ThreadEvent::SubagentSpawned(id))).ok();}@@ -5825,25 +5876,28 @@ impl ToolCallEventStream {};cx.spawn(async move |cx| {let (response_tx, mut response_rx) = oneshot::channel();- if let Err(error) = stream- .0- .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(- ToolCallAuthorization {- tool_call: acp::ToolCallUpdate::new(- tool_call_id.clone(),- // Leave the title untouched so the card keeps- // showing the command (matching the fallback flow).- acp::ToolCallUpdateFields::new(),- )- .meta(acp_thread::meta_with_sandbox_authorization(- sandbox_authorization_details,- )),- options,- response: response_tx,- context: None,- kind: acp_thread::AuthorizationKind::PermissionGrant,- },- )))+ if let Err(error) =+ stream+ .sender+ .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(+ ToolCallAuthorization {+ tool_call: acp::ToolCallUpdate::new(+ tool_call_id.clone(),+ // Leave the title untouched so the card keeps+ // showing the command (matching the fallback flow).+ acp::ToolCallUpdateFields::new(),+ )+ .meta(+ acp_thread::meta_with_sandbox_authorization(+ sandbox_authorization_details,+ ),+ ),+ options,+ response: response_tx,+ context: None,+ kind: acp_thread::AuthorizationKind::PermissionGrant,+ },+ ))){log::error!("Failed to send sandbox authorization: {error}");return Err(anyhow!("Failed to send sandbox authorization: {error}"));@@ -5942,24 +5996,25 @@ impl ToolCallEventStream {let tool_call_id = self.tool_call_id.clone();cx.spawn(async move |_cx| {let (response_tx, response_rx) = oneshot::channel();- if let Err(error) = stream- .0- .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(- ToolCallAuthorization {- tool_call: acp::ToolCallUpdate::new(- tool_call_id,- // Leave the title untouched so the card keeps- // showing the command (matching the escalation- // flow).- acp::ToolCallUpdateFields::new(),- )- .meta(acp_thread::meta_with_sandbox_authorization(details)),- options,- response: response_tx,- context: None,- kind: acp_thread::AuthorizationKind::PermissionGrant,- },- )))+ if let Err(error) =+ stream+ .sender+ .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(+ ToolCallAuthorization {+ tool_call: acp::ToolCallUpdate::new(+ tool_call_id,+ // Leave the title untouched so the card keeps+ // showing the command (matching the escalation+ // flow).+ acp::ToolCallUpdateFields::new(),+ )+ .meta(acp_thread::meta_with_sandbox_authorization(details)),+ options,+ response: response_tx,+ context: None,+ kind: acp_thread::AuthorizationKind::PermissionGrant,+ },+ ))){log::error!("Failed to send Windows-drive sandbox warning: {error}");return Err(anyhow!(@@ -6214,28 +6269,29 @@ impl ToolCallEventStream {let thread = self.thread.clone();cx.spawn(async move |cx| {let (response_tx, response_rx) = oneshot::channel();- if let Err(error) = stream- .0- .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(- ToolCallAuthorization {- // Deliberately leave the tool-call title untouched so- // the card keeps showing the *command* (not the- // failure reason): it's critical the user can see what- // they're approving to run unsandboxed. The reason is- // surfaced separately by the fallback details / warning.- tool_call: acp::ToolCallUpdate::new(- tool_call_id.clone(),- acp::ToolCallUpdateFields::new(),- )- .meta(- acp_thread::meta_with_sandbox_fallback_authorization(details),- ),- options,- response: response_tx,- context: None,- kind: acp_thread::AuthorizationKind::ActionChoice,- },- )))+ if let Err(error) =+ stream+ .sender+ .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(+ ToolCallAuthorization {+ // Deliberately leave the tool-call title untouched so+ // the card keeps showing the *command* (not the+ // failure reason): it's critical the user can see what+ // they're approving to run unsandboxed. The reason is+ // surfaced separately by the fallback details / warning.+ tool_call: acp::ToolCallUpdate::new(+ tool_call_id.clone(),+ acp::ToolCallUpdateFields::new(),+ )+ .meta(+ acp_thread::meta_with_sandbox_fallback_authorization(details),+ ),+ options,+ response: response_tx,+ context: None,+ kind: acp_thread::AuthorizationKind::ActionChoice,+ },+ ))){log::error!("Failed to send sandbox fallback authorization: {error}");return Err(anyhow!(@@ -6327,17 +6383,18 @@ impl ToolCallEventStream {}let (response_tx, response_rx) = oneshot::channel();- if let Err(error) = stream- .0- .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(- ToolCallAuthorization {- tool_call: acp::ToolCallUpdate::new(tool_call_id.clone(), fields),- options,- response: response_tx,- context: None,- kind: acp_thread::AuthorizationKind::ActionChoice,- },- )))+ if let Err(error) =+ stream+ .sender+ .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(+ ToolCallAuthorization {+ tool_call: acp::ToolCallUpdate::new(tool_call_id.clone(), fields),+ options,+ response: response_tx,+ context: None,+ kind: acp_thread::AuthorizationKind::ActionChoice,+ },+ ))){log::error!("Failed to send tool call decision prompt: {error}");return Err(anyhow!("Failed to send tool call decision prompt: {error}"));@@ -6370,7 +6427,7 @@ impl ToolCallEventStream {let (response_tx, response_rx) = oneshot::channel();if let Err(error) =stream- .0+ .sender.unbounded_send(Ok(ThreadEvent::Elicitation(ElicitationRequest {tool_call_id,message,@@ -6435,20 +6492,21 @@ impl ToolCallEventStream {};cx.spawn(async move |cx| {let (response_tx, mut response_rx) = oneshot::channel();- if let Err(error) = stream- .0- .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(- ToolCallAuthorization {- tool_call: acp::ToolCallUpdate::new(- tool_call_id.clone(),- acp::ToolCallUpdateFields::new().title(title),- ),- options,- response: response_tx,- context,- kind: acp_thread::AuthorizationKind::PermissionGrant,- },- )))+ if let Err(error) =+ stream+ .sender+ .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization(+ ToolCallAuthorization {+ tool_call: acp::ToolCallUpdate::new(+ tool_call_id.clone(),+ acp::ToolCallUpdateFields::new().title(title),+ ),+ options,+ response: response_tx,+ context,+ kind: acp_thread::AuthorizationKind::PermissionGrant,+ },+ ))){log::error!("Failed to send tool call authorization: {error}");return Err(anyhow!("Failed to send tool call authorization: {error}"));@@ -6854,7 +6912,7 @@ mod tests {});let (event_tx, _event_rx) = mpsc::unbounded();- let event_stream = ThreadEventStream(event_tx);+ let event_stream = ThreadEventStream::new(event_tx);(thread, event_stream)})@@ -6884,7 +6942,10 @@ mod tests {let message = Message::Compaction(CompactionInfo::Summary("Older context".into()));assert_eq!(message.role(), Role::User);- assert_eq!(message.to_markdown(), "--- Context Compacted ---\n");+ assert_eq!(+ message.to_markdown(),+ "## Context Compaction (Completed)\n\nOlder context\n\n"+ );let request_messages = message.to_request();assert_eq!(request_messages.len(), 1);diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 30f37fa0766..81f099bf09d 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -11,6 +11,7 @@ use agent_client_protocol::{Agent, Client, ConnectionTo, JsonRpcResponse, Lines,use anyhow::anyhow;use async_channel;use collections::{HashMap, HashSet};+use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _};use futures::channel::mpsc;use futures::future::Shared;use futures::io::BufReader;@@ -749,7 +750,10 @@ fn connect_client_future()}-fn client_capabilities_for_agent(agent_id: &AgentId) -> acp::ClientCapabilities {+fn client_capabilities_for_agent(+ agent_id: &AgentId,+ beta_features_enabled: bool,+) -> acp::ClientCapabilities {let mut meta = acp::Meta::from_iter([("terminal_output".into(), true.into()),("terminal-auth".into(), true.into()),@@ -759,18 +763,21 @@ fn client_capabilities_for_agent(agent_id: &AgentId) -> acp::ClientCapabilitiesmeta.insert(PARAMETERIZED_MODEL_PICKER_META_KEY.into(), true.into());}+ let mut session_capabilities = acp::ClientSessionCapabilities::new().config_options(+ acp::SessionConfigOptionsCapabilities::new()+ .boolean(acp::BooleanConfigOptionCapabilities::new()),+ );+ if beta_features_enabled {+ session_capabilities = session_capabilities.compaction(acp::CompactionCapabilities::new());+ }+acp::ClientCapabilities::new().fs(acp::FileSystemCapabilities::new().read_text_file(true).write_text_file(true)).terminal(true).auth(acp::AuthCapabilities::new().terminal(true))- .session(- acp::ClientSessionCapabilities::new().config_options(- acp::SessionConfigOptionsCapabilities::new()- .boolean(acp::BooleanConfigOptionCapabilities::new()),- ),- )+ .session(session_capabilities).elicitation(acp::ElicitationCapabilities::new().form(acp::ElicitationFormCapabilities::new())@@ -961,10 +968,14 @@ impl AcpConnection {}});+ let beta_features_enabled = cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>());let initialize_response = connection.send_request(acp::InitializeRequest::new(ProtocolVersion::V1)- .client_capabilities(client_capabilities_for_agent(&agent_id))+ .client_capabilities(client_capabilities_for_agent(+ &agent_id,+ beta_features_enabled,+ )).client_info(acp::Implementation::new("zed", version).title(release_channel.map(ToOwned::to_owned)),@@ -2632,7 +2643,7 @@ mod tests {use std::sync::atomic::{AtomicUsize, Ordering};use super::*;- use feature_flags::{AcpBetaFeatureFlag, FeatureFlag as _, FeatureFlagAppExt as _};+ use feature_flags::{AcpBetaFeatureFlag, FeatureFlag as _};use settings::Settings as _;fn init_feature_flags_test(cx: &mut gpui::TestAppContext) {@@ -2649,7 +2660,7 @@ mod tests {cx: &mut gpui::TestAppContext,) {init_feature_flags_test(cx);- let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"));+ let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"), false);let elicitation = capabilities.elicitation.expect("elicitation should always be advertised");@@ -2942,7 +2953,7 @@ mod tests {#[test]fn cursor_client_capabilities_include_parameterized_model_picker_meta() {- let capabilities = client_capabilities_for_agent(&AgentId::new(CURSOR_ID));+ let capabilities = client_capabilities_for_agent(&AgentId::new(CURSOR_ID), false);let meta = capabilities.meta.expect("expected client capabilities meta");@@ -2957,7 +2968,7 @@ mod tests {#[test]fn non_cursor_client_capabilities_do_not_include_parameterized_model_picker_meta() {- let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"));+ let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"), false);let meta = capabilities.meta.expect("expected client capabilities meta");@@ -2967,7 +2978,7 @@ mod tests {#[test]fn client_capabilities_include_boolean_config_options() {- let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"));+ let capabilities = client_capabilities_for_agent(&AgentId::new("codex-acp"), false);assert!(capabilities@@ -2978,6 +2989,22 @@ mod tests {);}+ #[test]+ fn client_capabilities_only_include_compaction_with_acp_beta() {+ for (beta_enabled, expected_compaction) in+ [(false, None), (true, Some(serde_json::json!({})))]+ {+ let capabilities =+ client_capabilities_for_agent(&AgentId::new("codex-acp"), beta_enabled);+ let capabilities =+ serde_json::to_value(capabilities).expect("client capabilities should serialize");+ let session = capabilities+ .get("session")+ .expect("session capabilities should be advertised");+ assert_eq!(session.get("compaction"), expected_compaction.as_ref());+ }+ }+#[gpui::test]async fn connection_routes_terminal_auth_without_acp_beta(cx: &mut gpui::TestAppContext) {init_feature_flags_test(cx);diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex 7d83869d851..c325290cf66 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -7681,6 +7681,101 @@ pub(crate) mod tests {);}+ #[gpui::test]+ async fn test_thread_search_highlights_expanded_compaction_details(cx: &mut TestAppContext) {+ 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());+ 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 bar should be open");+ let resource =+ acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(+ acp::TextResourceContents::new("retained resource details", "summary://context")+ .mime_type("text/markdown".to_string()),+ ));++ for (update, query) in [+ (+ acp::CompactionUpdate::new("failed", acp::CompactionStatus::Failed)+ .error("model *still* unavailable <details>"),+ "model *still* unavailable <details>",+ ),+ (+ acp::CompactionUpdate::new("completed", acp::CompactionStatus::Completed).summary(+ vec![+ acp::ContentBlock::Text(acp::TextContent::new("Retained summary")),+ acp::ContentBlock::Resource(resource),+ ],+ ),+ "retained resource details",+ ),+ ] {+ thread+ .update(cx, |thread, cx| {+ thread.handle_session_update(acp::SessionUpdate::CompactionUpdate(update), cx)+ })+ .expect("failed to receive compaction details");+ cx.run_until_parked();++ let (entry_index, markdown) = thread.read_with(cx, |thread, cx| {+ let (entry_index, entry) = thread+ .entries()+ .iter()+ .enumerate()+ .next_back()+ .expect("compaction entry should exist");+ let AgentThreadEntry::ContextCompaction(compaction) = entry else {+ panic!("expected a compaction entry");+ };+ let markdown = compaction+ .summary+ .iter()+ .filter_map(|content| content.markdown())+ .chain(compaction.error.iter())+ .find(|markdown| markdown.read(cx).source().contains(query))+ .expect("compaction should retain searchable details")+ .clone();+ (entry_index, markdown)+ });+ thread_view.update_in(cx, |view, window, cx| {+ view.toggle_compaction_expansion(entry_index, window, cx);+ });+ search_bar.update_in(cx, |search_bar, window, cx| {+ search_bar.query_editor.update(cx, |editor, cx| {+ editor.set_text(query, window, cx);+ });+ search_bar.update_matches(window, cx);+ });+ cx.run_until_parked();++ search_bar.read_with(cx, |search_bar, _| {+ assert_eq!(search_bar.match_count(), 1);+ assert_eq!(search_bar.active_match_index(), Some(0));+ });+ assert!(+ markdown.read_with(cx, |markdown, _| !markdown.search_highlights().is_empty()),+ "the visible compaction details should be highlighted",+ );++ thread_view.update_in(cx, |view, window, cx| {+ view.toggle_compaction_expansion(entry_index, window, cx);+ });+ cx.run_until_parked();+ assert_eq!(+ search_bar.read_with(cx, |search_bar, _| search_bar.match_count()),+ 0+ );+ assert!(markdown.read_with(cx, |markdown, _| markdown.search_highlights().is_empty()));+ }+ }+#[gpui::test]async fn test_thread_search_refreshes_on_new_thread_entry(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.rsindex 643cceda36a..f8ee82e9e59 100644--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs@@ -3,8 +3,7 @@ use std::sync::Arc;use std::time::Duration;use acp_thread::{- AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessageChunk, ContentBlock,- ToolCallContent,+ AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessageChunk, ToolCallContent,};use collections::HashMap;use editor::{@@ -917,21 +916,8 @@ fn collect_markdowns(.content.iter().filter_map(|content| match content {- ToolCallContent::ContentBlock(ContentBlock::Markdown { markdown }) => {- Some(markdown.clone())- }- ToolCallContent::ContentBlock(ContentBlock::EmbeddedResource {- markdown: Some(markdown),- ..- }) => Some(markdown.clone()),- ToolCallContent::ContentBlock(- ContentBlock::Empty- | ContentBlock::EmbeddedResource { markdown: None, .. }- | ContentBlock::ResourceLink { .. }- | ContentBlock::Image { .. },- )- | ToolCallContent::Diff(_)- | ToolCallContent::Terminal(_) => None,+ ToolCallContent::ContentBlock(content) => content.markdown().cloned(),+ ToolCallContent::Diff(_) | ToolCallContent::Terminal(_) => None,}),);}@@ -939,15 +925,63 @@ fn collect_markdowns(AgentThreadEntry::CompletedPlan(entries) => {out.extend(entries.iter().map(|e| e.content.clone()))}- AgentThreadEntry::ContextCompaction(compaction)- if entry_view_state.is_compaction_expanded(entry_ix) =>- {- if let Some(summary) = &compaction.summary {- out.push(summary.clone());- }- }+ AgentThreadEntry::ContextCompaction(compaction) => out.extend(compaction_markdowns(+ compaction,+ entry_view_state.is_compaction_expanded(entry_ix),+ )),AgentThreadEntry::Elicitation(_) => {}- AgentThreadEntry::ContextCompaction(_) => {}}out}++fn compaction_markdowns(+ compaction: &acp_thread::ContextCompaction,+ is_expanded: bool,+) -> impl Iterator<Item = Entity<Markdown>> + '_ {+ compaction+ .summary+ .iter()+ .filter_map(|content| content.markdown().cloned())+ .chain(compaction.error.iter().cloned())+ .filter(move |_| is_expanded)+}++#[cfg(test)]+mod tests {+ use super::*;+ use acp_thread::{+ ContentBlock, ContextCompaction, ContextCompactionId, ContextCompactionStatus,+ };+ use agent_client_protocol::schema::v1 as acp;++ #[gpui::test]+ fn test_compaction_markdowns_include_summary_and_error(cx: &mut App) {+ let summary = cx.new(|cx| Markdown::new("summary match".into(), None, None, cx));+ let unsupported =+ cx.new(|cx| Markdown::new("unsupported content match".into(), None, None, cx));+ let error = cx.new(|cx| Markdown::new("error match".into(), None, None, cx));+ let compaction = ContextCompaction {+ id: ContextCompactionId("compaction".into()),+ status: ContextCompactionStatus::Failed,+ summary: vec![+ ContentBlock::Markdown {+ markdown: summary.clone(),+ },+ ContentBlock::Unsupported {+ content: acp::ContentBlock::Audio(acp::AudioContent::new(+ "YXVkaW8=",+ "audio/wav",+ )),+ markdown: unsupported.clone(),+ },+ ContentBlock::Empty,+ ],+ error: Some(error.clone()),+ };++ assert!(compaction_markdowns(&compaction, false).next().is_none());++ let markdowns = compaction_markdowns(&compaction, true).collect::<Vec<_>>();+ assert_eq!(markdowns, vec![summary, unsupported, error]);+ }+}diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 8a2a77465ff..1d3bef44a79 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -3945,17 +3945,22 @@ impl ThreadView {cx: &Context<Self>,) -> AnyElement {let is_compacting = compaction.is_in_progress();- let summary = compaction.summary.clone();+ let summary = &compaction.summary;+ let error = compaction.error.clone();+ let has_details = !summary.is_empty() || error.is_some();let is_expanded = self.entry_view_state.read(cx).is_compaction_expanded(entry_ix);+ let details = (is_expanded && has_details).then_some((summary, error));let id = format!("context-compaction-{entry_ix}");- let header_label = match compaction.status {+ let header_label = match &compaction.status {acp_thread::ContextCompactionStatus::InProgress => "Compacting Context…",acp_thread::ContextCompactionStatus::Completed => "Context Compacted",+ acp_thread::ContextCompactionStatus::Failed => "Compaction Failed",acp_thread::ContextCompactionStatus::Canceled => "Compaction Canceled",+ acp_thread::ContextCompactionStatus::Other(_) => "Context Compaction",};let chevron_end = if is_expanded {IconName::ChevronUp@@ -3970,13 +3975,13 @@ impl ThreadView {Button::new(id, header_label).label_size(LabelSize::Small).loading(is_compacting)- .disabled(is_compacting)+ .disabled(!has_details).start_icon(Icon::new(IconName::Compact).size(IconSize::XSmall).color(Color::Muted),)- .when(!is_compacting, |this| {+ .when(has_details, |this| {this.end_icon(Icon::new(chevron_end).size(IconSize::XSmall)@@ -4003,20 +4008,37 @@ impl ThreadView {.border_color(gpui::transparent_black()).rounded_sm().child(header)- .when_some(summary.filter(|_| is_expanded), |this, summary| {+ .when_some(details, |this, (summary, error)| {this.border_color(self.tool_card_border_color(cx)).bg(cx.theme().colors().editor_background.opacity(0.2))- .child(- div()- .id(("compaction-summary", entry_ix))- .p_2()- .text_ui(cx)- .child(self.render_markdown(- summary,- MarkdownStyle::themed(MarkdownFont::Agent, window, cx),- cx,- )),- )+ .when(!summary.is_empty(), |this| {+ this.child(+ v_flex()+ .id(("compaction-summary", entry_ix))+ .p_2()+ .gap_2()+ .text_ui(cx)+ .children(summary.iter().enumerate().map(+ |(content_ix, content)| {+ self.render_output_content_block(+ entry_ix, content_ix, content, None, true,+ window, cx,+ )+ },+ )),+ )+ })+ .when_some(error, |this, error| {+ let mut style =+ MarkdownStyle::themed(MarkdownFont::Agent, window, cx);+ style.base_text_style.color = Color::Error.color(cx);+ this.child(+ div()+ .id(("compaction-error", entry_ix))+ .p_2()+ .child(self.render_markdown(error, style, cx)),+ )+ }).child(h_flex().border_t_1()@@ -4048,7 +4070,7 @@ impl ThreadView {.into_any()}- fn toggle_compaction_expansion(+ pub(super) fn toggle_compaction_expansion(&mut self,entry_ix: usize,window: &mut Window,@@ -10208,37 +10230,15 @@ impl ThreadView {cx: &Context<Self>,) -> AnyElement {match content {- ToolCallContent::ContentBlock(content) => {- if let Some((resource, markdown)) = content.embedded_resource() {- self.render_embedded_resource_output(- resource,- markdown.cloned(),- entry_ix,- context_ix,- tool_call,- card_layout,- window,- cx,- )- } else if let Some(resource_link) = content.resource_link() {- self.render_resource_link(resource_link, cx)- } else if let Some(markdown) = content.markdown() {- self.render_markdown_output(- markdown.clone(),- entry_ix,- context_ix,- tool_call,- card_layout,- window,- cx,- )- } else if let Some((image, _)) = content.image() {- let location = tool_call.locations.first().cloned();- self.render_image_output(entry_ix, image.clone(), location, card_layout, cx)- } else {- Empty.into_any_element()- }- }+ ToolCallContent::ContentBlock(content) => self.render_output_content_block(+ entry_ix,+ context_ix,+ content,+ Some(tool_call),+ card_layout,+ window,+ cx,+ ),ToolCallContent::Diff(diff) => {self.render_diff_editor(entry_ix, diff, tool_call, has_failed, cx)}@@ -10255,35 +10255,58 @@ impl ThreadView {}}- fn render_embedded_resource_output(+ fn render_output_content_block(&self,- resource: &acp::EmbeddedResource,- markdown: Option<Entity<Markdown>>,entry_ix: usize,context_ix: usize,- tool_call: &ToolCall,+ content: &acp_thread::ContentBlock,+ tool_call: Option<&ToolCall>,card_layout: bool,window: &Window,cx: &Context<Self>,) -> AnyElement {- if let Some(markdown) = markdown {- return self.render_markdown_output(- markdown,- entry_ix,- context_ix,- tool_call,- card_layout,- window,- cx,- );+ if let Some(markdown) = content.markdown() {+ if let Some(tool_call) = tool_call {+ self.render_markdown_output(+ markdown.clone(),+ entry_ix,+ context_ix,+ tool_call,+ card_layout,+ window,+ cx,+ )+ } else {+ self.render_markdown(+ markdown.clone(),+ MarkdownStyle::themed(MarkdownFont::Agent, window, cx),+ cx,+ )+ .into_any()+ }+ } else if let Some((resource, _)) = content.embedded_resource() {+ if tool_call.is_some() {+ self.render_embedded_resource_output(resource, context_ix, card_layout, cx)+ } else {+ self.render_embedded_resource_label(resource)+ }+ } else if let Some(resource_link) = content.resource_link() {+ self.render_resource_link(resource_link, cx)+ } else if let Some((image, _)) = content.image() {+ let location = tool_call.and_then(|tool_call| tool_call.locations.first().cloned());+ self.render_image_output(entry_ix, image.clone(), location, card_layout, cx)+ } else {+ Empty.into_any_element()}+ }- let uri = match &resource.resource {- acp::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),- acp::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),- _ => "",- };-+ fn render_embedded_resource_output(+ &self,+ resource: &acp::EmbeddedResource,+ context_ix: usize,+ card_layout: bool,+ cx: &Context<Self>,+ ) -> AnyElement {v_flex().gap_1().map(|this| {@@ -10299,16 +10322,26 @@ impl ThreadView {.border_color(self.tool_card_border_color(cx))}})- .when(!uri.is_empty(), |this| {- this.child(- Label::new(uri.to_string())- .size(LabelSize::XSmall)- .color(Color::Muted),- )- })+ .child(self.render_embedded_resource_label(resource)).into_any_element()}+ fn render_embedded_resource_label(&self, resource: &acp::EmbeddedResource) -> AnyElement {+ let uri = match &resource.resource {+ acp::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),+ acp::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),+ _ => "",+ };+ if uri.is_empty() {+ Empty.into_any_element()+ } else {+ Label::new(uri.to_string())+ .size(LabelSize::XSmall)+ .color(Color::Muted)+ .into_any_element()+ }+ }+fn render_resource_link(&self,resource_link: &acp::ResourceLink,