Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
acp_thread: Show ACP session messages in the transcript (#66028)
Ben Brandte96ffb0fd3cc
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rsindex 69c1d590a30..18b42f839d3 100644--- a/crates/acp_thread/src/acp_thread.rs+++ b/crates/acp_thread/src/acp_thread.rs@@ -359,6 +359,7 @@ pub enum MessageKind {User,Assistant,Thought,+ Session,}#[derive(Debug)]@@ -386,6 +387,32 @@ impl UserMessage {}}+/// A message between this session and another, such as a parent and its subagent. The+/// session that sent it is the outgoing view; the session that received it is the incoming+/// view. Either participant may be unknown.+#[derive(Debug)]+pub struct SessionMessage {+ pub identity: MessageIdentity,+ pub sender_session_id: Option<acp_v2::SessionId>,+ pub recipient_session_id: Option<acp_v2::SessionId>,+ pub meta: Option<acp_v2::Meta>,+ pub content: MessageContent,+}++impl SessionMessage {+ fn to_markdown(&self, cx: &App) -> String {+ let heading = match (&self.sender_session_id, &self.recipient_session_id) {+ (Some(sender), Some(recipient)) => {+ format!("## Message from `{sender}` to `{recipient}`")+ }+ (Some(sender), None) => format!("## Message from `{sender}`"),+ (None, Some(recipient)) => format!("## Message to `{recipient}`"),+ (None, None) => "## Session message".to_string(),+ };+ format!("{heading}\n\n{}\n\n", self.content.to_markdown(cx))+ }+}+#[derive(Debug, PartialEq)]pub struct AssistantMessage {pub chunks: Vec<AssistantMessageChunk>,@@ -475,12 +502,17 @@ enum MessageLocation {entry_index: usize,chunk_index: usize,},+ Session {+ entry_index: usize,+ },}impl MessageLocation {fn entry_index(self) -> usize {match self {- Self::User { entry_index } | Self::Assistant { entry_index, .. } => entry_index,+ Self::User { entry_index }+ | Self::Assistant { entry_index, .. }+ | Self::Session { entry_index } => entry_index,}}@@ -498,6 +530,9 @@ impl MessageLocation {| AssistantMessageChunk::Thought { block, meta, .. } => Some((block, meta)),}}+ (Self::Session { .. }, AgentThreadEntry::SessionMessage(message)) => {+ Some((&mut message.content, &mut message.meta))+ }_ => None,}}@@ -515,6 +550,7 @@ impl MessageLocation {pub enum AgentThreadEntry {UserMessage(UserMessage),AssistantMessage(AssistantMessage),+ SessionMessage(SessionMessage),ToolCall(ToolCall),Elicitation(ElicitationEntryId),ContextCompaction(ContextCompaction),@@ -978,6 +1014,7 @@ impl AgentThreadEntry {match self {Self::UserMessage(message) => message.indented,Self::AssistantMessage(message) => message.indented,+ Self::SessionMessage(_) => false,Self::ToolCall(_) => false,Self::Elicitation(_) => false,Self::ContextCompaction(_) => false,@@ -994,6 +1031,7 @@ impl AgentThreadEntry {| AssistantMessageChunk::Thought { block, .. }) = chunk;block.markdowns().any(has_pending_render)}),+ Self::SessionMessage(message) => message.content.markdowns().any(has_pending_render),Self::ToolCall(call) => {has_pending_render(&call.label)|| call@@ -1018,6 +1056,7 @@ impl AgentThreadEntry {match self {Self::UserMessage(message) => message.to_markdown(cx),Self::AssistantMessage(message) => message.to_markdown(cx),+ Self::SessionMessage(message) => message.to_markdown(cx),Self::ToolCall(tool_call) => tool_call.to_markdown(cx),Self::Elicitation(_) => "## Input Requested\n\n".to_string(),Self::ContextCompaction(compaction) => {@@ -4253,6 +4292,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::Elicitation(_)| AgentThreadEntry::AssistantMessage(_)+ | AgentThreadEntry::SessionMessage(_)| AgentThreadEntry::ContextCompaction(_) => {}}}@@ -4618,6 +4658,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::Elicitation(_)| AgentThreadEntry::AssistantMessage(_)+ | AgentThreadEntry::SessionMessage(_)| AgentThreadEntry::ContextCompaction(_) => {}}}@@ -4640,6 +4681,7 @@ impl AcpThread {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::Elicitation(_)| AgentThreadEntry::AssistantMessage(_)+ | AgentThreadEntry::SessionMessage(_)| AgentThreadEntry::ContextCompaction(_) => {}}}@@ -4652,6 +4694,7 @@ impl AcpThread {match entry {AgentThreadEntry::UserMessage(..) => return false,AgentThreadEntry::AssistantMessage(..)+ | AgentThreadEntry::SessionMessage(_)| AgentThreadEntry::ContextCompaction(_)| AgentThreadEntry::Elicitation(_) => continue,AgentThreadEntry::ToolCall(..) => return true,@@ -4783,6 +4826,47 @@ impl AcpThread {cx,);}+ acp_v1::SessionUpdate::SessionMessage(message) => {+ let content = match message.content {+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,+ MaybeUndefined::Null => MaybeUndefined::Null,+ MaybeUndefined::Value(blocks) => MaybeUndefined::Value(+ blocks+ .into_iter()+ .map(content::from_v1)+ .collect::<Result<Vec<_>>>()+ .map_err(acp_v1::Error::from)?,+ ),+ };+ self.upsert_session_message_inner(+ acp_v2::SessionMessage::new(message.message_id.0)+ .sender_session_id(+ message+ .sender_session_id+ .map(|id| acp_v2::SessionId::new(id.0)),+ )+ .recipient_session_id(+ message+ .recipient_session_id+ .map(|id| acp_v2::SessionId::new(id.0)),+ )+ .content(content)+ .meta(message.meta),+ MetadataUpdate::V1,+ cx,+ )+ .map_err(acp_v1::Error::from)?;+ }+ acp_v1::SessionUpdate::SessionMessageChunk(chunk) => {+ self.append_session_message_chunk(+ acp_v2::SessionMessageChunk::new(+ chunk.message_id.0,+ content::from_v1(chunk.content).map_err(acp_v1::Error::from)?,+ ),+ cx,+ )+ .map_err(acp_v1::Error::from)?;+ }_ => {}}Ok(())@@ -4797,7 +4881,7 @@ impl AcpThread {MessageKind::User,update.message_id,update.content,- update.meta,+ MetadataUpdate::V2(update.meta),cx,)}@@ -4811,7 +4895,7 @@ impl AcpThread {MessageKind::Assistant,update.message_id,update.content,- update.meta,+ MetadataUpdate::V2(update.meta),cx,)}@@ -4825,21 +4909,114 @@ impl AcpThread {MessageKind::Thought,update.message_id,update.content,- update.meta,+ MetadataUpdate::V2(update.meta),cx,)}+ pub fn upsert_session_message(+ &mut self,+ update: acp_v2::SessionMessage,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ self.upsert_session_message_inner(update, MetadataUpdate::V2, cx)+ }++ fn upsert_session_message_inner(+ &mut self,+ update: acp_v2::SessionMessage,+ metadata: fn(MaybeUndefined<acp_v2::Meta>) -> MetadataUpdate,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ let previous_entry_count = self.entries.len();+ let location = self.session_message_location(+ update.message_id,+ update.sender_session_id,+ update.recipient_session_id,+ cx,+ )?;+ self.replace_message_content(+ location,+ MessageKind::Session,+ update.content,+ metadata(update.meta),+ previous_entry_count,+ cx,+ )+ }++ pub fn append_session_message_chunk(+ &mut self,+ chunk: acp_v2::SessionMessageChunk,+ cx: &mut Context<Self>,+ ) -> Result<()> {+ // A chunk carries only content: its metadata does not patch the message's, and the+ // RFD keeps a message's participants on `session_message`, so the participant fields+ // that this schema version still has on chunks are ignored.+ let previous_entry_count = self.entries.len();+ let location = self.keyed_message_location(MessageKind::Session, chunk.message_id, cx)?;+ self.append_message_content(+ location,+ MessageKind::Session,+ chunk.content,+ previous_entry_count,+ cx,+ )+ }++ /// Participants that an update omits keep their earlier value, and a known participant+ /// cannot change.+ fn session_message_location(+ &mut self,+ id: acp_v2::MessageId,+ sender: Option<acp_v2::SessionId>,+ recipient: Option<acp_v2::SessionId>,+ cx: &mut Context<Self>,+ ) -> Result<MessageLocation> {+ let location = self.keyed_message_location(MessageKind::Session, id, cx)?;+ let Some(AgentThreadEntry::SessionMessage(message)) =+ self.entries.get_mut(location.entry_index())+ else {+ anyhow::bail!("session message disappeared during update");+ };+ for (stored, reported) in [+ (&mut message.sender_session_id, sender),+ (&mut message.recipient_session_id, recipient),+ ] {+ let Some(reported) = reported else {+ continue;+ };+ anyhow::ensure!(+ stored.as_ref().is_none_or(|stored| stored == &reported),+ "Session message participants cannot change"+ );+ *stored = Some(reported);+ }+ Ok(location)+ }+fn update_keyed_message(&mut self,kind: MessageKind,id: acp_v2::MessageId,content: MaybeUndefined<Vec<acp_v2::ContentBlock>>,- meta: MaybeUndefined<acp_v2::Meta>,+ meta: MetadataUpdate,cx: &mut Context<Self>,) -> Result<()> {let previous_entry_count = self.entries.len();let location = self.keyed_message_location(kind, id, cx)?;+ self.replace_message_content(location, kind, content, meta, previous_entry_count, cx)+ }++ fn replace_message_content(+ &mut self,+ location: MessageLocation,+ kind: MessageKind,+ content: MaybeUndefined<Vec<acp_v2::ContentBlock>>,+ meta: MetadataUpdate,+ previous_entry_count: usize,+ cx: &mut Context<Self>,+ ) -> Result<()> {if !content.is_undefined()&& self.streaming_text_buffer@@ -4868,7 +5045,7 @@ impl AcpThread {message_content.replace(replacement, &language_registry, path_style, cx);}}- MetadataUpdate::V2(meta).apply(message_meta);+ meta.apply(message_meta);self.emit_message_update(location, previous_entry_count, cx);Ok(())}@@ -4887,6 +5064,17 @@ impl AcpThread {} = chunk;let previous_entry_count = self.entries.len();let location = self.keyed_message_location(kind, message_id, cx)?;+ self.append_message_content(location, kind, content, previous_entry_count, cx)+ }++ fn append_message_content(+ &mut self,+ location: MessageLocation,+ kind: MessageKind,+ content: acp_v2::ContentBlock,+ previous_entry_count: usize,+ cx: &mut Context<Self>,+ ) -> Result<()> {let content = match content {acp_v2::ContentBlock::Text(text) => {let (content, _) = location@@ -4955,6 +5143,11 @@ impl AcpThread {{Some(MessageLocation::User { entry_index })}+ AgentThreadEntry::SessionMessage(message)+ if kind == MessageKind::Session && message.identity == identity =>+ {+ Some(MessageLocation::Session { entry_index })+ }AgentThreadEntry::AssistantMessage(message) => message.chunks.iter()@@ -4988,6 +5181,17 @@ impl AcpThread {}));Ok(MessageLocation::User { entry_index })}+ MessageKind::Session => {+ self.entries+ .push(AgentThreadEntry::SessionMessage(SessionMessage {+ identity,+ sender_session_id: None,+ recipient_session_id: None,+ meta: None,+ content: MessageContent::default(),+ }));+ Ok(MessageLocation::Session { entry_index })+ }MessageKind::Assistant | MessageKind::Thought => {let chunk = if kind == MessageKind::Thought {AssistantMessageChunk::Thought {@@ -11318,6 +11522,9 @@ mod tests {AgentThreadEntry::UserMessage(message) => {(&message.identity, &message.content, &message.meta)}+ AgentThreadEntry::SessionMessage(message) => {+ (&message.identity, &message.content, &message.meta)+ }AgentThreadEntry::AssistantMessage(message) => {let [chunk] = message.chunks.as_slice() else {panic!("expected one assistant chunk");@@ -11339,6 +11546,23 @@ mod tests {}}+ /// Session messages take chunks through their own API, which also records participants.+ fn append_keyed_chunk(+ thread: &mut AcpThread,+ kind: MessageKind,+ chunk: acp_v2::ContentChunk,+ cx: &mut Context<AcpThread>,+ ) -> Result<()> {+ if kind == MessageKind::Session {+ thread.append_session_message_chunk(+ acp_v2::SessionMessageChunk::new(chunk.message_id, chunk.content).meta(chunk.meta),+ cx,+ )+ } else {+ thread.append_message_chunk(kind, chunk, cx)+ }+ }+#[gpui::test]async fn test_unsupported_legacy_prompt_preserves_running_turn(cx: &mut TestAppContext) {init_test(cx);@@ -13454,6 +13678,7 @@ mod tests {MessageKind::User,MessageKind::Assistant,MessageKind::Thought,+ MessageKind::Session,] {let thread = new_test_thread(cx).await;let original = json!([{"type": "text", "text": "original", "_meta": {"block": true}}]);@@ -13520,6 +13745,10 @@ mod tests {serde_json::from_value(patch).expect("thought patch"),cx,),+ MessageKind::Session => thread.upsert_session_message(+ serde_json::from_value(patch).expect("session message patch"),+ cx,+ ),}.expect("apply patch");let (identity, content, meta) = only_keyed_message(thread);@@ -13541,14 +13770,14 @@ mod tests {acp_v2::TextContent::new("chunk").meta(acp_v2::Meta::from_iter([("block".into(), json!(true))])),);- thread- .append_message_chunk(- kind,- acp_v2::ContentChunk::new(block.clone(), "patch")- .meta(acp_v2::Meta::from_iter([("envelope".into(), json!(true))])),- cx,- )- .expect("append scoped metadata");+ append_keyed_chunk(+ thread,+ kind,+ acp_v2::ContentChunk::new(block.clone(), "patch")+ .meta(acp_v2::Meta::from_iter([("envelope".into(), json!(true))])),+ cx,+ )+ .expect("append scoped metadata");let (_, content, meta) = only_keyed_message(thread);assert_eq!(content.source_blocks(), &[block]);assert_eq!(@@ -13559,6 +13788,108 @@ mod tests {}}+ #[gpui::test]+ async fn test_session_messages_keep_participants_and_convert_from_v1(cx: &mut TestAppContext) {+ init_test(cx);+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ thread+ .append_session_message_chunk(+ acp_v2::SessionMessageChunk::new("task", "Start by ".into()),+ cx,+ )+ .expect("a message can start with a chunk and no participants");+ thread+ .upsert_session_message(+ acp_v2::SessionMessage::new("task")+ .sender_session_id(acp_v2::SessionId::new("parent"))+ .recipient_session_id(acp_v2::SessionId::new("child")),+ cx,+ )+ .expect("participants can arrive later");+ thread+ .append_session_message_chunk(+ acp_v2::SessionMessageChunk::new("task", "reproducing".into())+ .sender_session_id(acp_v2::SessionId::new("other")),+ cx,+ )+ .expect("a chunk's participant fields are ignored");+ let error = thread+ .upsert_session_message(+ acp_v2::SessionMessage::new("task")+ .sender_session_id(acp_v2::SessionId::new("other")),+ cx,+ )+ .expect_err("a known participant cannot change");+ assert!(error.to_string().contains("cannot change"), "{error}");+ thread+ .upsert_assistant_message(+ acp_v2::AgentMessage::new("task").content(vec!["answer".into()]),+ cx,+ )+ .expect("assistant messages have their own ID space");++ let [+ AgentThreadEntry::SessionMessage(message),+ AgentThreadEntry::AssistantMessage(_),+ ] = thread.entries()+ else {+ panic!("expected a session message, then an assistant message");+ };+ assert_eq!(message.identity, MessageIdentity::Keyed("task".into()));+ assert_eq!(message.sender_session_id, Some("parent".into()));+ assert_eq!(message.recipient_session_id, Some("child".into()));+ assert_eq!(+ message.content.source_blocks(),+ &["Start by ".into(), "reproducing".into()]+ );+ });++ // v1 replaces message metadata where v2 patches it by key.+ let thread = new_test_thread(cx).await;+ thread.update(cx, |thread, cx| {+ for update in [+ json!({+ "sessionUpdate": "session_message",+ "messageId": "reply",+ "senderSessionId": "child",+ "content": [{"type": "text", "text": "Done"}],+ "_meta": {"first": true},+ }),+ json!({+ "sessionUpdate": "session_message",+ "messageId": "reply",+ "recipientSessionId": "parent",+ "_meta": {"second": true},+ }),+ json!({+ "sessionUpdate": "session_message_chunk",+ "messageId": "reply",+ "senderSessionId": "other",+ "content": {"type": "text", "text": " now"},+ "_meta": {"chunk": true},+ }),+ ] {+ thread+ .handle_session_update(serde_json::from_value(update).expect("v1 update"), cx)+ .expect("v1 session message");+ }+ let [AgentThreadEntry::SessionMessage(message)] = thread.entries() else {+ panic!("expected one session message");+ };+ assert_eq!(message.sender_session_id, Some("child".into()));+ assert_eq!(message.recipient_session_id, Some("parent".into()));+ assert_eq!(+ message.meta,+ Some(acp_v2::Meta::from_iter([("second".into(), json!(true))]))+ );+ assert_eq!(+ message.content.source_blocks(),+ &["Done".into(), " now".into()]+ );+ });+ }+#[gpui::test]async fn test_v2_entity_metadata_patches_by_key(cx: &mut TestAppContext) {init_test(cx);@@ -13567,6 +13898,7 @@ mod tests {MessageKind::User,MessageKind::Assistant,MessageKind::Thought,+ MessageKind::Session,] {messages.push((kind, new_test_thread(cx).await));}@@ -13633,19 +13965,25 @@ mod tests {.meta(metadata.clone()),cx,),+ MessageKind::Session => thread.upsert_session_message(+ acp_v2::SessionMessage::new("metadata")+ .content(vec![block.clone()])+ .meta(metadata.clone()),+ cx,+ ),}.expect("message upsert");let (_, content, stored) = only_keyed_message(thread);assert_eq!(stored, &expected, "{kind:?}");assert_eq!(content.source_blocks(), std::slice::from_ref(&block));- thread- .append_message_chunk(- *kind,- acp_v2::ContentChunk::new("chunk".into(), "metadata")- .meta(snapshot_meta.clone()),- cx,- )- .expect("message chunk");+ append_keyed_chunk(+ thread,+ *kind,+ acp_v2::ContentChunk::new("chunk".into(), "metadata")+ .meta(snapshot_meta.clone()),+ cx,+ )+ .expect("message chunk");assert_eq!(only_keyed_message(thread).2, &expected);});}diff --git a/crates/agent_servers/src/acp/session_updates.rs b/crates/agent_servers/src/acp/session_updates.rsindex cc2bdf06b4d..4113e177041 100644--- a/crates/agent_servers/src/acp/session_updates.rs+++ b/crates/agent_servers/src/acp/session_updates.rs@@ -154,6 +154,8 @@ pub enum InboundSessionUpdate {UserMessage(acp_v2::UserMessage),AgentMessage(acp_v2::AgentMessage),AgentThought(acp_v2::AgentThought),+ SessionMessage(acp_v2::SessionMessage),+ SessionMessageChunk(acp_v2::SessionMessageChunk),UserMessageChunk(acp_v2::ContentChunk),AgentMessageChunk(acp_v2::ContentChunk),AgentThoughtChunk(acp_v2::ContentChunk),@@ -201,6 +203,12 @@ impl TryFrom<acp_v2::UpdateSessionNotification> for InboundSessionNotification {acp_v2::SessionUpdate::AgentThought(thought) => {InboundSessionUpdate::AgentThought(thought)}+ acp_v2::SessionUpdate::SessionMessage(message) => {+ InboundSessionUpdate::SessionMessage(message)+ }+ acp_v2::SessionUpdate::SessionMessageChunk(chunk) => {+ InboundSessionUpdate::SessionMessageChunk(chunk)+ }acp_v2::SessionUpdate::UserMessageChunk(chunk) => {InboundSessionUpdate::UserMessageChunk(chunk)}@@ -280,6 +288,12 @@ impl InboundSessionNotification {thread.upsert_assistant_message(message, cx)}InboundSessionUpdate::AgentThought(thought) => thread.upsert_thought(thought, cx),+ InboundSessionUpdate::SessionMessage(message) => {+ thread.upsert_session_message(message, cx)+ }+ InboundSessionUpdate::SessionMessageChunk(chunk) => {+ thread.append_session_message_chunk(chunk, cx)+ }InboundSessionUpdate::UserMessageChunk(chunk) => {thread.append_message_chunk(MessageKind::User, chunk, cx)}diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rsindex 9e8f7386633..670a81f39b4 100644--- a/crates/agent_servers/src/acp/v1.rs+++ b/crates/agent_servers/src/acp/v1.rs@@ -8007,20 +8007,36 @@ exit 7let parent_id = parent_session_id.0.to_string();let unadvertised = context_for(false, cx);- handle_session_notification(- acp::SessionNotification::new(- parent_id.clone(),- acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child")),- ),- &mut cx.to_async(),- &unadvertised,- );+ let delegation = || {+ acp::SessionMessage::new("delegation")+ .sender_session_id(acp::SessionId::new(parent_id.clone()))+ .recipient_session_id(acp::SessionId::new("child"))+ .content(vec!["Investigate".into()])+ };+ for update in [+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child")),+ acp::SessionUpdate::SessionMessage(delegation()),+ acp::SessionUpdate::SessionMessageChunk(acp::SessionMessageChunk::new(+ "delegation",+ " more".into(),+ )),+ ] {+ handle_session_notification(+ acp::SessionNotification::new(parent_id.clone(), update),+ &mut cx.to_async(),+ &unadvertised,+ );+ }parent.read_with(cx, |parent, _| {assert_eq!(parent.subagents().count(),0,"without the advertised capability, a v1 agent's subagent updates are ignored");+ assert!(+ parent.entries().is_empty(),+ "and so are its session messages"+ );});assert!(!sessions@@ -8055,6 +8071,20 @@ exit 7acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Working".into())),cx,);+ notify(+ &parent_id,+ acp::SessionUpdate::SessionMessage(delegation()),+ cx,+ );+ parent.read_with(cx, |parent, _| {+ assert!(+ matches!(+ parent.entries(),+ [acp_thread::AgentThreadEntry::SessionMessage(_)]+ ),+ "with the capability, session messages are applied"+ );+ });let child = parent.read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned()).expect("the parent owns the announced subagent");@@ -8791,6 +8821,7 @@ exit 7.map(|entry| match entry {acp_thread::AgentThreadEntry::UserMessage(_) => "user",acp_thread::AgentThreadEntry::AssistantMessage(_) => "assistant",+ acp_thread::AgentThreadEntry::SessionMessage(_) => "session_message",acp_thread::AgentThreadEntry::ToolCall(_) => "tool_call",acp_thread::AgentThreadEntry::Elicitation(_) => "elicitation",acp_thread::AgentThreadEntry::ContextCompaction(_) => "compaction",@@ -9791,13 +9822,20 @@ fn handle_session_notification(return;};+ if matches!(+ notification.update,+ acp::SessionUpdate::SubagentUpdate(_)+ | acp::SessionUpdate::SessionMessage(_)+ | acp::SessionUpdate::SessionMessageChunk(_)+ ) && !ctx.accepts_subagent_updates+ {+ log::warn!(+ "Ignoring a subagents update for {session_id:?}: Zed did not advertise the subagents capability"+ );+ return;+ }+if let acp::SessionUpdate::SubagentUpdate(update) = notification.update {- if !ctx.accepts_subagent_updates {- log::warn!(- "Ignoring subagent update for {session_id:?}: Zed did not advertise the subagents capability"- );- return;- }if let Err(error) =cx.update(|cx| apply_v1_subagent_update(&strong_thread, update, &ctx.sessions, cx)){diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rsindex e6c9929532a..bb5a5e6be82 100644--- a/crates/agent_servers/src/acp/v2.rs+++ b/crates/agent_servers/src/acp/v2.rs@@ -2374,6 +2374,94 @@ mod tests {});}+ #[gpui::test]+ async fn v2_session_messages_reach_both_transcripts(cx: &mut TestAppContext) {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let parent = harness.thread(cx).await;+ harness.send_update(+ "session",+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child")),+ );+ let message = acp::SessionMessage::new("delegation")+ .sender_session_id(acp::SessionId::new("session"))+ .recipient_session_id(acp::SessionId::new("child"))+ .content(vec!["Investigate the failure".into()]);+ harness.send_update(+ "session",+ acp::SessionUpdate::SessionMessage(message.clone()),+ );+ harness.send_update("child", acp::SessionUpdate::SessionMessage(message));+ harness.send_update(+ "child",+ acp::SessionUpdate::SessionMessageChunk(acp::SessionMessageChunk::new(+ "delegation",+ " on Windows".into(),+ )),+ );+ harness.drain_updates(cx).await;++ let child = parent+ .read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned())+ .expect("announced subagent");+ for (thread, expected_blocks) in [+ (&parent, vec!["Investigate the failure".into()]),+ (+ &child,+ vec!["Investigate the failure".into(), " on Windows".into()],+ ),+ ] {+ thread.read_with(cx, |thread, _| {+ let [acp_thread::AgentThreadEntry::SessionMessage(message)] = thread.entries()+ else {+ panic!("expected one session message in {}", thread.session_id());+ };+ assert_eq!(message.sender_session_id, Some("session".into()));+ assert_eq!(message.recipient_session_id, Some("child".into()));+ assert_eq!(message.content.source_blocks(), expected_blocks.as_slice());+ });+ }+ }++ #[gpui::test]+ async fn v2_resume_replay_delivers_subagent_history(cx: &mut TestAppContext) {+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;+ let loading = harness.reopen(true, cx);+ let (_, responder) = bounded(harness.resume_requests.recv(), cx)+ .await+ .expect("resume");+ harness.send_update(+ "saved",+ acp::SessionUpdate::SubagentUpdate(acp::SubagentUpdate::new("child")),+ );+ harness.send_update(+ "child",+ acp::SessionUpdate::AgentMessage(+ acp::AgentMessage::new("child-history").content(vec!["Replayed".into()]),+ ),+ );+ let initial = initial_response();+ responder+ .respond(+ acp::ResumeSessionResponse::new()+ .config_options(initial.config_options)+ .available_commands(initial.available_commands),+ )+ .expect("resumed");+ let parent = bounded(loading, cx).await.expect("resumed parent");+ cx.run_until_parked();++ let child = parent+ .read_with(cx, |parent, _| parent.subagent(&"child".into()).cloned())+ .expect("the replayed announcement creates the subagent");+ child.read_with(cx, |child, _| {+ assert_eq!(+ child.entries().len(),+ 1,+ "history replayed before the resume response reaches the subagent"+ );+ });+ }+#[gpui::test]async fn v2_subagent_updates_route_and_patch_child_sessions(cx: &mut TestAppContext) {use acp_thread::{ThreadStatus, subagents::SubagentAssociation};diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rsindex bc94442fc0d..124299aecc2 100644--- a/crates/agent_ui/src/conversation_view.rs+++ b/crates/agent_ui/src/conversation_view.rs@@ -20162,6 +20162,146 @@ pub(crate) mod tests {assert_eq!(label(&acp_child, cx), "Parent title");}+ #[test]+ fn session_message_side_follows_the_transcripts_own_session() {+ use thread_view::{SessionMessageSide, session_message_side};++ let own = acp_v2::SessionId::new("own");+ let other = acp_v2::SessionId::new("other");+ for (sender, recipient, expected) in [+ (+ Some("own"),+ Some("other"),+ SessionMessageSide::Outgoing {+ recipient: Some(&other),+ },+ ),+ (+ Some("own"),+ None,+ SessionMessageSide::Outgoing { recipient: None },+ ),+ (+ Some("other"),+ Some("own"),+ SessionMessageSide::Incoming {+ sender: Some(&other),+ },+ ),+ (+ None,+ Some("own"),+ SessionMessageSide::Incoming { sender: None },+ ),+ (+ Some("other"),+ None,+ SessionMessageSide::Incoming {+ sender: Some(&other),+ },+ ),+ (+ None,+ Some("other"),+ SessionMessageSide::Outgoing {+ recipient: Some(&other),+ },+ ),+ (None, None, SessionMessageSide::Unknown),+ ] {+ let message = acp_thread::SessionMessage {+ identity: acp_thread::MessageIdentity::Keyed("message".into()),+ sender_session_id: sender.map(acp_v2::SessionId::new),+ recipient_session_id: recipient.map(acp_v2::SessionId::new),+ meta: None,+ content: acp_thread::MessageContent::default(),+ };+ assert_eq!(+ session_message_side(&message, &own),+ expected,+ "{sender:?} -> {recipient:?}"+ );+ }+ }++ #[gpui::test]+ async fn test_session_message_participant_opens_its_session(cx: &mut TestAppContext) {+ init_test(cx);+ let connection = StubAgentConnection::new();+ let (conversation_view, cx) =+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;+ add_to_workspace_with_size(conversation_view.clone(), true, cx);+ let root =+ active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());+ let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone());+ let child = conversation_view.update(cx, |view, cx| {+ create_test_acp_subagent(+ root_session_id.clone(),+ "child",+ Rc::new(connection.clone()),+ view.project.clone(),+ cx,+ )+ });+ child.update(cx, |child, cx| {+ child+ .update_subagent_association(+ &acp_v2::SubagentUpdate::new("child").title("Investigator"),+ cx,+ )+ .expect("ACP subagent")+ });+ // Each ACP notification is applied in its own update, as here.+ root.update(cx, |root, cx| root.register_subagent(child.clone(), cx));+ root.update(cx, |root, cx| {+ root.upsert_session_message(+ acp_v2::SessionMessage::new("to-child")+ .sender_session_id(root_session_id.clone())+ .recipient_session_id(acp_v2::SessionId::new("child"))+ .content(vec!["Investigate the failure".into()]),+ cx,+ )+ })+ .expect("outgoing message");+ root.update(cx, |root, cx| {+ root.upsert_session_message(+ acp_v2::SessionMessage::new("from-unknown")+ .sender_session_id(acp_v2::SessionId::new("unknown"))+ .recipient_session_id(root_session_id.clone())+ .content(vec!["Hello".into()]),+ cx,+ )+ })+ .expect("incoming message");+ cx.run_until_parked();++ active_thread(&conversation_view, cx).read_with(cx, |view, cx| {+ for (session_id, expected) in [+ ("child", Some("Investigator")),+ (root_session_id.0.as_ref(), Some("Main Agent")),+ ("unknown", None),+ ] {+ assert_eq!(+ view.session_participant_label(&acp_v2::SessionId::new(session_id), cx),+ expected.map(SharedString::from),+ "{session_id}"+ );+ }+ });+ assert!(+ cx.debug_bounds("session-message-participant-1").is_none(),+ "an unknown participant is not a link"+ );+ let link = cx+ .debug_bounds("session-message-participant-0")+ .expect("the recipient links to its session");+ cx.simulate_click(link.center(), gpui::Modifiers::default());+ cx.run_until_parked();+ let active_session_id = active_thread(&conversation_view, cx)+ .read_with(cx, |view, cx| view.thread.read(cx).session_id().clone());+ assert_eq!(active_session_id, acp_v2::SessionId::new("child"));+ }+#[gpui::test]async fn test_release_policy_does_not_disable_explicit_close(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 3f7175fec1e..0a1aa6a42c4 100644--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs@@ -951,6 +951,9 @@ fn collect_markdowns(let mut out = Vec::new();match entry {AgentThreadEntry::UserMessage(_) => {}+ AgentThreadEntry::SessionMessage(message) => {+ out.extend(message.content.markdowns().cloned())+ }AgentThreadEntry::AssistantMessage(message) => {for (chunk_ix, chunk) in message.chunks.iter().enumerate() {match chunk {diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rsindex 385cfabe5b2..af8d9075ccd 100644--- a/crates/agent_ui/src/conversation_view/thread_view.rs+++ b/crates/agent_ui/src/conversation_view/thread_view.rs@@ -58,6 +58,38 @@ use super::elicitation::{use super::subagent_card::{SubagentCardState, SubagentStatus};use super::*;+/// Which side of a session message a transcript shows, and the other participant when it+/// is known.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum SessionMessageSide<'a> {+ Outgoing {+ recipient: Option<&'a acp_v2::SessionId>,+ },+ Incoming {+ sender: Option<&'a acp_v2::SessionId>,+ },+ Unknown,+}++/// The transcript's own session is always one participant, so a single known participant+/// that is another session also tells the direction.+pub(super) fn session_message_side<'a>(+ message: &'a acp_thread::SessionMessage,+ own_session_id: &acp_v2::SessionId,+) -> SessionMessageSide<'a> {+ let sender = message.sender_session_id.as_ref();+ let recipient = message.recipient_session_id.as_ref();+ if sender == Some(own_session_id) {+ SessionMessageSide::Outgoing { recipient }+ } else if recipient == Some(own_session_id) || sender.is_some() {+ SessionMessageSide::Incoming { sender }+ } else if recipient.is_some() {+ SessionMessageSide::Outgoing { recipient }+ } else {+ SessionMessageSide::Unknown+ }+}+/// How a parent's view names a subagent. An ACP parent's own title for the subagent/// describes it in that view, so it wins over the subagent's title for itself.pub(super) fn subagent_label(thread: &AcpThread) -> SharedString {@@ -7535,6 +7567,19 @@ impl ThreadView {AgentThreadEntry::ContextCompaction(compaction) => {self.render_context_compaction(entry_ix, compaction, window, cx)}+ AgentThreadEntry::SessionMessage(message) => {+ let session_message = self.render_session_message(entry_ix, message, window, cx);+ if let Some(handle) = self+ .entry_view_state+ .read(cx)+ .entry(entry_ix)+ .and_then(|entry| entry.focus_handle(cx))+ {+ session_message.track_focus(&handle).into_any()+ } else {+ session_message.into_any()+ }+ }};let is_subagent_output = self.is_subagent()@@ -8851,6 +8896,7 @@ impl ThreadView {AgentThreadEntry::ToolCall(_)| AgentThreadEntry::Elicitation(_)| AgentThreadEntry::AssistantMessage(_)+ | AgentThreadEntry::SessionMessage(_)| AgentThreadEntry::ContextCompaction(_) => {}}}@@ -8858,6 +8904,90 @@ impl ThreadView {has_running_terminal_call}+ fn render_session_message(+ &self,+ entry_ix: usize,+ message: &acp_thread::SessionMessage,+ window: &Window,+ cx: &Context<Self>,+ ) -> Div {+ let own_session_id = self.thread.read(cx).session_id().clone();+ let (icon, direction, participant) = match session_message_side(message, &own_session_id) {+ SessionMessageSide::Outgoing { recipient } => (IconName::Send, "To", recipient),+ SessionMessageSide::Incoming { sender } => (IconName::Envelope, "From", sender),+ SessionMessageSide::Unknown => (IconName::Envelope, "Message between sessions", None),+ };+ let participant = participant.map(|session_id| {+ match self.session_participant_label(session_id, cx) {+ Some(label) => div()+ .debug_selector(move || format!("session-message-participant-{entry_ix}"))+ .child(+ Button::new(("session-message-participant", entry_ix), label)+ .label_size(LabelSize::Small)+ .tooltip(Tooltip::text("Open Session"))+ .on_click(cx.listener({+ let session_id = session_id.clone();+ move |this, _, window, cx| {+ this.server_view+ .update(cx, |view, cx| {+ view.navigate_to_thread(session_id.clone(), window, cx)+ })+ .log_err();+ }+ })),+ )+ .into_any_element(),+ // The RFD allows messages naming a session this conversation never learned about.+ None => Label::new("Unavailable Session")+ .size(LabelSize::Small)+ .color(Color::Muted)+ .into_any_element(),+ }+ });++ v_flex()+ .px_5()+ .py_1p5()+ .w_full()+ .gap_1p5()+ .text_ui(cx)+ .child(+ h_flex()+ .gap_1p5()+ .child(Icon::new(icon).size(IconSize::Small).color(Color::Muted))+ .child(+ Label::new(direction)+ .size(LabelSize::Small)+ .color(Color::Muted),+ )+ .children(participant),+ )+ .child(+ div()+ .pl_3()+ .border_l_2()+ .border_color(cx.theme().colors().border)+ .child(self.render_message_content(entry_ix, 0, &message.content, window, cx)),+ )+ }++ /// How this conversation names another of its sessions, or `None` when it has no thread+ /// for that session.+ pub(super) fn session_participant_label(+ &self,+ session_id: &acp_v2::SessionId,+ cx: &App,+ ) -> Option<SharedString> {+ let server_view = self.server_view.upgrade()?;+ let thread_view = server_view.read(cx).thread_view(session_id)?;+ let thread = thread_view.read(cx).thread.read(cx);+ Some(if thread.parent_session_id().is_none() {+ "Main Agent".into()+ } else {+ subagent_label(thread)+ })+ }+fn render_collapsible_command(&self,group: SharedString,diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rsindex f36f15e9b96..143ee2bbc0d 100644--- a/crates/agent_ui/src/entry_view_state.rs+++ b/crates/agent_ui/src/entry_view_state.rs@@ -549,6 +549,16 @@ impl EntryViewState {);}}+ AgentThreadEntry::SessionMessage(_) => {+ if !matches!(self.entries.get(index), Some(Entry::SessionMessage { .. })) {+ self.set_entry(+ index,+ Entry::SessionMessage {+ focus_handle: cx.focus_handle(),+ },+ );+ }+ }AgentThreadEntry::AssistantMessage(message) => {let entry = if let Some(Entry::AssistantMessage(entry)) =self.entries.get_mut(index)@@ -620,6 +630,7 @@ impl EntryViewState {match entry {Entry::UserMessage { .. }| Entry::AssistantMessage { .. }+ | Entry::SessionMessage { .. }| Entry::Elicitation { .. }| Entry::ContextCompaction => {}Entry::ToolCall(ToolCallEntry { content, .. }) => {@@ -698,6 +709,9 @@ pub enum Entry {synced_source_version: acp_thread::MessageContentVersion,},AssistantMessage(AssistantMessageEntry),+ SessionMessage {+ focus_handle: FocusHandle,+ },ToolCall(ToolCallEntry),Elicitation {focus_handle: FocusHandle,@@ -710,6 +724,7 @@ impl Entry {match self {Self::UserMessage { editor, .. } => Some(editor.read(cx).focus_handle(cx)),Self::AssistantMessage(message) => Some(message.focus_handle.clone()),+ Self::SessionMessage { focus_handle } => Some(focus_handle.clone()),Self::ToolCall(tool_call) => Some(tool_call.focus_handle.clone()),Self::Elicitation { focus_handle } => Some(focus_handle.clone()),Self::ContextCompaction => None,@@ -720,6 +735,7 @@ impl Entry {match self {Self::UserMessage { editor, .. } => Some(editor),Self::AssistantMessage(_)+ | Self::SessionMessage { .. }| Self::ToolCall(_)| Self::Elicitation { .. }| Self::ContextCompaction => None,@@ -757,6 +773,7 @@ impl Entry {match self {Self::AssistantMessage(message) => message.scroll_handle_for_chunk(chunk_ix),Self::UserMessage { .. }+ | Self::SessionMessage { .. }| Self::ToolCall(_)| Self::Elicitation { .. }| Self::ContextCompaction => None,@@ -776,6 +793,7 @@ impl Entry {Self::ToolCall(ToolCallEntry { content, .. }) => !content.is_empty(),Self::UserMessage { .. }| Self::AssistantMessage(_)+ | Self::SessionMessage { .. }| Self::Elicitation { .. }| Self::ContextCompaction => false,}@@ -793,6 +811,7 @@ impl Focusable for Entry {match self {Self::UserMessage { editor, .. } => editor.read(cx).focus_handle(cx),Self::AssistantMessage(message) => message.focus_handle.clone(),+ Self::SessionMessage { focus_handle } => focus_handle.clone(),Self::ToolCall(tool_call) => tool_call.focus_handle.clone(),Self::Elicitation { focus_handle } => focus_handle.clone(),Self::ContextCompaction => cx.focus_handle(),