Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
agent: Improve compaction UI (#58409)
Bennet Bo Fenner176622acf98c
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex ff98888ca65..01e466043b3 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -246,7 +246,27 @@ pub enum AgentThreadEntry {AssistantMessage(AssistantMessage),ToolCall(ToolCall),CompletedPlan(Vec<PlanEntry>),- ContextCompaction,+ ContextCompaction(ContextCompaction),+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ContextCompactionId(pub Arc<str>);++/// A point in the thread where the conversation history was compacted to free+/// up room in the model's context window. The summary can be expanded to inspect+/// what the model retained.+#[derive(Debug)]+pub struct ContextCompaction {+ pub id: ContextCompactionId,+ /// 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>>,+}++#[derive(Debug)]+pub struct ContextCompactionUpdate {+ pub id: ContextCompactionId,+ pub summary_delta: String,}impl AgentThreadEntry {@@ -256,7 +276,7 @@ impl AgentThreadEntry {Self::AssistantMessage(message) => message.indented,Self::ToolCall(_) => false,Self::CompletedPlan(_) => false,- Self::ContextCompaction => false,+ Self::ContextCompaction(_) => false,}}@@ -273,7 +293,7 @@ impl AgentThreadEntry {}md}- Self::ContextCompaction => "--- Context Compacted ---\n\n".to_string(),+ Self::ContextCompaction(_) => "--- Context Compacted ---\n\n".to_string(),}}@@ -1543,7 +1563,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::AssistantMessage(_)| AgentThreadEntry::CompletedPlan(_)- | AgentThreadEntry::ContextCompaction => {}+ | AgentThreadEntry::ContextCompaction(_) => {}}}false@@ -1572,7 +1592,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::AssistantMessage(_)| AgentThreadEntry::CompletedPlan(_)- | AgentThreadEntry::ContextCompaction => {}+ | AgentThreadEntry::ContextCompaction(_) => {}}}@@ -1592,7 +1612,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::AssistantMessage(_)| AgentThreadEntry::CompletedPlan(_)- | AgentThreadEntry::ContextCompaction => {}+ | AgentThreadEntry::ContextCompaction(_) => {}}}@@ -1605,7 +1625,7 @@ impl AcpThread {AgentThreadEntry::UserMessage(..) => return false,AgentThreadEntry::AssistantMessage(..)| AgentThreadEntry::CompletedPlan(..)- | AgentThreadEntry::ContextCompaction => continue,+ | AgentThreadEntry::ContextCompaction(_) => continue,AgentThreadEntry::ToolCall(..) => return true,}}@@ -1949,8 +1969,63 @@ impl AcpThread {cx.emit(AcpThreadEvent::NewEntry);}- pub fn push_context_compaction(&mut self, cx: &mut Context<Self>) {- self.push_entry(AgentThreadEntry::ContextCompaction, cx);+ pub fn push_context_compaction(+ &mut self,+ compaction: ContextCompaction,+ cx: &mut Context<Self>,+ ) {+ if let Some(ix) =+ self.entries+ .iter()+ .enumerate()+ .rev()+ .find_map(|(ix, entry)| match entry {+ AgentThreadEntry::ContextCompaction(c) if &c.id == &compaction.id => Some(ix),+ _ => None,+ })+ {+ self.entries[ix] = AgentThreadEntry::ContextCompaction(compaction);+ cx.emit(AcpThreadEvent::EntryUpdated(ix));+ } else {+ self.push_entry(AgentThreadEntry::ContextCompaction(compaction), cx);+ }+ }++ pub fn update_context_compaction(+ &mut self,+ update: ContextCompactionUpdate,+ cx: &mut Context<Self>,+ ) {+ let language_registry = self.project.read(cx).languages().clone();+ let Some((ix, compaction)) =+ self.entries+ .iter_mut()+ .enumerate()+ .rev()+ .find_map(|(ix, entry)| match entry {+ AgentThreadEntry::ContextCompaction(c) if &c.id == &update.id => Some((ix, c)),+ _ => None,+ })+ else {+ return;+ };++ 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)+ });+ }++ cx.emit(AcpThreadEvent::EntryUpdated(ix));}pub fn can_set_title(&mut self, cx: &mut Context<Self>) -> bool {diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rsindex a1c37ef6284..ddf90cfa738 100644--- a/crates/agent/src/agent.rs+++ b/crates/agent/src/agent.rs@@ -2040,9 +2040,14 @@ impl NativeAgentConnection {thread.update_retry_status(status, cx)})?;}- ThreadEvent::ContextCompaction => {+ ThreadEvent::ContextCompaction(compaction) => {acp_thread.update(cx, |thread, cx| {- thread.push_context_compaction(cx);+ thread.push_context_compaction(compaction, cx);+ })?;+ }+ ThreadEvent::ContextCompactionUpdate(update) => {+ acp_thread.update(cx, |thread, cx| {+ thread.update_context_compaction(update, cx);})?;}ThreadEvent::Stop(stop_reason) => {diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rsindex d28f4ab1d94..953bbe194e8 100644--- a/crates/agent/src/thread.rs+++ b/crates/agent/src/thread.rs@@ -828,7 +828,8 @@ pub enum ThreadEvent {ToolCallAuthorization(ToolCallAuthorization),SubagentSpawned(acp::SessionId),Retry(acp_thread::RetryStatus),- ContextCompaction,+ ContextCompaction(acp_thread::ContextCompaction),+ ContextCompactionUpdate(acp_thread::ContextCompactionUpdate),Stop(acp::StopReason),}@@ -1349,7 +1350,7 @@ impl Thread {) -> mpsc::UnboundedReceiver<Result<ThreadEvent>> {let (tx, rx) = mpsc::unbounded();let stream = ThreadEventStream(tx);- for message in &self.messages {+ for (message_ix, message) in self.messages.iter().enumerate() {match &**message {Message::User(user_message) => stream.send_user_message(user_message),Message::Agent(assistant_message) => {@@ -1372,7 +1373,20 @@ impl Thread {}}Message::Resume => {}- Message::Compaction(_) => stream.send_context_compaction(),+ Message::Compaction(info) => {+ let compaction_id = acp_thread::ContextCompactionId(+ format!("replay-compaction-{message_ix}").into(),+ );+ match info {+ CompactionInfo::Summary(summary) => {+ stream.send_context_compaction(compaction_id.clone());+ stream.send_context_compaction_update(compaction_id.clone(), summary);+ }+ CompactionInfo::ProviderNative { .. } => {+ stream.send_context_compaction(compaction_id);+ }+ }+ }}}rx@@ -2525,6 +2539,8 @@ impl Thread {};log::debug!("Running compaction");+ let compaction_id = acp_thread::ContextCompactionId(Uuid::new_v4().to_string().into());+ event_stream.send_context_compaction(compaction_id.clone());let stream = futures::select! {result = model.stream_completion(request, cx).fuse() => result,_ = cancellation_rx.changed().fuse() => {@@ -2555,7 +2571,10 @@ impl Thread {};match event? {- LanguageModelCompletionEvent::Text(text) => summary.push_str(&text),+ LanguageModelCompletionEvent::Text(text) => {+ summary.push_str(&text);+ event_stream.send_context_compaction_update(compaction_id.clone(), &text);+ }LanguageModelCompletionEvent::Stop(_)| LanguageModelCompletionEvent::Started| LanguageModelCompletionEvent::Queued { .. }@@ -2589,7 +2608,6 @@ impl Thread {} else {this.messages.push(compaction);}- event_stream.send_context_compaction();cx.notify();})?;@@ -4380,9 +4398,26 @@ impl ThreadEventStream {self.0.unbounded_send(Ok(ThreadEvent::Retry(status))).ok();}- fn send_context_compaction(&self) {+ fn send_context_compaction(&self, id: acp_thread::ContextCompactionId) {+ self.0+ .unbounded_send(Ok(ThreadEvent::ContextCompaction(+ acp_thread::ContextCompaction { id, summary: None },+ )))+ .ok();+ }++ fn send_context_compaction_update(+ &self,+ id: acp_thread::ContextCompactionId,+ summary_delta: &str,+ ) {self.0- .unbounded_send(Ok(ThreadEvent::ContextCompaction))+ .unbounded_send(Ok(ThreadEvent::ContextCompactionUpdate(+ acp_thread::ContextCompactionUpdate {+ id,+ summary_delta: summary_delta.to_string(),+ },+ ))).ok();}@@ -5560,10 +5595,20 @@ mod tests {"expected replayed user message, got {event:?}");+ let event = replay_events.next().await;+ let compaction_id = match &event {+ Some(Ok(ThreadEvent::ContextCompaction(compaction))) => compaction.id.clone(),+ _ => panic!("expected context compaction event, got {event:?}"),+ };+let event = replay_events.next().await;assert!(- matches!(&event, Some(Ok(ThreadEvent::ContextCompaction))),- "expected context compaction event, got {event:?}"+ matches!(+ &event,+ Some(Ok(ThreadEvent::ContextCompactionUpdate(update)))+ if update.id == compaction_id && update.summary_delta == "summary"+ ),+ "expected context compaction summary event, got {event:?}");let event = replay_events.next().await;diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rsindex 6dbd44d29cf..52d00208820 100644--- a/crates/agent_servers/src/acp.rs+++ b/crates/agent_servers/src/acp.rs@@ -3506,7 +3506,7 @@ mod tests {acp_thread::AgentThreadEntry::AssistantMessage(_) => "assistant",acp_thread::AgentThreadEntry::ToolCall(_) => "tool_call",acp_thread::AgentThreadEntry::CompletedPlan(_) => "plan",- acp_thread::AgentThreadEntry::ContextCompaction => "compaction",+ acp_thread::AgentThreadEntry::ContextCompaction(_) => "compaction",}).collect::<Vec<_>>()});diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex e704c864b2c..2670744711f 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -576,6 +576,9 @@ pub struct ThreadView {pub expanded_thinking_blocks: HashSet<(usize, usize)>,auto_expanded_thinking_block: Option<(usize, usize)>,user_toggled_thinking_blocks: HashSet<(usize, usize)>,+ /// Tracks which context compaction entries (by entry index) have their+ /// summary expanded.+ expanded_compactions: HashSet<usize>,pub subagent_scroll_handles: RefCell<HashMap<acp::SessionId, ScrollHandle>>,pub edits_expanded: bool,pub plan_expanded: bool,@@ -891,6 +894,7 @@ impl ThreadView {expanded_thinking_blocks: HashSet::default(),auto_expanded_thinking_block: None,user_toggled_thinking_blocks: HashSet::default(),+ expanded_compactions: HashSet::default(),subagent_scroll_handles: RefCell::new(HashMap::default()),edits_expanded: false,plan_expanded: false,@@ -3438,6 +3442,113 @@ impl ThreadView {.into_any()}+ fn render_context_compaction(+ &self,+ entry_ix: usize,+ total_entries: usize,+ compaction: &acp_thread::ContextCompaction,+ window: &Window,+ cx: &Context<Self>,+ ) -> AnyElement {+ let is_compacting = entry_ix + 1 == total_entries+ && self.thread.read(cx).status() == acp_thread::ThreadStatus::Generating;+ let summary = compaction.summary.clone();+ let summary_available = summary.is_some();+ let is_expanded = summary_available && self.expanded_compactions.contains(&entry_ix);++ let header = h_flex()+ .id(("context-compaction", entry_ix))+ .px_5()+ .py_1()+ .gap_2()+ .w_full()+ .child(+ h_flex()+ .flex_none()+ .gap_1p5()+ .child(+ Icon::new(IconName::Scissors)+ .size(IconSize::XSmall)+ .color(Color::Muted),+ )+ .child(+ Label::new(if is_compacting {+ "Compacting context…"+ } else {+ "Context compacted"+ })+ .size(LabelSize::Custom(self.tool_name_font_size()))+ .color(Color::Muted),+ ),+ )+ .child(if is_compacting {+ div().flex_1().into_any_element()+ } else {+ Divider::horizontal().into_any_element()+ })+ .child(+ Disclosure::new(("compaction-disclosure", entry_ix), is_expanded)+ .opened_icon(IconName::ChevronUp)+ .closed_icon(IconName::ChevronDown),+ )+ .on_click(cx.listener(move |this, _event: &ClickEvent, _window, cx| {+ this.toggle_compaction_expansion(entry_ix, cx);+ }));++ if let Some(summary) = summary.filter(|_| is_expanded) {+ v_flex()+ .w_full()+ .child(header)+ .child(+ div()+ .id(("compaction-summary", entry_ix))+ .mx_5()+ .pl_3p5()+ .border_l_1()+ .border_color(self.tool_card_border_color(cx))+ .child(self.render_markdown(+ summary,+ MarkdownStyle::themed(MarkdownFont::Agent, window, cx),+ cx,+ )),+ )+ .child(+ div()+ .mx_5()+ .mb_1()+ .pl_3p5()+ .pt_2()+ .border_l_1()+ .border_color(self.tool_card_border_color(cx))+ .child(+ IconButton::new(+ ("compaction-summary-collapse", entry_ix),+ IconName::ChevronUp,+ )+ .full_width()+ .style(ButtonStyle::Outlined)+ .icon_color(Color::Muted)+ .on_click(cx.listener(+ move |this, _event: &ClickEvent, _window, cx| {+ this.expanded_compactions.remove(&entry_ix);+ cx.notify();+ },+ )),+ ),+ )+ .into_any()+ } else {+ header.into_any()+ }+ }++ fn toggle_compaction_expansion(&mut self, entry_ix: usize, cx: &mut Context<Self>) {+ if !self.expanded_compactions.remove(&entry_ix) {+ self.expanded_compactions.insert(entry_ix);+ }+ cx.notify();+ }+fn render_edits_summary(&self,changed_buffers: &[(Entity<Buffer>, Entity<BufferDiff>)],@@ -5396,19 +5507,9 @@ impl ThreadView {AgentThreadEntry::CompletedPlan(entries) => {self.render_completed_plan(entries, window, cx)}- AgentThreadEntry::ContextCompaction => h_flex()- .id(("context_compaction", entry_ix))- .px_5()- .py_1()- .gap_2()- .child(Divider::horizontal())- .child(- Label::new("Context Compacted")- .size(LabelSize::Custom(self.tool_name_font_size()))- .color(Color::Muted),- )- .child(Divider::horizontal())- .into_any(),+ AgentThreadEntry::ContextCompaction(compaction) => {+ self.render_context_compaction(entry_ix, total_entries, compaction, window, cx)+ }};let is_subagent_output = self.is_subagent()@@ -6519,7 +6620,7 @@ impl ThreadView {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::AssistantMessage(_)| AgentThreadEntry::CompletedPlan(_)- | AgentThreadEntry::ContextCompaction => {}+ | AgentThreadEntry::ContextCompaction(_) => {}}}diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex 85db4e32e48..48747f9cb33 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -232,7 +232,7 @@ impl EntryViewState {self.set_entry(index, Entry::CompletedPlan);}}- AgentThreadEntry::ContextCompaction => {+ AgentThreadEntry::ContextCompaction(_) => {if !matches!(self.entries.get(index), Some(Entry::ContextCompaction)) {self.set_entry(index, Entry::ContextCompaction);}