Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp: Support plan operations (#66345)
Ben Brandt1478fb5e60f8
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex ecb6ed87a40..f2372f23ac6 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -3461,9 +3461,31 @@ enum PlanIdentity {#[derive(Debug, Default)]pub struct Plan {- pub entries: Vec<PlanEntry>,+ pub content: PlanContent,pub meta: Option<acp_v2::Meta>,pub update_meta: Option<acp_v2::Meta>,+ /// Orders plans by their last meaningful change, so removing the visible plan can+ /// fall back to the next most recently changed one.+ last_changed: u64,+}++#[derive(Debug)]+pub enum PlanContent {+ Items(Vec<PlanEntry>),+ Markdown(Entity<Markdown>),+ File { uri: SharedString },+}++impl Default for PlanContent {+ fn default() -> Self {+ Self::Items(Vec::new())+ }+}++enum PlanContentUpdate {+ Items(Vec<acp_v2::PlanEntry>),+ Markdown(String),+ File(String),}#[derive(Debug)]@@ -3475,8 +3497,20 @@ pub struct PlanStats<'a> {}impl Plan {- pub fn is_empty(&self) -> bool {- self.entries.is_empty()+ pub fn is_empty(&self, cx: &App) -> bool {+ match &self.content {+ PlanContent::Items(entries) => entries.is_empty(),+ PlanContent::Markdown(markdown) => markdown.read(cx).source().trim().is_empty(),+ PlanContent::File { uri } => uri.is_empty(),+ }+ }++ /// Structured entries for item-based plans. Markdown and file plans have none.+ pub fn entries(&self) -> &[PlanEntry] {+ match &self.content {+ PlanContent::Items(entries) => entries,+ PlanContent::Markdown(_) | PlanContent::File { .. } => &[],+ }}pub fn stats(&self) -> PlanStats<'_> {@@ -3487,7 +3521,7 @@ impl Plan {cancelled: 0,};- for entry in &self.entries {+ for entry in self.entries() {match &entry.source.status {acp_v2::PlanEntryStatus::InProgress => {stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));@@ -3508,34 +3542,76 @@ impl Plan {fn replace(&mut self,- entries: Vec<acp_v2::PlanEntry>,+ update: PlanContentUpdate,meta: Option<acp_v2::Meta>,update_meta: Option<acp_v2::Meta>,cx: &mut App,) -> bool {- let changed = self.entries.len() != entries.len()- || self.entries.iter().zip(&entries).any(|(old, new)| {- old.source.content != new.content- || old.source.priority != new.priority- || old.source.status != new.status- });- let new_length = entries.len();- let mut entries = entries.into_iter();- for (old, new) in self.entries.iter_mut().zip(entries.by_ref()) {- if old.source.content != new.content {- update_markdown_in_place(&old.content, &new.content, cx);+ let changed = match (&mut self.content, update) {+ (PlanContent::Items(old_entries), PlanContentUpdate::Items(entries)) => {+ replace_plan_entries(old_entries, entries, cx)}- old.source = new;- }- self.entries- .extend(entries.map(|source| PlanEntry::new(source, cx)));- self.entries.truncate(new_length);+ (PlanContent::Markdown(markdown), PlanContentUpdate::Markdown(text)) => {+ let changed = markdown.read(cx).source() != text.as_str();+ if changed {+ update_markdown_in_place(markdown, &text, cx);+ }+ changed+ }+ (PlanContent::File { uri }, PlanContentUpdate::File(new_uri)) => {+ let changed = uri.as_ref() != new_uri.as_str();+ *uri = new_uri.into();+ changed+ }+ (_, PlanContentUpdate::Items(entries)) => {+ self.content = PlanContent::Items(+ entries+ .into_iter()+ .map(|source| PlanEntry::new(source, cx))+ .collect(),+ );+ true+ }+ (_, PlanContentUpdate::Markdown(text)) => {+ self.content =+ PlanContent::Markdown(cx.new(|cx| Markdown::new(text.into(), None, None, cx)));+ true+ }+ (_, PlanContentUpdate::File(uri)) => {+ self.content = PlanContent::File { uri: uri.into() };+ true+ }+ };self.meta = meta;self.update_meta = update_meta;changed}}+fn replace_plan_entries(+ old_entries: &mut Vec<PlanEntry>,+ entries: Vec<acp_v2::PlanEntry>,+ cx: &mut App,+) -> bool {+ let changed = old_entries.len() != entries.len()+ || old_entries.iter().zip(&entries).any(|(old, new)| {+ old.source.content != new.content+ || old.source.priority != new.priority+ || old.source.status != new.status+ });+ let new_length = entries.len();+ let mut entries = entries.into_iter();+ for (old, new) in old_entries.iter_mut().zip(entries.by_ref()) {+ if old.source.content != new.content {+ update_markdown_in_place(&old.content, &new.content, cx);+ }+ old.source = new;+ }+ old_entries.extend(entries.map(|source| PlanEntry::new(source, cx)));+ old_entries.truncate(new_length);+ changed+}+#[derive(Debug)]pub struct PlanEntry {pub source: acp_v2::PlanEntry,@@ -3551,6 +3627,10 @@ impl PlanEntry {}}+fn plan_id_from_v1(plan_id: acp_v1::PlanId) -> acp_v2::PlanId {+ acp_v2::PlanId::new(plan_id.0)+}+fn plan_entry_from_v1(entry: acp_v1::PlanEntry) -> Result<acp_v2::PlanEntry> {let priority = match entry.priority {acp_v1::PlanEntryPriority::High => acp_v2::PlanEntryPriority::High,@@ -3673,6 +3753,7 @@ pub struct AcpThread {permission_requests: IndexMap<PermissionRequestId, PermissionRequest>,plans: HashMap<PlanIdentity, Plan>,visible_plan: Option<PlanIdentity>,+ plan_change_count: u64,project: Entity<Project>,action_log: Entity<ActionLog>,shared_buffers: HashMap<Entity<Buffer>, BufferSnapshot>,@@ -4036,6 +4117,7 @@ impl AcpThread {subagent_association: None,plans: HashMap::default(),visible_plan: None,+ plan_change_count: 0,provisional_title: None,project,running_turn: None,@@ -5026,6 +5108,13 @@ impl AcpThread {acp_v1::SessionUpdate::Plan(plan) => {self.update_plan(plan, cx).map_err(acp_v1::Error::from)?;}+ acp_v1::SessionUpdate::PlanUpdate(update) => {+ self.apply_v1_plan_update(update, cx)+ .map_err(acp_v1::Error::from)?;+ }+ acp_v1::SessionUpdate::PlanRemoved(removed) => {+ self.remove_plan(plan_id_from_v1(removed.plan_id), cx);+ }acp_v1::SessionUpdate::Notice(notice) => {self.push_notice(notices::from_v1(notice).map_err(acp_v1::Error::from)?, cx);}@@ -7129,7 +7218,48 @@ impl AcpThread {.into_iter().map(plan_entry_from_v1).collect::<Result<_>>()?;- self.replace_plan(PlanIdentity::Legacy, entries, request.meta, None, cx);+ self.replace_plan(+ PlanIdentity::Legacy,+ PlanContentUpdate::Items(entries),+ request.meta,+ None,+ cx,+ );+ Ok(())+ }++ fn apply_v1_plan_update(+ &mut self,+ update: acp_v1::PlanUpdate,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let update_meta = update.meta;+ match update.plan {+ acp_v1::PlanUpdateContent::Items(plan) => {+ let entries = plan+ .entries+ .into_iter()+ .map(plan_entry_from_v1)+ .collect::<Result<_>>()?;+ self.upsert_plan_items(+ acp_v2::PlanItems::new(plan_id_from_v1(plan.plan_id), entries).meta(plan.meta),+ update_meta,+ cx,+ );+ }+ acp_v1::PlanUpdateContent::Markdown(plan) => self.upsert_plan_markdown(+ acp_v2::PlanMarkdown::new(plan_id_from_v1(plan.plan_id), plan.content)+ .meta(plan.meta),+ update_meta,+ cx,+ ),+ acp_v1::PlanUpdateContent::File(plan) => self.upsert_plan_file(+ acp_v2::PlanFile::new(plan_id_from_v1(plan.plan_id), plan.uri).meta(plan.meta),+ update_meta,+ cx,+ ),+ other => anyhow::bail!("unsupported plan update content: {other:?}"),+ }Ok(())}@@ -7141,28 +7271,76 @@ impl AcpThread {) {self.replace_plan(PlanIdentity::Keyed(plan.plan_id),- plan.entries,+ PlanContentUpdate::Items(plan.entries),+ plan.meta,+ update_meta,+ cx,+ );+ }++ pub fn upsert_plan_markdown(+ &mut self,+ plan: acp_v2::PlanMarkdown,+ update_meta: Option<acp_v2::Meta>,+ cx: &mut Context<Self>,+ ) {+ self.replace_plan(+ PlanIdentity::Keyed(plan.plan_id),+ PlanContentUpdate::Markdown(plan.content),plan.meta,update_meta,cx,);}+ pub fn upsert_plan_file(+ &mut self,+ plan: acp_v2::PlanFile,+ update_meta: Option<acp_v2::Meta>,+ cx: &mut Context<Self>,+ ) {+ self.replace_plan(+ PlanIdentity::Keyed(plan.plan_id),+ PlanContentUpdate::File(plan.uri),+ plan.meta,+ update_meta,+ cx,+ );+ }++ pub fn remove_plan(&mut self, plan_id: acp_v2::PlanId, cx: &mut Context<Self>) {+ let identity = PlanIdentity::Keyed(plan_id);+ if self.plans.remove(&identity).is_none() {+ return;+ }+ // A user dismissal (no visible plan) stays in effect; only an agent removing the+ // plan on screen moves the panel to the next most recently changed plan. Empty plans+ // are skipped because the panel hides them, which would mask a non-empty one.+ if self.visible_plan.as_ref() == Some(&identity) {+ self.visible_plan = self+ .plans+ .iter()+ .filter(|(_, plan)| !plan.is_empty(cx))+ .max_by_key(|(_, plan)| plan.last_changed)+ .map(|(identity, _)| identity.clone());+ }+ cx.notify();+ }+fn replace_plan(&mut self,identity: PlanIdentity,- entries: Vec<acp_v2::PlanEntry>,+ update: PlanContentUpdate,meta: Option<acp_v2::Meta>,update_meta: Option<acp_v2::Meta>,cx: &mut Context<Self>,) {let is_new = !self.plans.contains_key(&identity);- let changed =- self.plans- .entry(identity.clone())- .or_default()- .replace(entries, meta, update_meta, cx);+ let plan = self.plans.entry(identity.clone()).or_default();+ let changed = plan.replace(update, meta, update_meta, cx);if is_new || changed || identity == PlanIdentity::Legacy {+ self.plan_change_count += 1;+ plan.last_changed = self.plan_change_count;self.visible_plan = Some(identity);}cx.notify();@@ -7170,8 +7348,12 @@ impl AcpThread {fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {// V1's next-turn cleanup is a compatibility policy, not authority to alter keyed plans.- if let Some(plan) = self.plans.get_mut(&PlanIdentity::Legacy) {- plan.entries+ if let Some(Plan {+ content: PlanContent::Items(entries),+ ..+ }) = self.plans.get_mut(&PlanIdentity::Legacy)+ {+ entries.retain(|entry| !matches!(entry.source.status, acp_v2::PlanEntryStatus::Completed));}cx.notify();@@ -8850,11 +9032,11 @@ mod tests {let plan = thread.plan().expect("visible plan");assert_eq!(plan.meta, items.meta);assert_eq!(plan.update_meta, update_meta);- for (entry, source) in plan.entries.iter().zip(&items.entries) {+ for (entry, source) in plan.entries().iter().zip(&items.entries) {assert_eq!(&entry.source, source);assert_eq!(entry.content.read(cx).source().as_ref(), source.content);}- let markdown = plan.entries[0].content.clone();+ let markdown = plan.entries()[0].content.clone();let stats = plan.stats();assert_eq!((stats.pending, stats.completed, stats.cancelled), (1, 1, 1));assert!(stats.in_progress_entry.is_none());@@ -8868,20 +9050,20 @@ mod tests {let plan = thread.plan_by_id(&id).expect("retained hidden plan");assert_eq!(plan.meta, Some(acp_v2::Meta::new()));assert_eq!(plan.update_meta, Some(acp_v2::Meta::new()));- assert_eq!(plan.entries[0].source.meta, Some(acp_v2::Meta::new()));- assert_eq!(plan.entries[0].content, markdown);+ assert_eq!(plan.entries()[0].source.meta, Some(acp_v2::Meta::new()));+ assert_eq!(plan.entries()[0].content, markdown);items.meta = None;items.entries[0].meta = None;thread.upsert_plan_items(items.clone(), None, cx);let plan = thread.plan_by_id(&id).expect("retained plan");assert_eq!(plan.meta, None);assert_eq!(plan.update_meta, None);- assert_eq!(plan.entries[0].source.meta, None);+ assert_eq!(plan.entries()[0].source.meta, None);assert!(thread.plan().is_none(), "absent metadata replaces, but does not show the plan");items.entries[0].status = acp_v2::PlanEntryStatus::Other("_waiting".into());thread.upsert_plan_items(items, None, cx);let plan = thread.plan().expect("changed unknown status reopens the plan");- assert_eq!(plan.entries[0].content, markdown);+ assert_eq!(plan.entries()[0].content, markdown);assert_eq!(plan.stats().pending, 1);assert!(thread.entries().is_empty(), "plans never become transcript entries");});@@ -8932,18 +9114,18 @@ mod tests {None,cx,);- let markdown = thread.plan_by_id(&"plan".into()).expect("plan").entries[0]+ let markdown = thread.plan_by_id(&"plan".into()).expect("plan").entries()[0].content.clone();thread.clear_plan(cx);thread.upsert_plan_items(acp_v2::PlanItems::new("plan", updated.clone()), None, cx);let plan = thread.plan().expect("meaningful changes select the plan");- assert_eq!(plan.entries.len(), updated.len());- for (entry, source) in plan.entries.iter().zip(&updated) {+ assert_eq!(plan.entries().len(), updated.len());+ for (entry, source) in plan.entries().iter().zip(&updated) {assert_eq!(&entry.source, source);assert_eq!(entry.content.read(cx).source().as_ref(), source.content);}- if let Some(first) = plan.entries.first() {+ if let Some(first) = plan.entries().first() {assert_eq!(first.content, markdown);}}@@ -8961,12 +9143,12 @@ mod tests {acp_v2::PlanEntryStatus::Pending,)];thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx);- let first_markdown = thread.plan().expect("A").entries[0].content.clone();+ let first_markdown = thread.plan().expect("A").entries()[0].content.clone();thread.upsert_plan_items(acp_v2::PlanItems::new("b", entries.clone()), None, cx);let second_markdown = thread.plan().expect("new B selects despite identical contents")- .entries[0]+ .entries()[0].content.clone();assert_ne!(@@ -8980,7 +9162,13 @@ mod tests {);assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into())));thread.upsert_plan_items(acp_v2::PlanItems::new("empty", vec![]), None, cx);- assert!(thread.plan().expect("selected empty plan").is_empty());+ assert!(+ thread+ .plan()+ .expect("selected empty plan")+ .entries()+ .is_empty()+ );thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx);assert_eq!(thread.visible_plan,@@ -8991,7 +9179,7 @@ mod tests {thread.upsert_plan_items(acp_v2::PlanItems::new("a", changed), None, cx);assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("a".into())));assert_eq!(- thread.plan().expect("A reopens").entries[0].content,+ thread.plan().expect("A reopens").entries()[0].content,first_markdown);thread.upsert_plan_items(acp_v2::PlanItems::new("b", vec![]), None, cx);@@ -9000,13 +9188,14 @@ mod tests {thread.plan().expect("clearing older B selects empty B")+ .entries().is_empty());assert_eq!(thread.plan_by_id(&"a".into()).expect("A retained")- .entries+ .entries().len(),1);@@ -9014,6 +9203,119 @@ mod tests {});}+ #[gpui::test]+ async fn test_keyed_plan_content_types_and_removal(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ let entries = vec![acp_v2::PlanEntry::new(+ "Task",+ acp_v2::PlanEntryPriority::Medium,+ acp_v2::PlanEntryStatus::Pending,+ )];+ thread.upsert_plan_items(acp_v2::PlanItems::new("items", entries), None, cx);+ thread.upsert_plan_markdown(+ acp_v2::PlanMarkdown::new("doc", "# Design\n- step"),+ None,+ cx,+ );+ let PlanContent::Markdown(markdown) = &thread.plan().expect("markdown plan").content+ else {+ panic!("markdown plan is visible");+ };+ let markdown = markdown.clone();+ assert_eq!(markdown.read(cx).source(), "# Design\n- step");++ thread.clear_plan(cx);+ thread.upsert_plan_markdown(+ acp_v2::PlanMarkdown::new("doc", "# Design\n- step"),+ None,+ cx,+ );+ assert!(thread.plan().is_none(), "identical markdown keeps dismissal");+ thread.upsert_plan_markdown(+ acp_v2::PlanMarkdown::new("doc", "# Design\n- step\n- another"),+ None,+ cx,+ );+ let PlanContent::Markdown(updated) = &thread.plan().expect("changed markdown").content+ else {+ panic!("markdown plan is visible");+ };+ assert_eq!(updated, &markdown, "markdown is updated in place");++ thread.upsert_plan_file(acp_v2::PlanFile::new("doc", "file:///tmp/plan.md"), None, cx);+ let plan = thread.plan().expect("file plan");+ assert!(+ matches!(&plan.content, PlanContent::File { uri } if uri.as_ref() == "file:///tmp/plan.md")+ );+ assert!(plan.entries().is_empty());+ assert!(!plan.is_empty(cx));++ thread.remove_plan("doc".into(), cx);+ assert!(thread.plan_by_id(&"doc".into()).is_none());+ assert_eq!(+ thread.visible_plan,+ Some(PlanIdentity::Keyed("items".into())),+ "removing the visible plan falls back to the most recently changed plan"+ );++ thread.upsert_plan_items(acp_v2::PlanItems::new("empty", vec![]), None, cx);+ thread.upsert_plan_markdown(acp_v2::PlanMarkdown::new("other", "Other"), None, cx);+ thread.remove_plan("other".into(), cx);+ assert_eq!(+ thread.visible_plan,+ Some(PlanIdentity::Keyed("items".into())),+ "fallback skips empty plans"+ );++ thread.upsert_plan_markdown(acp_v2::PlanMarkdown::new("other", "Other"), None, cx);+ thread.clear_plan(cx);+ thread.remove_plan("other".into(), cx);+ assert!(thread.plan().is_none(), "removal does not undo dismissal");++ thread.remove_plan("missing".into(), cx);+ assert!(thread.plan_by_id(&"items".into()).is_some());+ assert!(thread.entries().is_empty());+ });+ }++ #[gpui::test]+ async fn test_v1_plan_update_and_removal(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ for update in [+ json!({"sessionUpdate": "plan_update", "plan": {"type": "items", "planId": "a",+ "entries": [{"content": "Step", "priority": "high", "status": "in_progress"}]}}),+ json!({"sessionUpdate": "plan_update", "plan": {"type": "markdown", "planId": "b",+ "content": "Notes"}, "_meta": {"scope": "update"}}),+ ] {+ thread+ .handle_session_update(serde_json::from_value(update).expect("v1 update"), cx)+ .expect("plan update applies");+ }+ let items = thread.plan_by_id(&"a".into()).expect("items plan");+ assert_eq!(items.stats().pending, 1);+ let markdown = thread.plan().expect("markdown plan is visible");+ assert!(matches!(markdown.content, PlanContent::Markdown(_)));+ assert_eq!(+ markdown.update_meta,+ Some(acp_v2::Meta::from_iter([("scope".into(), json!("update"))]))+ );++ thread+ .handle_session_update(+ serde_json::from_value(json!({"sessionUpdate": "plan_removed", "planId": "b"}))+ .expect("v1 removal"),+ cx,+ )+ .expect("plan removal applies");+ assert!(thread.plan_by_id(&"b".into()).is_none());+ assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("a".into())));+ });+ }+#[gpui::test]async fn test_legacy_plan_cleanup_does_not_mutate_keyed_plans(cx: &mut TestAppContext) {init_test(cx);@@ -9055,7 +9357,7 @@ mod tests {assert_eq!(thread.plan().expect("legacy plan").meta, legacy.meta);assert_eq!(thread.plan().expect("legacy plan").update_meta, None);assert_eq!(- thread.plan().expect("legacy plan").entries[1].source.meta,+ thread.plan().expect("legacy plan").entries()[1].source.meta,Some(acp_v2::Meta::new()));thread.clear_plan(cx);@@ -9064,7 +9366,7 @@ mod tests {.update_plan(legacy, cx).expect("identical legacy update restores the panel");assert_eq!(- thread.plan().expect("legacy compatibility").entries.len(),+ thread.plan().expect("legacy compatibility").entries().len(),2);thread.upsert_plan_items(keyed.clone(), None, cx);@@ -9079,16 +9381,16 @@ mod tests {);let retained = thread.plan_by_id(&keyed.plan_id).expect("keyed plan");assert_eq!(retained.meta, keyed.meta);- assert_eq!(retained.entries.len(), keyed.entries.len());- for (entry, expected) in retained.entries.iter().zip(&keyed.entries) {+ assert_eq!(retained.entries().len(), keyed.entries.len());+ for (entry, expected) in retained.entries().iter().zip(&keyed.entries) {assert_eq!(&entry.source, expected);}let legacy = thread.plans.get(&PlanIdentity::Legacy).expect("legacy record");- assert_eq!(legacy.entries.len(), 1);- assert_eq!(legacy.entries[0].source.content, "Pending");+ assert_eq!(legacy.entries().len(), 1);+ assert_eq!(legacy.entries()[0].source.content, "Pending");});complete.send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))diff --git a/crates/agent_servers/src/acp/session_updates.rs b/crates/agent_servers/src/acp/session_updates.rsindex b70ba79f841..b4114ad9214 100644--- a/crates/agent_servers/src/acp/session_updates.rs+++ b/crates/agent_servers/src/acp/session_updates.rs@@ -173,6 +173,15 @@ pub enum InboundSessionUpdate {plan: acp_v2::PlanItems,update_meta: Option<acp_v2::Meta>,},+ PlanMarkdown {+ plan: acp_v2::PlanMarkdown,+ update_meta: Option<acp_v2::Meta>,+ },+ PlanFile {+ plan: acp_v2::PlanFile,+ update_meta: Option<acp_v2::Meta>,+ },+ PlanRemoved(acp_v2::PlanRemoved),Terminal(DecodedTerminalUpdate),SessionInfo(acp_v2::SessionInfoUpdate),AvailableCommands(acp_v2::AvailableCommandsUpdate),@@ -232,29 +241,33 @@ impl TryFrom<acp_v2::UpdateSessionNotification> for InboundSessionNotification {acp_v2::SessionUpdate::ToolCallContentChunk(chunk) => {InboundSessionUpdate::ToolCallContentChunk(chunk)}- acp_v2::SessionUpdate::PlanUpdate(mut update) => {- // Zed only renders item plans, but any plan type replaces the plan with that ID.- let plan = match update.plan {- acp_v2::PlanUpdateContent::Items(plan) => plan,- acp_v2::PlanUpdateContent::File(plan) => {- acp_v2::PlanItems::new(plan.plan_id, Vec::new())- }- acp_v2::PlanUpdateContent::Markdown(plan) => {- acp_v2::PlanItems::new(plan.plan_id, Vec::new())- }- acp_v2::PlanUpdateContent::Other(plan) => {- acp_v2::PlanItems::new(plan.plan_id, Vec::new())- }- content => {- update.plan = content;- notification.update = acp_v2::SessionUpdate::PlanUpdate(update);- return Err(notification);- }- };- InboundSessionUpdate::PlanItems {+ acp_v2::SessionUpdate::PlanUpdate(mut update) => match update.plan {+ acp_v2::PlanUpdateContent::Items(plan) => InboundSessionUpdate::PlanItems {+ plan,+ update_meta: update.meta,+ },+ acp_v2::PlanUpdateContent::Markdown(plan) => InboundSessionUpdate::PlanMarkdown {+ plan,+ update_meta: update.meta,+ },+ acp_v2::PlanUpdateContent::File(plan) => InboundSessionUpdate::PlanFile {plan,update_meta: update.meta,+ },+ // Zed can't render an unknown plan type, but it still replaces the plan with+ // that ID.+ acp_v2::PlanUpdateContent::Other(plan) => InboundSessionUpdate::PlanItems {+ plan: acp_v2::PlanItems::new(plan.plan_id, Vec::new()),+ update_meta: update.meta,+ },+ content => {+ update.plan = content;+ notification.update = acp_v2::SessionUpdate::PlanUpdate(update);+ return Err(notification);}+ },+ acp_v2::SessionUpdate::PlanRemoved(removed) => {+ InboundSessionUpdate::PlanRemoved(removed)}acp_v2::SessionUpdate::SessionInfoUpdate(update) => {InboundSessionUpdate::SessionInfo(update)@@ -331,6 +344,18 @@ impl InboundSessionNotification {thread.upsert_plan_items(plan, update_meta, cx);Ok(())}+ InboundSessionUpdate::PlanMarkdown { plan, update_meta } => {+ thread.upsert_plan_markdown(plan, update_meta, cx);+ Ok(())+ }+ InboundSessionUpdate::PlanFile { plan, update_meta } => {+ thread.upsert_plan_file(plan, update_meta, cx);+ Ok(())+ }+ InboundSessionUpdate::PlanRemoved(removed) => {+ thread.remove_plan(removed.plan_id, cx);+ Ok(())+ }InboundSessionUpdate::Terminal(update) => DecodedTerminalNotification {session_id,meta: delivery_metadata,diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 2e19fad2c30..0d50e196dc1 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -486,12 +486,9 @@ fn client_builder()}-/// `offer_subagents` advertises the unstable subagents RFD, which Zed only offers v1 agents-/// behind the `acp-beta` flag.-fn client_capabilities_for_agent(- agent_id: &AgentId,- offer_subagents: bool,-) -> acp::ClientCapabilities {+/// `acp_beta` advertises the unstable subagents and plan operations RFDs, which Zed only+/// offers v1 agents behind the `acp-beta` flag.+fn client_capabilities_for_agent(agent_id: &AgentId, acp_beta: bool) -> acp::ClientCapabilities {let mut meta = acp::Meta::from_iter([("terminal_output".into(), true.into()),("terminal-auth".into(), true.into()),@@ -521,7 +518,8 @@ fn client_capabilities_for_agent(.form(acp::ElicitationFormCapabilities::new()).url(acp::ElicitationUrlCapabilities::new()),)- .subagents(offer_subagents.then(acp::SubagentCapabilities::new))+ .subagents(acp_beta.then(acp::SubagentCapabilities::new))+ .plan(acp_beta.then(acp::PlanCapabilities::new)).meta(meta)}@@ -575,8 +573,8 @@ impl AcpConnection {let client_session_list: Rc<RefCell<Option<Rc<AcpSessionList>>>> =Rc::new(RefCell::new(None));let request_elicitations = cx.new(|_| ElicitationStore::default());- let offer_subagents = cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>());- let client_capabilities = client_capabilities_for_agent(&agent_id, offer_subagents);+ let acp_beta = cx.update(|cx| cx.has_flag::<AcpBetaFeatureFlag>());+ let client_capabilities = client_capabilities_for_agent(&agent_id, acp_beta);let accepts_subagent_updates = client_capabilities.subagents.is_some();let dispatch_context = ClientContext {@@ -4137,7 +4135,7 @@ mod tests {let plan = thread.plan_by_id(&plan_id).expect("first plan");assert_eq!(plan.meta, Some(v2_terminal_meta("plan")));assert_eq!(plan.update_meta, Some(v2_terminal_meta("update")));- let [retained] = plan.entries.as_slice() else {+ let [retained] = plan.entries() else {panic!("one retained entry");};assert_eq!(@@ -4164,7 +4162,7 @@ mod tests {let plan = thread.plan_by_id(&plan_id).expect("retained hidden plan");assert_eq!(plan.meta, Some(acp_v2::Meta::new()));assert_eq!(plan.update_meta, Some(acp_v2::Meta::new()));- assert_eq!(plan.entries.first().expect("entry").content, markdown);+ assert_eq!(plan.entries().first().expect("entry").content, markdown);});harness.send(json!({"sessionUpdate": "plan_update",@@ -4177,7 +4175,7 @@ mod tests {let plan = thread.plan().expect("changed tasks reopen the plan");assert_eq!(plan.meta, None);assert_eq!(plan.update_meta, None);- let [entry] = plan.entries.as_slice() else {+ let [entry] = plan.entries() else {panic!("replacement entry");};assert_eq!(entry.source.status, acp_v2::PlanEntryStatus::Completed);@@ -4196,14 +4194,14 @@ mod tests {thread.plan_by_id(&plan_id).expect("empty plan")- .entries+ .entries().is_empty());assert_eq!(thread.plan_by_id(&"plan-extra".into()).expect("other plan")- .entries+ .entries().len(),1);@@ -5223,6 +5221,54 @@ mod tests {);}+ #[gpui::test]+ async fn v2_plan_sdk_markdown_file_and_removal(cx: &mut gpui::TestAppContext) {+ use serde_json::json;++ let harness = V2SessionHarness::new(cx).await;+ for update in [+ json!({"sessionUpdate": "plan_update",+ "plan": {"type": "markdown", "planId": "design", "content": "# Design\n- step"}}),+ json!({"sessionUpdate": "plan_update",+ "plan": {"type": "file", "planId": "doc", "uri": "file:///tmp/plan.md"}}),+ ] {+ harness.send(update, None);+ }+ harness.drain(cx).await;+ harness.thread.read_with(cx, |thread, cx| {+ let Some(acp_thread::PlanContent::Markdown(markdown)) = thread+ .plan_by_id(&"design".into())+ .map(|plan| &plan.content)+ else {+ panic!("markdown plan");+ };+ assert_eq!(markdown.read(cx).source(), "# Design\n- step");+ let Some(acp_thread::PlanContent::File { uri }) =+ thread.plan().map(|plan| &plan.content)+ else {+ panic!("file plan is visible");+ };+ assert_eq!(uri.as_ref(), "file:///tmp/plan.md");+ });++ harness.send(+ json!({"sessionUpdate": "plan_removed", "planId": "doc"}),+ None,+ );+ harness.drain(cx).await;+ harness.thread.read_with(cx, |thread, _| {+ assert!(thread.plan_by_id(&"doc".into()).is_none());+ assert!(+ matches!(+ thread.plan().map(|plan| &plan.content),+ Some(acp_thread::PlanContent::Markdown(_))+ ),+ "removing the visible plan falls back to the remaining one"+ );+ });+ assert!(harness.fallback.lock().expect("fallback mutex").is_empty());+ }+#[gpui::test]async fn v2_session_sdk_falls_through_unhandled_updates(cx: &mut gpui::TestAppContext) {let harness = V2SessionHarness::new(cx).await;@@ -5275,15 +5321,29 @@ mod tests {}#[gpui::test]- async fn v2_plan_sdk_unrenderable_types_replace_the_plan(cx: &mut gpui::TestAppContext) {+ async fn v2_plan_sdk_any_type_replaces_the_plan(cx: &mut gpui::TestAppContext) {+ use acp_thread::PlanContent;use serde_json::json;let harness = V2SessionHarness::new(cx).await;let plan_id = acp_v2::PlanId::new("plan");- for replacement in [- json!({"type": "file", "planId": "plan", "uri": "file:///tmp/plan.md"}),- json!({"type": "markdown", "planId": "plan", "content": "Unsupported"}),- json!({"type": "_future", "planId": "plan", "payload": [null, 7]}),+ let is_file = |content: &PlanContent| matches!(content, PlanContent::File { .. });+ let is_markdown = |content: &PlanContent| matches!(content, PlanContent::Markdown(_));+ let is_empty_items = |content: &PlanContent| matches!(content, PlanContent::Items(entries) if entries.is_empty());+ for (replacement, expected) in [+ (+ json!({"type": "file", "planId": "plan", "uri": "file:///tmp/plan.md"}),+ &is_file as &dyn Fn(&PlanContent) -> bool,+ ),+ (+ json!({"type": "markdown", "planId": "plan", "content": "# Plan"}),+ &is_markdown,+ ),+ // An unknown type still replaces the plan, so the stale entries stop showing.+ (+ json!({"type": "_future", "planId": "plan", "payload": [null, 7]}),+ &is_empty_items,+ ),] {harness.send(json!({"sessionUpdate": "plan_update",@@ -5293,7 +5353,10 @@ mod tests {);harness.drain(cx).await;harness.thread.read_with(cx, |thread, _| {- assert_eq!(thread.plan_by_id(&plan_id).expect("plan").entries.len(), 1);+ assert_eq!(+ thread.plan_by_id(&plan_id).expect("plan").entries().len(),+ 1+ );});harness.send(json!({"sessionUpdate": "plan_update", "plan": replacement}),@@ -5301,13 +5364,10 @@ mod tests {);harness.drain(cx).await;harness.thread.read_with(cx, |thread, _| {+ let plan = thread.plan_by_id(&plan_id).expect("replaced plan");assert!(- thread- .plan_by_id(&plan_id)- .expect("replaced plan")- .entries- .is_empty(),- "{replacement} must replace the stale entries"+ expected(&plan.content),+ "{replacement} must replace the plan");});}@@ -5706,6 +5766,21 @@ mod tests {}}+ #[test]+ fn client_capabilities_advertise_plan_operations_only_with_acp_beta() {+ let agent_id = AgentId::new("codex-acp");+ let without = serde_json::to_value(client_capabilities_for_agent(&agent_id, false))+ .expect("capabilities serialize");+ assert_eq!(+ without.get("plan"),+ None,+ "v1 plan operations must only be offered behind acp-beta"+ );+ let with = serde_json::to_value(client_capabilities_for_agent(&agent_id, true))+ .expect("capabilities serialize");+ assert_eq!(with.get("plan"), Some(&serde_json::json!({})));+ }+#[gpui::test]async fn connection_routes_terminal_auth(cx: &mut gpui::TestAppContext) {init_settings_test(cx);diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex c7cecc3dc51..5e265955a6d 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -5,7 +5,7 @@ use acp_thread::{PermissionPattern, PermissionRequest, PermissionRequestId, ProtocolErrorInfo, RetryStatus,SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,};-use acp_thread::{AgentConnection, Plan};+use acp_thread::{AgentConnection, Plan, PlanContent};use action_log::{ActionLog, ActionLogTelemetry, DiffStats};use agent::{NativeAgentServer, NoModelConfiguredError, ThreadStore};use agent_client_protocol::v2::schema as acp_v2;@@ -9588,7 +9588,7 @@ pub(crate) mod tests {.read(cx).plan().expect("active plan")- .entries+ .entries().first().expect("active plan entry").content@@ -9624,7 +9624,7 @@ pub(crate) mod tests {thread.plan().expect("completed plan")- .entries+ .entries().first().expect("completed plan entry").content,@@ -9650,7 +9650,7 @@ pub(crate) mod tests {let entry = thread.plan().expect("reopened plan")- .entries+ .entries().first().expect("reopened plan entry");assert_eq!(entry.content, plan_content);@@ -9699,7 +9699,12 @@ pub(crate) mod tests {cx.run_until_parked();active_thread(&conversation_view, cx).read_with(cx, |view, cx| {assert_thread_list_item_count_matches_entries(view, cx);- assert!(view.thread.read(cx).plan().is_none_or(Plan::is_empty));+ assert!(+ view.thread+ .read(cx)+ .plan()+ .is_none_or(|plan| plan.is_empty(cx))+ );});connection.end_turn(session_id, acp_v1::StopReason::EndTurn);cx.run_until_parked();@@ -9730,7 +9735,7 @@ pub(crate) mod tests {});cx.run_until_parked();let markdown = thread.read_with(cx, |thread, _| {- thread.plan().expect("visible plan").entries[0]+ thread.plan().expect("visible plan").entries()[0].content.clone()});@@ -9805,7 +9810,7 @@ pub(crate) mod tests {assert!(cx.debug_bounds(row).is_some(), "{row}");thread.read_with(cx, |thread, cx| {assert_eq!(- thread.plan().expect("visible plan").entries[0].content,+ thread.plan().expect("visible plan").entries()[0].content,markdown);assert_eq!(markdown.read(cx).source(), "Unchanged task");@@ -9835,7 +9840,13 @@ pub(crate) mod tests {assert!(cx.debug_bounds("plan-status-All Done").is_none());thread.update(cx, |thread, cx| {thread.upsert_plan_items(acp_v2::PlanItems::new("status-plan", vec![]), None, cx);- assert!(thread.plan().expect("empty selected plan").is_empty());+ assert!(+ thread+ .plan()+ .expect("empty selected plan")+ .entries()+ .is_empty()+ );assert!(thread.entries().is_empty());});cx.run_until_parked();diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex e8276686a3f..86e51a58b54 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -4006,7 +4006,7 @@ impl ThreadView {let action_log = thread.action_log();let telemetry = ActionLogTelemetry::from(thread);let changed_buffers = action_log.read(cx).changed_buffers(cx).collect::<Vec<_>>();- let plan = thread.plan().filter(|plan| !plan.is_empty());+ let plan = thread.plan().filter(|plan| !plan.is_empty(cx));let has_plan = plan.is_some();let queue_is_empty = !self.has_queued_messages();@@ -4078,7 +4078,7 @@ impl ThreadView {.when_some(plan, |this, plan| {this.child(self.render_plan_summary(plan, window, cx)).when(plan_expanded, |parent| {- parent.child(self.render_plan_entries(plan, window, cx))+ parent.children(self.render_plan_body(plan, window, cx))})}).when(has_plan && !changed_buffers.is_empty(), |this| {@@ -4861,10 +4861,94 @@ impl ThreadView {window: &mut Window,cx: &Context<Self>,) -> impl IntoElement {+ let plan_expanded = self.plan_expanded;+ let file_uri = match &plan.content {+ PlanContent::File { uri } => Some(uri.clone()),+ PlanContent::Items(_) | PlanContent::Markdown(_) => None,+ };++ let title = match &plan.content {+ PlanContent::Items(_) => self.render_plan_items_title(plan, window, cx),+ PlanContent::Markdown(markdown) => {+ let heading = markdown_plan_heading(markdown.read(cx).source());+ h_flex()+ .w_full()+ .min_w_0()+ .gap_1()+ .child(+ Label::new("Plan")+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .when_some(heading, |this, heading| {+ this.child(+ Label::new(heading.to_owned())+ .size(LabelSize::Small)+ .color(Color::Muted)+ .truncate(),+ )+ })+ }+ PlanContent::File { uri } => h_flex()+ .w_full()+ .min_w_0()+ .gap_1()+ .child(+ Label::new("Plan")+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .child(+ Label::new(plan_file_label(uri))+ .size(LabelSize::Small)+ .truncate(),+ )+ .child(+ Icon::new(IconName::ArrowUpRight)+ .size(IconSize::XSmall)+ .color(Color::Muted),+ ),+ };++ h_flex()+ .id("plan_summary")+ .debug_selector(|| "plan_summary".into())+ .p_1()+ .w_full()+ .gap_1()+ .when(plan_expanded && file_uri.is_none(), |this| {+ this.border_b_1().border_color(cx.theme().colors().border)+ })+ .when(file_uri.is_none(), |this| {+ this.child(Disclosure::new("plan_disclosure", plan_expanded))+ })+ .child(title.flex_1())+ .child(+ IconButton::new("dismiss-plan", IconName::Close)+ .icon_size(IconSize::XSmall)+ .shape(ui::IconButtonShape::Square)+ .tooltip(Tooltip::text("Clear Plan"))+ .on_click(cx.listener(|this, _, _, cx| {+ this.thread.update(cx, |thread, cx| thread.clear_plan(cx));+ cx.stop_propagation();+ })),+ )+ .on_click(cx.listener(move |this, _, window, cx| {+ if let Some(uri) = &file_uri {+ open_link(uri.clone(), &this.workspace, window, cx);+ } else {+ this.plan_expanded = !this.plan_expanded;+ cx.notify();+ }+ }))+ .into_any_element()+ }++ fn render_plan_items_title(&self, plan: &Plan, window: &mut Window, cx: &Context<Self>) -> Div {let plan_expanded = self.plan_expanded;let stats = plan.stats();- let title = if let Some(entry) = stats.in_progress_entry+ if let Some(entry) = stats.in_progress_entry&& !plan_expanded{h_flex()@@ -4910,7 +4994,7 @@ impl ThreadView {)})} else {- let status_label = plan_summary_label(&stats, plan.entries.len());+ let status_label = plan_summary_label(&stats, plan.entries().len());h_flex().debug_selector(|| format!("plan-status-{status_label}"))@@ -4928,39 +5012,42 @@ impl ThreadView {.color(Color::Muted).mr_1(),)- };+ }+ }- h_flex()- .id("plan_summary")- .debug_selector(|| "plan_summary".into())- .p_1()- .w_full()- .gap_1()- .when(plan_expanded, |this| {- this.border_b_1().border_color(cx.theme().colors().border)- })- .child(Disclosure::new("plan_disclosure", plan_expanded))- .child(title.flex_1())- .child(- IconButton::new("dismiss-plan", IconName::Close)- .icon_size(IconSize::XSmall)- .shape(ui::IconButtonShape::Square)- .tooltip(Tooltip::text("Clear Plan"))- .on_click(cx.listener(|this, _, _, cx| {- this.thread.update(cx, |thread, cx| thread.clear_plan(cx));- cx.stop_propagation();- })),- )- .on_click(cx.listener(|this, _, _, cx| {- this.plan_expanded = !this.plan_expanded;- cx.notify();- }))- .into_any_element()+ fn render_plan_body(+ &self,+ plan: &Plan,+ window: &mut Window,+ cx: &Context<Self>,+ ) -> Option<AnyElement> {+ match &plan.content {+ PlanContent::Items(entries) => Some(+ self.render_plan_entries(entries, window, cx)+ .into_any_element(),+ ),+ PlanContent::Markdown(markdown) => Some(+ v_flex()+ .id("plan_markdown")+ .max_h_64()+ .overflow_y_scroll()+ .px_2()+ .py_1()+ .bg(cx.theme().colors().editor_background)+ .text_xs()+ .child(MarkdownElement::new(+ markdown.clone(),+ MarkdownStyle::themed(MarkdownFont::Agent, window, cx),+ ))+ .into_any_element(),+ ),+ PlanContent::File { .. } => None,+ }}fn render_plan_entries(&self,- plan: &Plan,+ entries: &[acp_thread::PlanEntry],window: &mut Window,cx: &Context<Self>,) -> impl IntoElement {@@ -4969,7 +5056,7 @@ impl ThreadView {.max_h_40().overflow_y_scroll().child(- v_flex().children(plan.entries.iter().enumerate().flat_map(|(index, entry)| {+ v_flex().children(entries.iter().enumerate().flat_map(|(index, entry)| {let entry_bg = cx.theme().colors().editor_background;let tooltip_text: SharedString =entry.content.read(cx).source().to_string().into();@@ -5001,7 +5088,7 @@ impl ThreadView {.justify_between().relative().bg(entry_bg)- .when(index < plan.entries.len() - 1, |parent| {+ .when(index < entries.len() - 1, |parent| {parent.border_color(cx.theme().colors().border).border_b_1()}).overflow_hidden()@@ -14462,6 +14549,28 @@ pub(crate) fn open_link(}}+/// The first markdown heading, used as the collapsed summary of a markdown plan.+fn markdown_plan_heading(source: &str) -> Option<&str> {+ source.lines().find_map(|line| {+ let line = line.trim_start();+ let heading = line.trim_start_matches('#');+ let level = line.len() - heading.len();+ let heading = heading.trim();+ ((1..=6).contains(&level)+ && line[level..].starts_with(char::is_whitespace)+ && !heading.is_empty())+ .then_some(heading)+ })+}++fn plan_file_label(uri: &str) -> String {+ Url::parse(uri)+ .ok()+ .and_then(|url| url.to_file_path().ok())+ .and_then(|path| Some(path.file_name()?.to_string_lossy().into_owned()))+ .unwrap_or_else(|| uri.to_owned())+}+fn file_link_parts(input: &str, path_style: PathStyle) -> Option<(&str, Option<&str>)> {let (path, fragment) = input.split_once('#')