Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

acp: Handle acp message ids when we get them (#59927)

Ben Brandt70fd3c577468
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index 1efe43188b4..07c6cb092e9 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -283,7 +283,9 @@ pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<Subag
#[derive(Debug)]
pub struct UserMessage {
- pub id: Option<UserMessageId>,
+ pub protocol_id: Option<acp::MessageId>,
+ pub client_id: Option<ClientUserMessageId>,
+ pub is_optimistic: bool,
pub content: ContentBlock,
pub chunks: Vec<acp::ContentBlock>,
pub checkpoint: Option<Checkpoint>,
@@ -336,8 +338,14 @@ impl AssistantMessage {
#[derive(Debug, PartialEq)]
pub enum AssistantMessageChunk {
- Message { block: ContentBlock },
- Thought { block: ContentBlock },
+ Message {
+ id: Option<acp::MessageId>,
+ block: ContentBlock,
+ },
+ Thought {
+ id: Option<acp::MessageId>,
+ block: ContentBlock,
+ },
}
impl AssistantMessageChunk {
@@ -348,20 +356,31 @@ impl AssistantMessageChunk {
cx: &mut App,
) -> Self {
Self::Message {
+ id: None,
block: ContentBlock::new(chunk.into(), language_registry, path_style, cx),
}
}
fn to_markdown(&self, cx: &App) -> String {
match self {
- Self::Message { block } => block.to_markdown(cx).to_string(),
- Self::Thought { block } => {
+ Self::Message { block, .. } => block.to_markdown(cx).to_string(),
+ Self::Thought { block, .. } => {
format!("<thinking>\n{}\n</thinking>", block.to_markdown(cx))
}
}
}
}
+fn can_merge_message_chunks(
+ existing: Option<&acp::MessageId>,
+ incoming: Option<&acp::MessageId>,
+) -> bool {
+ match (existing, incoming) {
+ (Some(existing), Some(incoming)) => existing == incoming,
+ _ => true,
+ }
+}
+
#[derive(Debug)]
pub enum AgentThreadEntry {
UserMessage(UserMessage),
@@ -2014,8 +2033,8 @@ impl AcpThread {
};
for chunk in chunks {
let block = match chunk {
- AssistantMessageChunk::Message { block } => block,
- AssistantMessageChunk::Thought { block } => block,
+ AssistantMessageChunk::Message { block, .. } => block,
+ AssistantMessageChunk::Thought { block, .. } => block,
};
if let Some(markdown) = block.markdown() {
markdown.update(cx, |markdown, cx| {
@@ -2142,24 +2161,54 @@ impl AcpThread {
cx: &mut Context<Self>,
) -> Result<(), acp::Error> {
match update {
- acp::SessionUpdate::UserMessageChunk(acp::ContentChunk { content, .. }) => {
+ acp::SessionUpdate::UserMessageChunk(acp::ContentChunk {
+ content,
+ message_id,
+ ..
+ }) => {
// We optimistically add the full user prompt before calling `prompt`.
- // Some ACP servers echo user chunks back over updates. Skip the chunk if
- // it's already present in the current user message to avoid duplicating content.
+ // Some ACP servers echo user chunks back over updates. Skip echoed
+ // chunks only when they match the local optimistic message.
let already_in_user_message = self
.entries
- .last()
- .and_then(|entry| entry.user_message())
- .is_some_and(|message| message.chunks.contains(&content));
+ .last_mut()
+ .and_then(|entry| match entry {
+ AgentThreadEntry::UserMessage(message) => Some(message),
+ _ => None,
+ })
+ .is_some_and(|message| {
+ let already_in_user_message = message.is_optimistic
+ && message.chunks.contains(&content)
+ && can_merge_message_chunks(
+ message.protocol_id.as_ref(),
+ message_id.as_ref(),
+ );
+ if already_in_user_message && message.protocol_id.is_none() {
+ message.protocol_id = message_id.clone();
+ }
+ already_in_user_message
+ });
if !already_in_user_message {
- self.push_user_content_block(None, content, cx);
+ self.push_user_content_block_from_agent(message_id, content, cx);
}
}
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk { content, .. }) => {
- self.push_assistant_content_block(content, false, cx);
+ acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
+ content,
+ message_id,
+ ..
+ }) => {
+ self.push_assistant_content_block_with_message_id(
+ message_id, content, false, false, cx,
+ );
}
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk { content, .. }) => {
- self.push_assistant_content_block(content, true, cx);
+ acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk {
+ content,
+ message_id,
+ ..
+ }) => {
+ self.push_assistant_content_block_with_message_id(
+ message_id, content, true, false, cx,
+ );
}
acp::SessionUpdate::ToolCall(tool_call) => {
self.upsert_tool_call(tool_call, cx)?;
@@ -2216,16 +2265,44 @@ impl AcpThread {
pub fn push_user_content_block(
&mut self,
- message_id: Option<UserMessageId>,
+ client_id: Option<ClientUserMessageId>,
chunk: acp::ContentBlock,
cx: &mut Context<Self>,
) {
- self.push_user_content_block_with_indent(message_id, chunk, false, cx)
+ self.push_user_content_block_with_indent(client_id, chunk, false, cx)
}
pub fn push_user_content_block_with_indent(
&mut self,
- message_id: Option<UserMessageId>,
+ client_id: Option<ClientUserMessageId>,
+ chunk: acp::ContentBlock,
+ indented: bool,
+ cx: &mut Context<Self>,
+ ) {
+ self.push_user_content_block_with_protocol_id(
+ client_id.clone(),
+ client_id.is_some(),
+ None,
+ chunk,
+ indented,
+ cx,
+ )
+ }
+
+ fn push_user_content_block_from_agent(
+ &mut self,
+ id: Option<acp::MessageId>,
+ chunk: acp::ContentBlock,
+ cx: &mut Context<Self>,
+ ) {
+ self.push_user_content_block_with_protocol_id(None, false, id, chunk, false, cx)
+ }
+
+ fn push_user_content_block_with_protocol_id(
+ &mut self,
+ incoming_client_id: Option<ClientUserMessageId>,
+ is_optimistic: bool,
+ protocol_id: Option<acp::MessageId>,
chunk: acp::ContentBlock,
indented: bool,
cx: &mut Context<Self>,
@@ -2236,16 +2313,29 @@ impl AcpThread {
if let Some(last_entry) = self.entries.last_mut()
&& let AgentThreadEntry::UserMessage(UserMessage {
- id,
+ protocol_id: existing_protocol_id,
+ client_id: existing_client_id,
content,
chunks,
+ is_optimistic: existing_is_optimistic,
indented: existing_indented,
..
}) = last_entry
&& *existing_indented == indented
+ && can_merge_message_chunks(existing_protocol_id.as_ref(), protocol_id.as_ref())
+ && !(*existing_is_optimistic
+ && !is_optimistic
+ && existing_protocol_id.is_none()
+ && protocol_id.is_some())
{
Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
- *id = message_id.or(id.take());
+ if let Some(incoming_client_id) = incoming_client_id {
+ *existing_client_id = Some(incoming_client_id);
+ }
+ *existing_is_optimistic |= is_optimistic;
+ if existing_protocol_id.is_none() {
+ *existing_protocol_id = protocol_id;
+ }
content.append(chunk.clone(), &language_registry, path_style, cx);
chunks.push(chunk);
let idx = entries_len - 1;
@@ -2254,7 +2344,9 @@ impl AcpThread {
let content = ContentBlock::new(chunk.clone(), &language_registry, path_style, cx);
self.push_entry(
AgentThreadEntry::UserMessage(UserMessage {
- id: message_id,
+ protocol_id,
+ client_id: incoming_client_id,
+ is_optimistic,
content,
chunks: vec![chunk],
checkpoint: None,
@@ -2280,13 +2372,26 @@ impl AcpThread {
is_thought: bool,
indented: bool,
cx: &mut Context<Self>,
+ ) {
+ self.push_assistant_content_block_with_message_id(None, chunk, is_thought, indented, cx)
+ }
+
+ fn push_assistant_content_block_with_message_id(
+ &mut self,
+ message_id: Option<acp::MessageId>,
+ chunk: acp::ContentBlock,
+ is_thought: bool,
+ indented: bool,
+ cx: &mut Context<Self>,
) {
let path_style = self.project.read(cx).path_style(cx);
// For text chunks going to an existing Markdown block, buffer for smooth
// streaming instead of appending all at once which may feel more choppy.
if let acp::ContentBlock::Text(text_content) = &chunk {
- if let Some(markdown) = self.streaming_markdown_target(is_thought, indented) {
+ if let Some(markdown) =
+ self.streaming_markdown_target(message_id.as_ref(), is_thought, indented)
+ {
let entries_len = self.entries.len();
cx.emit(AcpThreadEvent::EntryUpdated(entries_len - 1));
self.buffer_streaming_text(&markdown, text_content.text.clone(), cx);
@@ -2308,25 +2413,52 @@ impl AcpThread {
Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
cx.emit(AcpThreadEvent::EntryUpdated(idx));
match (chunks.last_mut(), is_thought) {
- (Some(AssistantMessageChunk::Message { block }), false)
- | (Some(AssistantMessageChunk::Thought { block }), true) => {
+ (
+ Some(AssistantMessageChunk::Message {
+ id: existing_id,
+ block,
+ }),
+ false,
+ )
+ | (
+ Some(AssistantMessageChunk::Thought {
+ id: existing_id,
+ block,
+ }),
+ true,
+ ) if can_merge_message_chunks(existing_id.as_ref(), message_id.as_ref()) => {
+ if existing_id.is_none() {
+ *existing_id = message_id;
+ }
block.append(chunk, &language_registry, path_style, cx)
}
_ => {
let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
if is_thought {
- chunks.push(AssistantMessageChunk::Thought { block })
+ chunks.push(AssistantMessageChunk::Thought {
+ id: message_id,
+ block,
+ })
} else {
- chunks.push(AssistantMessageChunk::Message { block })
+ chunks.push(AssistantMessageChunk::Message {
+ id: message_id,
+ block,
+ })
}
}
}
} else {
let block = ContentBlock::new(chunk, &language_registry, path_style, cx);
let chunk = if is_thought {
- AssistantMessageChunk::Thought { block }
+ AssistantMessageChunk::Thought {
+ id: message_id,
+ block,
+ }
} else {
- AssistantMessageChunk::Message { block }
+ AssistantMessageChunk::Message {
+ id: message_id,
+ block,
+ }
};
self.push_entry(
@@ -2341,32 +2473,40 @@ impl AcpThread {
}
fn streaming_markdown_target(
- &self,
+ &mut self,
+ message_id: Option<&acp::MessageId>,
is_thought: bool,
indented: bool,
) -> Option<Entity<Markdown>> {
- let last_entry = self.entries.last()?;
+ let last_entry = self.entries.last_mut()?;
if let AgentThreadEntry::AssistantMessage(AssistantMessage {
chunks,
indented: existing_indented,
..
}) = last_entry
&& *existing_indented == indented
- && let [.., chunk] = chunks.as_slice()
+ && let [.., chunk] = chunks.as_mut_slice()
{
match (chunk, is_thought) {
(
AssistantMessageChunk::Message {
+ id: existing_id,
block: ContentBlock::Markdown { markdown },
},
false,
)
| (
AssistantMessageChunk::Thought {
+ id: existing_id,
block: ContentBlock::Markdown { markdown },
},
true,
- ) => Some(markdown.clone()),
+ ) if can_merge_message_chunks(existing_id.as_ref(), message_id) => {
+ if existing_id.is_none() {
+ *existing_id = message_id.cloned();
+ }
+ Some(markdown.clone())
+ }
_ => None,
}
} else {
@@ -3039,14 +3179,19 @@ impl AcpThread {
let request = acp::PromptRequest::new(self.session_id.clone(), message.clone());
let git_store = self.project.read(cx).git_store().clone();
- let message_id = UserMessageId::new();
+ let client_user_message_ids = self.connection.client_user_message_ids(cx);
+ let client_id = client_user_message_ids
+ .as_ref()
+ .map(|client_user_message_ids| client_user_message_ids.new_id());
self.run_turn(cx, async move |this, cx| {
if push_user_message {
this.update(cx, |this, cx| {
this.push_entry(
AgentThreadEntry::UserMessage(UserMessage {
- id: Some(message_id.clone()),
+ protocol_id: None,
+ client_id: client_id.clone(),
+ is_optimistic: true,
content: block,
chunks: message,
checkpoint: None,
@@ -3074,7 +3219,11 @@ impl AcpThread {
}
this.update(cx, |this, cx| {
- this.connection.prompt(message_id, request, cx)
+ if let (Some(prompt), Some(client_id)) = (client_user_message_ids, client_id) {
+ prompt.prompt(client_id, request, cx)
+ } else {
+ this.connection.prompt(request, cx)
+ }
})?
.await
})
@@ -3295,10 +3444,10 @@ impl AcpThread {
/// Restores the git working tree to the state at the given checkpoint (if one exists)
pub fn restore_checkpoint(
&mut self,
- id: UserMessageId,
+ client_id: ClientUserMessageId,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
- let Some((_, message)) = self.user_message_mut(&id) else {
+ let Some((_, message)) = self.user_message_mut(&client_id) else {
return Task::ready(Err(anyhow!("message not found")));
};
@@ -3309,7 +3458,7 @@ impl AcpThread {
// Cancel any in-progress generation before restoring
let cancel_task = self.cancel(cx);
- let rewind = self.rewind(id.clone(), cx);
+ let rewind = self.rewind(client_id.clone(), cx);
let git_store = self.project.read(cx).git_store().clone();
cx.spawn(async move |_, cx| {
@@ -3328,7 +3477,11 @@ impl AcpThread {
/// Rewinds this thread to before the entry at `index`, removing it and all
/// subsequent entries while rejecting any action_log changes made from that point.
/// Unlike `restore_checkpoint`, this method does not restore from git.
- pub fn rewind(&mut self, id: UserMessageId, cx: &mut Context<Self>) -> Task<Result<()>> {
+ pub fn rewind(
+ &mut self,
+ client_id: ClientUserMessageId,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<()>> {
let Some(truncate) = self.connection.truncate(&self.session_id, cx) else {
return Task::ready(Err(anyhow!("not supported")));
};
@@ -3336,9 +3489,9 @@ impl AcpThread {
Self::flush_streaming_text(&mut self.streaming_text_buffer, cx);
let telemetry = ActionLogTelemetry::from(&*self);
cx.spawn(async move |this, cx| {
- cx.update(|cx| truncate.run(id.clone(), cx)).await?;
+ cx.update(|cx| truncate.run(client_id.clone(), cx)).await?;
this.update(cx, |this, cx| {
- if let Some((ix, _)) = this.user_message_mut(&id) {
+ if let Some((ix, _)) = this.user_message_mut(&client_id) {
// Collect all terminals from entries that will be removed
let terminals_to_remove: Vec<acp::TerminalId> = this.entries[ix..]
.iter()
@@ -3375,13 +3528,11 @@ impl AcpThread {
let git_store = self.project.read(cx).git_store().clone();
- let Some((user_message_id, checkpoint)) =
- self.last_user_message().and_then(|(_, message)| {
- let id = message.id.clone()?;
- let checkpoint = message.checkpoint.as_ref()?;
- Some((id, checkpoint))
- })
- else {
+ let Some((client_id, checkpoint)) = self.last_user_message().and_then(|(_, message)| {
+ let id = message.client_id.clone()?;
+ let checkpoint = message.checkpoint.as_ref()?;
+ Some((id, checkpoint))
+ }) else {
return Task::ready(Ok(()));
};
if checkpoint.show {
@@ -3426,7 +3577,7 @@ impl AcpThread {
let Some((ix, message)) = this.last_user_message() else {
return;
};
- if message.id.as_ref() != Some(&user_message_id) {
+ if message.client_id.as_ref() != Some(&client_id) {
return;
}
if let Some(checkpoint) = message.checkpoint.as_mut()
@@ -3447,7 +3598,7 @@ impl AcpThread {
let Some((_, message)) = self.last_user_message() else {
return Task::ready(Ok(()));
};
- let Some(user_message_id) = message.id.clone() else {
+ let Some(client_id) = message.client_id.clone() else {
return Task::ready(Ok(()));
};
let Some(checkpoint) = message.checkpoint.as_ref() else {
@@ -3473,7 +3624,7 @@ impl AcpThread {
.unwrap_or(true);
this.update(cx, |this, cx| {
- if let Some((ix, message)) = this.user_message_mut(&user_message_id) {
+ if let Some((ix, message)) = this.user_message_mut(&client_id) {
if let Some(checkpoint) = message.checkpoint.as_mut() {
checkpoint.show = !equal;
cx.emit(AcpThreadEvent::EntryUpdated(ix));
@@ -3499,10 +3650,13 @@ impl AcpThread {
})
}
- fn user_message_mut(&mut self, id: &UserMessageId) -> Option<(usize, &mut UserMessage)> {
+ fn user_message_mut(
+ &mut self,
+ client_id: &ClientUserMessageId,
+ ) -> Option<(usize, &mut UserMessage)> {
self.entries.iter_mut().enumerate().find_map(|(ix, entry)| {
if let AgentThreadEntry::UserMessage(message) = entry {
- if message.id.as_ref() == Some(id) {
+ if message.client_id.as_ref() == Some(client_id) {
Some((ix, message))
} else {
None
@@ -4083,6 +4237,23 @@ mod tests {
assert_eq!(command_category_from_meta(&Some(unknown)), None);
}
+ #[test]
+ fn client_user_message_id_serializes_as_string() {
+ let serialized =
+ serde_json::to_value(ClientUserMessageId::new()).expect("serialize client message id");
+ assert!(
+ serialized.is_string(),
+ "expected string, got {serialized:?}"
+ );
+
+ let deserialized: ClientUserMessageId =
+ serde_json::from_value(json!("client-id")).expect("deserialize client message id");
+ assert_eq!(
+ serde_json::to_value(deserialized).expect("serialize client message id"),
+ json!("client-id")
+ );
+ }
+
fn init_test(cx: &mut TestAppContext) {
env_logger::try_init().ok();
cx.update(|cx| {
@@ -4625,7 +4796,8 @@ mod tests {
thread.update(cx, |thread, cx| {
assert_eq!(thread.entries.len(), 1);
if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
- assert_eq!(user_msg.id, None);
+ assert_eq!(user_msg.protocol_id, None);
+ assert_eq!(user_msg.client_id, None);
assert_eq!(user_msg.content.to_markdown(cx), "Hello, ");
} else {
panic!("Expected UserMessage");
@@ -4633,7 +4805,7 @@ mod tests {
});
// Test appending to existing user message
- let message_1_id = UserMessageId::new();
+ let message_1_id = ClientUserMessageId::new();
thread.update(cx, |thread, cx| {
thread.push_user_content_block(Some(message_1_id.clone()), "world!".into(), cx);
});
@@ -4641,7 +4813,8 @@ mod tests {
thread.update(cx, |thread, cx| {
assert_eq!(thread.entries.len(), 1);
if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[0] {
- assert_eq!(user_msg.id, Some(message_1_id));
+ assert_eq!(user_msg.protocol_id, None);
+ assert_eq!(user_msg.client_id, Some(message_1_id));
assert_eq!(user_msg.content.to_markdown(cx), "Hello, world!");
} else {
panic!("Expected UserMessage");
@@ -4653,7 +4826,7 @@ mod tests {
thread.push_assistant_content_block("Assistant response".into(), false, cx);
});
- let message_2_id = UserMessageId::new();
+ let message_2_id = ClientUserMessageId::new();
thread.update(cx, |thread, cx| {
thread.push_user_content_block(
Some(message_2_id.clone()),
@@ -4665,7 +4838,8 @@ mod tests {
thread.update(cx, |thread, cx| {
assert_eq!(thread.entries.len(), 3);
if let AgentThreadEntry::UserMessage(user_msg) = &thread.entries[2] {
- assert_eq!(user_msg.id, Some(message_2_id));
+ assert_eq!(user_msg.protocol_id, None);
+ assert_eq!(user_msg.client_id, Some(message_2_id));
assert_eq!(user_msg.content.to_markdown(cx), "New user message");
} else {
panic!("Expected UserMessage at index 2");
@@ -4673,6 +4847,285 @@ mod tests {
});
}
+ #[gpui::test]
+ async fn test_user_message_chunks_use_protocol_message_id_boundaries(
+ cx: &mut gpui::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
+ .unwrap();
+
+ thread.update(cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("First ".into()).message_id("msg_user_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("message".into()).message_id("msg_user_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("Second message".into()).message_id("msg_user_2"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
+ ),
+ cx,
+ )
+ .unwrap();
+ });
+
+ thread.update(cx, |thread, cx| {
+ assert_eq!(thread.entries.len(), 3);
+
+ let AgentThreadEntry::UserMessage(first_message) = &thread.entries[0] else {
+ panic!("expected first entry to be a user message")
+ };
+ assert_eq!(first_message.content.to_markdown(cx), "First message");
+ assert_eq!(
+ first_message
+ .protocol_id
+ .as_ref()
+ .map(ToString::to_string)
+ .as_deref(),
+ Some("msg_user_1")
+ );
+
+ let AgentThreadEntry::UserMessage(second_message) = &thread.entries[1] else {
+ panic!("expected second entry to be a user message")
+ };
+ assert_eq!(second_message.content.to_markdown(cx), "Second message");
+ assert_eq!(
+ second_message
+ .protocol_id
+ .as_ref()
+ .map(ToString::to_string)
+ .as_deref(),
+ Some("msg_user_2")
+ );
+
+ let AgentThreadEntry::UserMessage(third_message) = &thread.entries[2] else {
+ panic!("expected third entry to be a user message")
+ };
+ assert_eq!(third_message.content.to_markdown(cx), "EchoEcho");
+ assert_eq!(
+ third_message
+ .protocol_id
+ .as_ref()
+ .map(ToString::to_string)
+ .as_deref(),
+ Some("msg_user_3")
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_protocol_user_chunk_does_not_merge_into_optimistic_prompt(
+ cx: &mut gpui::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
+ .unwrap();
+
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block_with_protocol_id(
+ None,
+ true,
+ None,
+ "Typed prompt".into(),
+ false,
+ cx,
+ );
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(
+ acp::ContentChunk::new("Agent user chunk".into())
+ .message_id("agent_user_chunk"),
+ ),
+ cx,
+ )
+ .unwrap();
+ });
+
+ thread.update(cx, |thread, cx| {
+ assert_eq!(thread.entries.len(), 2);
+
+ let AgentThreadEntry::UserMessage(optimistic_message) = &thread.entries[0] else {
+ panic!("expected first entry to be optimistic user message")
+ };
+ assert!(optimistic_message.is_optimistic);
+ assert_eq!(optimistic_message.content.to_markdown(cx), "Typed prompt");
+ assert!(optimistic_message.protocol_id.is_none());
+ assert!(optimistic_message.client_id.is_none());
+
+ let AgentThreadEntry::UserMessage(agent_message) = &thread.entries[1] else {
+ panic!("expected second entry to be protocol user chunk")
+ };
+ assert!(!agent_message.is_optimistic);
+ assert_eq!(agent_message.content.to_markdown(cx), "Agent user chunk");
+ assert_eq!(
+ agent_message
+ .protocol_id
+ .as_ref()
+ .map(ToString::to_string)
+ .as_deref(),
+ Some("agent_user_chunk")
+ );
+ });
+ }
+
+ #[gpui::test]
+ async fn test_assistant_chunks_use_protocol_message_id_boundaries(
+ cx: &mut gpui::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
+ .unwrap();
+
+ thread.update(cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentThoughtChunk(
+ acp::ContentChunk::new("Thinking ".into()).message_id("msg_thought_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentThoughtChunk(
+ acp::ContentChunk::new("hard".into()).message_id("msg_thought_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentThoughtChunk(
+ acp::ContentChunk::new("A separate thought".into())
+ .message_id("msg_thought_2"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Answer ".into()).message_id("msg_agent_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("done".into()).message_id("msg_agent_1"),
+ ),
+ cx,
+ )
+ .unwrap();
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::AgentMessageChunk(
+ acp::ContentChunk::new("Follow-up".into()).message_id("msg_agent_2"),
+ ),
+ cx,
+ )
+ .unwrap();
+ });
+
+ thread.update(cx, |thread, cx| {
+ assert_eq!(thread.entries.len(), 1);
+ let AgentThreadEntry::AssistantMessage(message) = &thread.entries[0] else {
+ panic!("expected assistant entry")
+ };
+ assert_eq!(message.chunks.len(), 4);
+
+ let AssistantMessageChunk::Thought { id, block } = &message.chunks[0] else {
+ panic!("expected first chunk to be a thought")
+ };
+ assert_eq!(block.to_markdown(cx), "Thinking hard");
+ assert_eq!(
+ id.as_ref().map(ToString::to_string).as_deref(),
+ Some("msg_thought_1")
+ );
+
+ let AssistantMessageChunk::Thought { id, block } = &message.chunks[1] else {
+ panic!("expected second chunk to be a thought")
+ };
+ assert_eq!(block.to_markdown(cx), "A separate thought");
+ assert_eq!(
+ id.as_ref().map(ToString::to_string).as_deref(),
+ Some("msg_thought_2")
+ );
+
+ let AssistantMessageChunk::Message { id, block } = &message.chunks[2] else {
+ panic!("expected third chunk to be a message")
+ };
+ assert_eq!(block.to_markdown(cx), "Answer done");
+ assert_eq!(
+ id.as_ref().map(ToString::to_string).as_deref(),
+ Some("msg_agent_1")
+ );
+
+ let AssistantMessageChunk::Message { id, block } = &message.chunks[3] else {
+ panic!("expected fourth chunk to be a message")
+ };
+ assert_eq!(block.to_markdown(cx), "Follow-up");
+ assert_eq!(
+ id.as_ref().map(ToString::to_string).as_deref(),
+ Some("msg_agent_2")
+ );
+ });
+ }
+
#[gpui::test]
async fn test_thinking_concatenation(cx: &mut gpui::TestAppContext) {
init_test(cx);
@@ -4818,27 +5271,29 @@ mod tests {
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
- let connection = Rc::new(FakeAgentConnection::new().on_user_message(
- |request, thread, mut cx| {
- async move {
- let prompt = request.prompt.first().cloned().unwrap_or_else(|| "".into());
+ let connection = Rc::new(
+ FakeAgentConnection::new()
+ .without_truncate_support()
+ .on_user_message(|request, thread, mut cx| {
+ async move {
+ let prompt = request.prompt.first().cloned().unwrap_or_else(|| "".into());
- thread.update(&mut cx, |thread, cx| {
- thread
- .handle_session_update(
- acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(
- prompt,
- )),
- cx,
- )
- .unwrap();
- })?;
+ thread.update(&mut cx, |thread, cx| {
+ thread
+ .handle_session_update(
+ acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(
+ prompt,
+ )),
+ cx,
+ )
+ .unwrap();
+ })?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
- }
- .boxed_local()
- },
- ));
+ Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ }
+ .boxed_local()
+ }),
+ );
let thread = cx
.update(|cx| {
@@ -4854,6 +5309,14 @@ mod tests {
let output = thread.read_with(cx, |thread, cx| thread.to_markdown(cx));
assert_eq!(output.matches("Hello from Zed!").count(), 1);
+ thread.read_with(cx, |thread, _cx| {
+ let Some(AgentThreadEntry::UserMessage(message)) = thread.entries.first() else {
+ panic!("expected optimistic user message");
+ };
+ assert_eq!(message.protocol_id, None);
+ assert_eq!(message.client_id, None);
+ assert!(message.is_optimistic);
+ });
}
#[gpui::test]
@@ -5900,7 +6363,7 @@ mod tests {
let AgentThreadEntry::UserMessage(message) = &thread.entries[2] else {
panic!("unexpected entries {:?}", thread.entries)
};
- thread.restore_checkpoint(message.id.clone().unwrap(), cx)
+ thread.restore_checkpoint(message.client_id.clone().unwrap(), cx)
})
.await
.unwrap();
@@ -6419,7 +6882,6 @@ mod tests {
fn prompt(
&self,
- _id: UserMessageId,
params: acp::PromptRequest,
cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -6434,6 +6896,17 @@ mod tests {
}
}
+ fn client_user_message_ids(
+ &self,
+ _cx: &App,
+ ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
+ self.supports_truncate.then(|| {
+ Rc::new(FakeAgentSessionClientUserMessageIds {
+ connection: self.clone(),
+ }) as Rc<dyn AgentSessionClientUserMessageIds>
+ })
+ }
+
fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
fn truncate(
@@ -6479,11 +6952,30 @@ mod tests {
}
impl AgentSessionTruncate for FakeAgentSessionEditor {
- fn run(&self, _message_id: UserMessageId, _cx: &mut App) -> Task<Result<()>> {
+ fn run(
+ &self,
+ _client_user_message_id: ClientUserMessageId,
+ _cx: &mut App,
+ ) -> Task<Result<()>> {
Task::ready(Ok(()))
}
}
+ struct FakeAgentSessionClientUserMessageIds {
+ connection: FakeAgentConnection,
+ }
+
+ impl AgentSessionClientUserMessageIds for FakeAgentSessionClientUserMessageIds {
+ fn prompt(
+ &self,
+ _client_user_message_id: ClientUserMessageId,
+ params: acp::PromptRequest,
+ cx: &mut App,
+ ) -> Task<Result<acp::PromptResponse>> {
+ self.connection.prompt(params, cx)
+ }
+ }
+
#[gpui::test]
async fn test_tool_call_not_found_creates_failed_entry(cx: &mut TestAppContext) {
init_test(cx);
@@ -6689,7 +7181,7 @@ mod tests {
let AgentThreadEntry::UserMessage(message) = &thread.entries[1] else {
panic!("expected user message at index 1");
};
- message.id.clone().unwrap()
+ message.client_id.clone().unwrap()
});
// Create a terminal AFTER the checkpoint we'll restore to.
@@ -6895,7 +7387,9 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.push_entry(
AgentThreadEntry::UserMessage(UserMessage {
- id: Some(UserMessageId::new()),
+ protocol_id: None,
+ client_id: Some(ClientUserMessageId::new()),
+ is_optimistic: true,
content: ContentBlock::Empty,
chunks: vec!["Injected message (no checkpoint)".into()],
checkpoint: None,
@@ -7097,7 +7591,9 @@ mod tests {
}
#[gpui::test]
- async fn test_send_assigns_message_id_without_truncate_support(cx: &mut TestAppContext) {
+ async fn test_send_omits_message_id_without_client_user_message_id_support(
+ cx: &mut TestAppContext,
+ ) {
init_test(cx);
let fs = FakeFs::new(cx.executor());
@@ -7120,10 +7616,9 @@ mod tests {
let AgentThreadEntry::UserMessage(message) = &thread.entries[0] else {
panic!("expected first entry to be a user message")
};
- assert!(
- message.id.is_some(),
- "user message should always have an id"
- );
+ assert_eq!(message.protocol_id, None);
+ assert_eq!(message.client_id, None);
+ assert!(message.is_optimistic);
});
}
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index a730e6c39d9..e5bb82e9afd 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -13,10 +13,11 @@ use ui::{App, IconName};
use util::path_list::PathList;
use uuid::Uuid;
+/// A user-message ID generated by Zed and passed to agents that support client IDs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
-pub struct UserMessageId(SharedString);
+pub struct ClientUserMessageId(SharedString);
-impl UserMessageId {
+impl ClientUserMessageId {
pub fn new() -> Self {
Self(Uuid::new_v4().to_string().into())
}
@@ -183,12 +184,16 @@ pub trait AgentConnection {
Task::ready(Err(anyhow::Error::msg("Logout is not supported")))
}
- fn prompt(
+ /// Returns a capability for agents that accept client-generated user message IDs.
+ fn client_user_message_ids(
&self,
- user_message_id: UserMessageId,
- params: acp::PromptRequest,
- cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>>;
+ _cx: &App,
+ ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
+ None
+ }
+
+ fn prompt(&self, params: acp::PromptRequest, cx: &mut App)
+ -> Task<Result<acp::PromptResponse>>;
fn retry(&self, _session_id: &acp::SessionId, _cx: &App) -> Option<Rc<dyn AgentSessionRetry>> {
None
@@ -254,7 +259,20 @@ impl dyn AgentConnection {
}
pub trait AgentSessionTruncate {
- fn run(&self, message_id: UserMessageId, cx: &mut App) -> Task<Result<()>>;
+ fn run(&self, client_user_message_id: ClientUserMessageId, cx: &mut App) -> Task<Result<()>>;
+}
+
+pub trait AgentSessionClientUserMessageIds {
+ fn new_id(&self) -> ClientUserMessageId {
+ ClientUserMessageId::new()
+ }
+
+ fn prompt(
+ &self,
+ client_user_message_id: ClientUserMessageId,
+ params: acp::PromptRequest,
+ cx: &mut App,
+ ) -> Task<Result<acp::PromptResponse>>;
}
pub trait AgentSessionRetry {
@@ -943,7 +961,6 @@ mod test_support {
fn prompt(
&self,
- _id: UserMessageId,
params: acp::PromptRequest,
cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -1000,6 +1017,15 @@ mod test_support {
}
}
+ fn client_user_message_ids(
+ &self,
+ _cx: &App,
+ ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
+ Some(Rc::new(StubAgentSessionClientUserMessageIds {
+ connection: self.clone(),
+ }))
+ }
+
fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
if let Some(end_turn_tx) = self
.sessions
@@ -1042,10 +1068,25 @@ mod test_support {
}
}
+ struct StubAgentSessionClientUserMessageIds {
+ connection: StubAgentConnection,
+ }
+
+ impl AgentSessionClientUserMessageIds for StubAgentSessionClientUserMessageIds {
+ fn prompt(
+ &self,
+ _client_user_message_id: ClientUserMessageId,
+ params: acp::PromptRequest,
+ cx: &mut App,
+ ) -> Task<Result<acp::PromptResponse>> {
+ self.connection.prompt(params, cx)
+ }
+ }
+
struct StubAgentSessionEditor;
impl AgentSessionTruncate for StubAgentSessionEditor {
- fn run(&self, _: UserMessageId, _: &mut App) -> Task<Result<()>> {
+ fn run(&self, _: ClientUserMessageId, _: &mut App) -> Task<Result<()>> {
Task::ready(Ok(()))
}
}
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index e9abeef5a22..75e52207f27 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -30,7 +30,7 @@ pub use tools::*;
use acp_thread::{
AcpThread, AgentModelId, AgentModelSelector, AgentSessionInfo, AgentSessionList,
- AgentSessionListRequest, AgentSessionListResponse, TokenUsageRatio, UserMessageId,
+ AgentSessionListRequest, AgentSessionListResponse, ClientUserMessageId, TokenUsageRatio,
};
use agent_client_protocol::schema::v1 as acp;
use agent_skills::{
@@ -1818,7 +1818,7 @@ impl NativeAgent {
fn send_mcp_prompt(
&self,
- message_id: UserMessageId,
+ client_user_message_id: ClientUserMessageId,
session_id: acp::SessionId,
prompt_name: String,
server_id: ContextServerId,
@@ -1852,7 +1852,7 @@ impl NativeAgent {
thread.update(cx, |thread, cx| {
thread.push_acp_user_block(
- message_id,
+ client_user_message_id,
original_content.into_iter().skip(1),
path_style,
cx,
@@ -1865,7 +1865,7 @@ impl NativeAgent {
match role {
context_server::types::Role::User => {
- let id = acp_thread::UserMessageId::new();
+ let id = acp_thread::ClientUserMessageId::new();
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
@@ -1925,7 +1925,7 @@ impl NativeAgent {
/// `/compact` slash command.
fn send_compact_command(
&self,
- message_id: UserMessageId,
+ client_user_message_id: ClientUserMessageId,
session_id: acp::SessionId,
cx: &mut Context<Self>,
) -> Task<Result<acp::PromptResponse>> {
@@ -1938,7 +1938,8 @@ impl NativeAgent {
anyhow::Ok((session.acp_thread.clone(), session.thread.clone()))
})??;
- let response_stream = thread.update(cx, |thread, cx| thread.compact(message_id, cx))?;
+ let response_stream =
+ thread.update(cx, |thread, cx| thread.compact(client_user_message_id, cx))?;
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.update_token_usage(None, cx);
});
@@ -1966,7 +1967,7 @@ impl NativeAgent {
/// instructions followed by the user's request.
fn send_skill_invocation(
&self,
- message_id: UserMessageId,
+ client_user_message_id: ClientUserMessageId,
session_id: acp::SessionId,
skill: Skill,
original_content: Vec<acp::ContentBlock>,
@@ -2025,7 +2026,7 @@ impl NativeAgent {
// the user can see what context was loaded for the skill. The
// user's own typed message is already rendered by the normal
// prompt flow, so we don't push it to the UI again here.
- let injected_id = acp_thread::UserMessageId::new();
+ let injected_id = acp_thread::ClientUserMessageId::new();
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
Some(injected_id),
@@ -2042,7 +2043,7 @@ impl NativeAgent {
combined.extend(user_blocks);
thread.update(cx, |thread, cx| {
- thread.push_acp_user_block(message_id, combined, path_style, cx);
+ thread.push_acp_user_block(client_user_message_id, combined, path_style, cx);
});
let response_stream = thread.update(cx, |thread, cx| thread.send_existing(cx))?;
@@ -2618,9 +2619,101 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
}) as Rc<dyn AgentModelSelector>)
}
+ fn client_user_message_ids(
+ &self,
+ _cx: &App,
+ ) -> Option<Rc<dyn acp_thread::AgentSessionClientUserMessageIds>> {
+ let prompt: Rc<dyn acp_thread::AgentSessionClientUserMessageIds> = Rc::new(self.clone());
+ Some(prompt)
+ }
+
fn prompt(
&self,
- id: acp_thread::UserMessageId,
+ params: acp::PromptRequest,
+ cx: &mut App,
+ ) -> Task<Result<acp::PromptResponse>> {
+ acp_thread::AgentSessionClientUserMessageIds::prompt(
+ self,
+ acp_thread::AgentSessionClientUserMessageIds::new_id(self),
+ params,
+ cx,
+ )
+ }
+
+ fn retry(
+ &self,
+ session_id: &acp::SessionId,
+ _cx: &App,
+ ) -> Option<Rc<dyn acp_thread::AgentSessionRetry>> {
+ Some(Rc::new(NativeAgentSessionRetry {
+ connection: self.clone(),
+ session_id: session_id.clone(),
+ }) as _)
+ }
+
+ fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
+ log::info!("Cancelling on session: {}", session_id);
+ self.0.update(cx, |agent, cx| {
+ if let Some(session) = agent.sessions.get(session_id) {
+ session
+ .thread
+ .update(cx, |thread, cx| thread.cancel(cx))
+ .detach();
+ }
+ });
+ }
+
+ fn truncate(
+ &self,
+ session_id: &acp::SessionId,
+ cx: &App,
+ ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
+ self.0.read_with(cx, |agent, _cx| {
+ agent.sessions.get(session_id).map(|session| {
+ Rc::new(NativeAgentSessionTruncate {
+ thread: session.thread.clone(),
+ acp_thread: session.acp_thread.downgrade(),
+ }) as _
+ })
+ })
+ }
+
+ fn set_title(
+ &self,
+ session_id: &acp::SessionId,
+ cx: &App,
+ ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
+ self.0.read_with(cx, |agent, _cx| {
+ agent
+ .sessions
+ .get(session_id)
+ .filter(|s| !s.thread.read(cx).is_subagent())
+ .map(|session| {
+ Rc::new(NativeAgentSessionSetTitle {
+ thread: session.thread.clone(),
+ }) as _
+ })
+ })
+ }
+
+ fn session_list(&self, cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
+ let thread_store = self.0.read(cx).thread_store.clone();
+ Some(Rc::new(NativeAgentSessionList::new(thread_store, cx)) as _)
+ }
+
+ fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
+ Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
+ }
+
+ fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
+ self
+ }
+}
+
+impl acp_thread::AgentSessionClientUserMessageIds for NativeAgentConnection {
+ fn prompt(
+ &self,
+ client_user_message_id: acp_thread::ClientUserMessageId,
params: acp::PromptRequest,
cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
@@ -2642,7 +2735,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
if let Some(parsed_command) = Command::parse(&params.prompt) {
if parsed_command.is_unqualified(COMPACT_COMMAND_NAME) {
return self.0.update(cx, |agent, cx| {
- agent.send_compact_command(id, session_id, cx)
+ agent.send_compact_command(client_user_message_id, session_id, cx)
});
}
@@ -2659,7 +2752,13 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
{
let skill = skill.clone();
return self.0.update(cx, |agent, cx| {
- agent.send_skill_invocation(id, session_id.clone(), skill, params.prompt, cx)
+ agent.send_skill_invocation(
+ client_user_message_id,
+ session_id.clone(),
+ skill,
+ params.prompt,
+ cx,
+ )
});
}
@@ -2694,7 +2793,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
return self.0.update(cx, |agent, cx| {
agent.send_mcp_prompt(
- id,
+ client_user_message_id,
session_id.clone(),
prompt_name,
server_id,
@@ -2742,7 +2841,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
let skill = skill.clone();
return self.0.update(cx, |agent, cx| {
agent.send_skill_invocation(
- id,
+ client_user_message_id,
session_id.clone(),
skill,
params.prompt,
@@ -2762,81 +2861,14 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
.map(|block| UserMessageContent::from_content_block(block, path_style))
.collect::<Vec<_>>();
log::debug!("Converted prompt to message: {} chars", content.len());
- log::debug!("Message id: {:?}", id);
+ log::debug!("Client user message id: {:?}", client_user_message_id);
log::debug!("Message content: {:?}", content);
- thread.update(cx, |thread, cx| thread.send(id, content, cx))
- })
- }
-
- fn retry(
- &self,
- session_id: &acp::SessionId,
- _cx: &App,
- ) -> Option<Rc<dyn acp_thread::AgentSessionRetry>> {
- Some(Rc::new(NativeAgentSessionRetry {
- connection: self.clone(),
- session_id: session_id.clone(),
- }) as _)
- }
-
- fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
- log::info!("Cancelling on session: {}", session_id);
- self.0.update(cx, |agent, cx| {
- if let Some(session) = agent.sessions.get(session_id) {
- session
- .thread
- .update(cx, |thread, cx| thread.cancel(cx))
- .detach();
- }
- });
- }
-
- fn truncate(
- &self,
- session_id: &acp::SessionId,
- cx: &App,
- ) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
- self.0.read_with(cx, |agent, _cx| {
- agent.sessions.get(session_id).map(|session| {
- Rc::new(NativeAgentSessionTruncate {
- thread: session.thread.clone(),
- acp_thread: session.acp_thread.downgrade(),
- }) as _
+ thread.update(cx, |thread, cx| {
+ thread.send(client_user_message_id, content, cx)
})
})
}
-
- fn set_title(
- &self,
- session_id: &acp::SessionId,
- cx: &App,
- ) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
- self.0.read_with(cx, |agent, _cx| {
- agent
- .sessions
- .get(session_id)
- .filter(|s| !s.thread.read(cx).is_subagent())
- .map(|session| {
- Rc::new(NativeAgentSessionSetTitle {
- thread: session.thread.clone(),
- }) as _
- })
- })
- }
-
- fn session_list(&self, cx: &mut App) -> Option<Rc<dyn AgentSessionList>> {
- let thread_store = self.0.read(cx).thread_store.clone();
- Some(Rc::new(NativeAgentSessionList::new(thread_store, cx)) as _)
- }
-
- fn telemetry(&self) -> Option<Rc<dyn acp_thread::AgentTelemetry>> {
- Some(Rc::new(self.clone()) as Rc<dyn acp_thread::AgentTelemetry>)
- }
-
- fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
- self
- }
}
impl acp_thread::AgentTelemetry for NativeAgentConnection {
@@ -2938,9 +2970,13 @@ struct NativeAgentSessionTruncate {
}
impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
- fn run(&self, message_id: acp_thread::UserMessageId, cx: &mut App) -> Task<Result<()>> {
+ fn run(
+ &self,
+ client_user_message_id: acp_thread::ClientUserMessageId,
+ cx: &mut App,
+ ) -> Task<Result<()>> {
match self.thread.update(cx, |thread, cx| {
- thread.truncate(message_id.clone(), cx)?;
+ thread.truncate(client_user_message_id.clone(), cx)?;
Ok(thread.latest_token_usage())
}) {
Ok(usage) => {
@@ -3780,7 +3816,7 @@ mod internal_tests {
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());
- let old_message_id = UserMessageId::new();
+ let old_message_id = ClientUserMessageId::new();
cx.update(|cx| {
let path_style = project.read(cx).path_style(cx);
@@ -3796,9 +3832,10 @@ mod internal_tests {
});
});
- let compact_message_id = UserMessageId::new();
+ let compact_message_id = ClientUserMessageId::new();
let prompt_task = cx.update(|cx| {
- connection.prompt(
+ acp_thread::AgentSessionClientUserMessageIds::prompt(
+ connection.as_ref(),
compact_message_id,
acp::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),
cx,
@@ -3854,7 +3891,7 @@ mod internal_tests {
let path_style = project.read(cx).path_style(cx);
thread.update(cx, |thread, cx| {
thread.push_acp_user_block(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
[acp::ContentBlock::from("hello from the user")],
path_style,
cx,
diff --git a/crates/agent/src/db.rs b/crates/agent/src/db.rs
index 6d104bd5bd2..61768833506 100644
--- a/crates/agent/src/db.rs
+++ b/crates/agent/src/db.rs
@@ -1,5 +1,5 @@
use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
-use acp_thread::UserMessageId;
+use acp_thread::ClientUserMessageId;
use agent_client_protocol::schema::v1 as acp;
use agent_settings::AgentProfileId;
use anyhow::{Result, anyhow};
@@ -62,7 +62,7 @@ pub struct DbThread {
#[serde(default)]
pub cumulative_token_usage: language_model::TokenUsage,
#[serde(default)]
- pub request_token_usage: HashMap<acp_thread::UserMessageId, language_model::TokenUsage>,
+ pub request_token_usage: HashMap<acp_thread::ClientUserMessageId, language_model::TokenUsage>,
#[serde(default)]
pub model: Option<DbLanguageModel>,
#[serde(default)]
@@ -241,7 +241,7 @@ impl DbThread {
content.push(UserMessageContent::Text(msg.context));
}
- let id = UserMessageId::new();
+ let id = ClientUserMessageId::new();
last_user_message_id = Some(id.clone());
crate::Message::User(UserMessage {
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index 876fa33b9b9..11f542ee8e6 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -1,7 +1,7 @@
use super::*;
use acp_thread::{
- AgentConnection, AgentModelGroupName, AgentModelList, PermissionOptions, ThreadStatus,
- UserMessageId,
+ AgentConnection, AgentModelGroupName, AgentModelList, ClientUserMessageId, PermissionOptions,
+ ThreadStatus,
};
use agent_client_protocol::schema::v1 as acp;
use agent_settings::AgentProfileId;
@@ -301,7 +301,11 @@ async fn test_echo(cx: &mut TestAppContext) {
let events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Testing: Reply with 'Hello'"], cx)
+ thread.send(
+ ClientUserMessageId::new(),
+ ["Testing: Reply with 'Hello'"],
+ cx,
+ )
})
.unwrap();
cx.run_until_parked();
@@ -453,7 +457,7 @@ async fn test_thinking(cx: &mut TestAppContext) {
let events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
[indoc! {"
Testing:
@@ -536,7 +540,7 @@ async fn test_system_prompt(cx: &mut TestAppContext) {
thread.update(cx, |thread, _| thread.add_tool(EchoTool));
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -574,7 +578,7 @@ async fn test_system_prompt_without_tools(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -613,7 +617,7 @@ async fn test_prompt_caching(cx: &mut TestAppContext) {
// Send initial user message and verify it's cached
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Message 1"], cx)
+ thread.send(ClientUserMessageId::new(), ["Message 1"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -637,7 +641,7 @@ async fn test_prompt_caching(cx: &mut TestAppContext) {
// Send another user message and verify only the latest is cached
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Message 2"], cx)
+ thread.send(ClientUserMessageId::new(), ["Message 2"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -676,7 +680,7 @@ async fn test_prompt_caching(cx: &mut TestAppContext) {
thread.update(cx, |thread, _| thread.add_tool(EchoTool));
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Use the echo tool"], cx)
+ thread.send(ClientUserMessageId::new(), ["Use the echo tool"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -761,7 +765,7 @@ async fn test_basic_tool_calls(cx: &mut TestAppContext) {
.update(cx, |thread, cx| {
thread.add_tool(EchoTool);
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Now test the echo tool with 'Hello'. Does it work? Say 'Yes' or 'No'."],
cx,
)
@@ -777,7 +781,7 @@ async fn test_basic_tool_calls(cx: &mut TestAppContext) {
thread.remove_tool(&EchoTool::NAME);
thread.add_tool(DelayTool);
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
[
"Now call the delay tool with 200ms.",
"When the timer goes off, then you echo the output of the tool.",
@@ -820,7 +824,7 @@ async fn test_streaming_tool_calls(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(WordListTool);
- thread.send(UserMessageId::new(), ["Test the word_list tool."], cx)
+ thread.send(ClientUserMessageId::new(), ["Test the word_list tool."], cx)
})
.unwrap();
@@ -871,7 +875,7 @@ async fn test_tool_authorization(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -1016,7 +1020,7 @@ async fn test_tool_hallucination(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -1345,7 +1349,7 @@ async fn test_concurrent_tool_calls(cx: &mut TestAppContext) {
.update(cx, |thread, cx| {
thread.add_tool(DelayTool);
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
[
"Call the delay tool twice in the same message.",
"Once with 100ms. Once with 300ms.",
@@ -1425,7 +1429,7 @@ async fn test_profiles(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
thread.set_profile(AgentProfileId("test-1".into()), cx);
- thread.send(UserMessageId::new(), ["test"], cx)
+ thread.send(ClientUserMessageId::new(), ["test"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -1445,7 +1449,7 @@ async fn test_profiles(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
thread.set_profile(AgentProfileId("test-2".into()), cx);
- thread.send(UserMessageId::new(), ["test2"], cx)
+ thread.send(ClientUserMessageId::new(), ["test2"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -1515,7 +1519,9 @@ async fn test_mcp_tools(cx: &mut TestAppContext) {
);
let events = thread.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hey"], cx).unwrap()
+ thread
+ .send(ClientUserMessageId::new(), ["Hey"], cx)
+ .unwrap()
});
cx.run_until_parked();
@@ -1558,7 +1564,7 @@ async fn test_mcp_tools(cx: &mut TestAppContext) {
// Send again after adding the echo tool, ensuring the name collision is resolved.
let events = thread.update(cx, |thread, cx| {
thread.add_tool(EchoTool);
- thread.send(UserMessageId::new(), ["Go"], cx).unwrap()
+ thread.send(ClientUserMessageId::new(), ["Go"], cx).unwrap()
});
cx.run_until_parked();
let completion = fake_model.pending_completions().pop().unwrap();
@@ -1678,7 +1684,7 @@ async fn test_mcp_tool_multi_content_response(cx: &mut TestAppContext) {
let events = thread.update(cx, |thread, cx| {
thread
- .send(UserMessageId::new(), ["Take a screenshot"], cx)
+ .send(ClientUserMessageId::new(), ["Take a screenshot"], cx)
.unwrap()
});
cx.run_until_parked();
@@ -1819,7 +1825,7 @@ async fn test_mcp_tool_result_displayed_when_server_disconnected(cx: &mut TestAp
// Send a message and have the model call the MCP tool
let events = thread.update(cx, |thread, cx| {
thread
- .send(UserMessageId::new(), ["Read issue #47404"], cx)
+ .send(ClientUserMessageId::new(), ["Read issue #47404"], cx)
.unwrap()
});
cx.run_until_parked();
@@ -2112,7 +2118,7 @@ async fn test_mcp_tool_truncation(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Go"], cx)
+ thread.send(ClientUserMessageId::new(), ["Go"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -2148,7 +2154,7 @@ async fn test_cancellation(cx: &mut TestAppContext) {
thread.add_tool(InfiniteTool);
thread.add_tool(EchoTool);
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Call the echo tool, then call the infinite tool, then explain their output"],
cx,
)
@@ -2205,7 +2211,7 @@ async fn test_cancellation(cx: &mut TestAppContext) {
let events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Testing: reply with 'Hello' then stop."],
cx,
)
@@ -2242,7 +2248,7 @@ async fn test_terminal_tool_cancellation_captures_output(cx: &mut TestAppContext
thread.project().clone(),
environment,
));
- thread.send(UserMessageId::new(), ["run a command"], cx)
+ thread.send(ClientUserMessageId::new(), ["run a command"], cx)
})
.unwrap();
@@ -2334,7 +2340,7 @@ async fn test_cancellation_aware_tool_responds_to_cancellation(cx: &mut TestAppC
.update(cx, |thread, cx| {
thread.add_tool(tool);
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["call the cancellation aware tool"],
cx,
)
@@ -2423,7 +2429,7 @@ async fn verify_thread_recovery(
let events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Testing: reply with 'Hello' then stop."],
cx,
)
@@ -2516,7 +2522,7 @@ async fn test_truncate_while_terminal_tool_running(cx: &mut TestAppContext) {
}));
let handle = environment.terminal_handle.clone().unwrap();
- let message_id = UserMessageId::new();
+ let message_id = ClientUserMessageId::new();
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(crate::TerminalTool::new(
@@ -2588,7 +2594,7 @@ async fn test_cancel_multiple_concurrent_terminal_tools(cx: &mut TestAppContext)
thread.project().clone(),
environment.clone(),
));
- thread.send(UserMessageId::new(), ["run multiple commands"], cx)
+ thread.send(ClientUserMessageId::new(), ["run multiple commands"], cx)
})
.unwrap();
@@ -2702,7 +2708,7 @@ async fn test_terminal_tool_stopped_via_terminal_card_button(cx: &mut TestAppCon
thread.project().clone(),
environment,
));
- thread.send(UserMessageId::new(), ["run a command"], cx)
+ thread.send(ClientUserMessageId::new(), ["run a command"], cx)
})
.unwrap();
@@ -2794,7 +2800,11 @@ async fn test_terminal_tool_timeout_expires(cx: &mut TestAppContext) {
thread.project().clone(),
environment,
));
- thread.send(UserMessageId::new(), ["run a command with timeout"], cx)
+ thread.send(
+ ClientUserMessageId::new(),
+ ["run a command with timeout"],
+ cx,
+ )
})
.unwrap();
@@ -2879,7 +2889,7 @@ async fn test_in_progress_send_canceled_by_next_send(cx: &mut TestAppContext) {
let events_1 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello 1"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello 1"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -2888,7 +2898,7 @@ async fn test_in_progress_send_canceled_by_next_send(cx: &mut TestAppContext) {
let events_2 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello 2"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello 2"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -2915,7 +2925,7 @@ async fn test_retry_cancelled_promptly_on_new_send(cx: &mut TestAppContext) {
// Start a turn with model_a.
let events_1 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -2945,7 +2955,7 @@ async fn test_retry_cancelled_promptly_on_new_send(cx: &mut TestAppContext) {
});
let events_2 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Continue"], cx)
+ thread.send(ClientUserMessageId::new(), ["Continue"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -2988,7 +2998,7 @@ async fn test_subsequent_successful_sends_dont_cancel(cx: &mut TestAppContext) {
let events_1 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello 1"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello 1"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3000,7 +3010,7 @@ async fn test_subsequent_successful_sends_dont_cancel(cx: &mut TestAppContext) {
let events_2 = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello 2"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello 2"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3021,7 +3031,7 @@ async fn test_refusal(cx: &mut TestAppContext) {
let events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3068,7 +3078,7 @@ async fn test_truncate_first_message(cx: &mut TestAppContext) {
let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
- let message_id = UserMessageId::new();
+ let message_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_id.clone(), ["Hello"], cx)
@@ -3134,7 +3144,7 @@ async fn test_truncate_first_message(cx: &mut TestAppContext) {
// Ensure we can still send a new message after truncation.
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hi"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hi"], cx)
})
.unwrap();
thread.update(cx, |thread, _cx| {
@@ -3190,7 +3200,7 @@ async fn test_latest_token_usage_counts_cached_input_tokens(cx: &mut TestAppCont
let ThreadTest { model, thread, .. } = setup(cx, TestModel::Fake).await;
let fake_model = model.as_fake();
- let message_1_id = UserMessageId::new();
+ let message_1_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_1_id, ["Message 1"], cx)
@@ -3223,7 +3233,7 @@ async fn test_latest_token_usage_counts_cached_input_tokens(cx: &mut TestAppCont
);
});
- let message_2_id = UserMessageId::new();
+ let message_2_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_2_id.clone(), ["Message 2"], cx)
@@ -3249,7 +3259,7 @@ async fn test_cumulative_token_usage(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
thread.add_tool(EchoTool);
- thread.send(UserMessageId::new(), ["Use the echo tool"], cx)
+ thread.send(ClientUserMessageId::new(), ["Use the echo tool"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3339,7 +3349,7 @@ async fn test_cumulative_token_usage_keeps_accounted_usage_monotonic(cx: &mut Te
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3383,7 +3393,7 @@ async fn test_truncate_second_message(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Message 1"], cx)
+ thread.send(ClientUserMessageId::new(), ["Message 1"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3429,7 +3439,7 @@ async fn test_truncate_second_message(cx: &mut TestAppContext) {
assert_first_message_state(cx);
- let second_message_id = UserMessageId::new();
+ let second_message_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(second_message_id.clone(), ["Message 2"], cx)
@@ -3503,7 +3513,7 @@ async fn test_title_generation(cx: &mut TestAppContext) {
let send = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3527,7 +3537,7 @@ async fn test_title_generation(cx: &mut TestAppContext) {
// Send another message, ensuring no title is generated this time.
let send = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello again"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello again"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3591,7 +3601,7 @@ async fn test_db_thread_markdown_matches_live_thread(cx: &mut TestAppContext) {
let send = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3620,7 +3630,7 @@ async fn test_title_generation_failure_allows_retry(cx: &mut TestAppContext) {
let send = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3676,7 +3686,7 @@ async fn test_building_request_with_pending_tools(cx: &mut TestAppContext) {
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
thread.add_tool(EchoTool);
- thread.send(UserMessageId::new(), ["Hey!"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hey!"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3855,8 +3865,9 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
drop(acp_thread);
let result = cx
.update(|cx| {
- connection.prompt(
- acp_thread::UserMessageId::new(),
+ acp_thread::AgentSessionClientUserMessageIds::prompt(
+ &connection,
+ acp_thread::ClientUserMessageId::new(),
acp::PromptRequest::new(session_id.clone(), vec!["ghi".into()]),
cx,
)
@@ -3878,7 +3889,7 @@ async fn test_tool_updates_to_completion(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Echo something"], cx)
+ thread.send(ClientUserMessageId::new(), ["Echo something"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3956,7 +3967,7 @@ async fn test_send_no_retry_on_success(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello!"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello!"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -3999,7 +4010,7 @@ async fn test_send_retry_on_error(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello!"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello!"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -4064,7 +4075,7 @@ async fn test_send_retry_finishes_tool_calls_on_error(cx: &mut TestAppContext) {
let events = thread
.update(cx, |thread, cx| {
thread.add_tool(EchoTool);
- thread.send(UserMessageId::new(), ["Call the echo tool!"], cx)
+ thread.send(ClientUserMessageId::new(), ["Call the echo tool!"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -4143,7 +4154,7 @@ async fn test_send_max_retries_exceeded(cx: &mut TestAppContext) {
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Hello!"], cx)
+ thread.send(ClientUserMessageId::new(), ["Hello!"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -4206,7 +4217,11 @@ async fn test_streaming_tool_completes_when_llm_stream_ends_without_final_input(
let _events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Use the streaming_echo tool"], cx)
+ thread.send(
+ ClientUserMessageId::new(),
+ ["Use the streaming_echo tool"],
+ cx,
+ )
})
.unwrap();
cx.run_until_parked();
@@ -4310,7 +4325,7 @@ async fn test_streaming_tool_json_parse_error_is_forwarded_to_running_tool(
let _events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Use the streaming_json_error_context tool"],
cx,
)
@@ -4670,7 +4685,7 @@ async fn test_tokens_before_message(cx: &mut TestAppContext) {
let fake_model = model.as_fake();
// First message
- let message_1_id = UserMessageId::new();
+ let message_1_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_1_id.clone(), ["First message"], cx)
@@ -4710,7 +4725,7 @@ async fn test_tokens_before_message(cx: &mut TestAppContext) {
});
// Second message
- let message_2_id = UserMessageId::new();
+ let message_2_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_2_id.clone(), ["Second message"], cx)
@@ -4741,7 +4756,7 @@ async fn test_tokens_before_message(cx: &mut TestAppContext) {
cx.run_until_parked();
// Third message
- let message_3_id = UserMessageId::new();
+ let message_3_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_3_id.clone(), ["Third message"], cx)
@@ -4777,7 +4792,7 @@ async fn test_tokens_before_message_after_truncate(cx: &mut TestAppContext) {
let fake_model = model.as_fake();
// Set up three messages with responses
- let message_1_id = UserMessageId::new();
+ let message_1_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_1_id.clone(), ["Message 1"], cx)
@@ -4796,7 +4811,7 @@ async fn test_tokens_before_message_after_truncate(cx: &mut TestAppContext) {
fake_model.end_last_completion_stream();
cx.run_until_parked();
- let message_2_id = UserMessageId::new();
+ let message_2_id = ClientUserMessageId::new();
thread
.update(cx, |thread, cx| {
thread.send(message_2_id.clone(), ["Message 2"], cx)
@@ -5893,7 +5908,7 @@ async fn test_lsp_tools_gated_by_feature_flag(cx: &mut TestAppContext) {
// `enabled_for_staff`, so it is already visible in debug builds.
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -5928,7 +5943,7 @@ async fn test_lsp_tools_gated_by_feature_flag(cx: &mut TestAppContext) {
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["hello again"], cx)
+ thread.send(ClientUserMessageId::new(), ["hello again"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -6022,7 +6037,7 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
set_flag_override("off", cx);
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["hello"], cx)
+ thread.send(ClientUserMessageId::new(), ["hello"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -6048,7 +6063,7 @@ async fn test_sibling_thread_tools_gated_by_feature_flag(cx: &mut TestAppContext
set_flag_override("on", cx);
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["hello again"], cx)
+ thread.send(ClientUserMessageId::new(), ["hello again"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -6100,7 +6115,7 @@ async fn test_parent_cancel_stops_subagent(cx: &mut TestAppContext) {
subagent
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Do work".to_string()], cx)
+ thread.send(ClientUserMessageId::new(), ["Do work".to_string()], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7074,7 +7089,7 @@ async fn test_always_allow_resolves_pending_authorizations(cx: &mut TestAppConte
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7155,7 +7170,7 @@ async fn test_external_settings_edit_resolves_pending_authorization(cx: &mut Tes
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7226,7 +7241,7 @@ async fn test_external_deny_rule_resolves_pending_authorization(cx: &mut TestApp
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7302,7 +7317,7 @@ async fn test_unrelated_settings_change_does_not_resolve_pending_authorization(
let mut events = thread
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7366,7 +7381,7 @@ async fn test_always_allow_does_not_resolve_unrelated_tool_authorization(cx: &mu
.update(cx, |thread, cx| {
thread.add_tool(ToolRequiringPermission);
thread.add_tool(ToolRequiringPermission2);
- thread.send(UserMessageId::new(), ["abc"], cx)
+ thread.send(ClientUserMessageId::new(), ["abc"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7468,7 +7483,7 @@ async fn test_queued_message_ends_turn_at_boundary(cx: &mut TestAppContext) {
// Start a turn by sending a message
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Use the echo tool"], cx)
+ thread.send(ClientUserMessageId::new(), ["Use the echo tool"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7551,7 +7566,7 @@ async fn test_queued_message_does_not_end_turn_without_boundary_flag(cx: &mut Te
let mut events = thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["Use the echo tool"], cx)
+ thread.send(ClientUserMessageId::new(), ["Use the echo tool"], cx)
})
.unwrap();
cx.run_until_parked();
@@ -7616,7 +7631,7 @@ async fn test_streaming_tool_error_breaks_stream_loop_immediately(cx: &mut TestA
let _events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Use the streaming_failing_echo tool"],
cx,
)
@@ -7697,7 +7712,7 @@ async fn test_streaming_tool_error_waits_for_prior_tools_to_complete(cx: &mut Te
let _events = thread
.update(cx, |thread, cx| {
thread.send(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
["Use the streaming_echo tool and the streaming_failing_echo tool"],
cx,
)
@@ -7840,7 +7855,7 @@ async fn test_mid_turn_model_and_settings_refresh(cx: &mut TestAppContext) {
// Send a message — first iteration starts with model A, profile-a, thinking off.
thread
.update(cx, |thread, cx| {
- thread.send(UserMessageId::new(), ["test mid-turn refresh"], cx)
+ thread.send(ClientUserMessageId::new(), ["test mid-turn refresh"], cx)
})
.unwrap();
cx.run_until_parked();
diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs
index e70a4b2dbb7..899f979a717 100644
--- a/crates/agent/src/thread.rs
+++ b/crates/agent/src/thread.rs
@@ -7,7 +7,7 @@ use crate::{
TerminalTool, ToolPermissionDecision, WebSearchTool, WriteFileTool,
decide_permission_from_settings,
};
-use acp_thread::{MentionUri, UserMessageId};
+use acp_thread::{ClientUserMessageId, MentionUri};
use action_log::ActionLog;
use agent_settings::UserAgentsMd;
@@ -241,7 +241,7 @@ impl Message {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct UserMessage {
- pub id: UserMessageId,
+ pub id: ClientUserMessageId,
pub content: Arc<[UserMessageContent]>,
}
@@ -1215,7 +1215,7 @@ pub struct Thread {
end_turn_at_next_boundary: bool,
pending_message: Option<AgentMessage>,
pub(crate) tools: BTreeMap<SharedString, Arc<dyn AnyAgentTool>>,
- request_token_usage: HashMap<UserMessageId, language_model::TokenUsage>,
+ request_token_usage: HashMap<ClientUserMessageId, language_model::TokenUsage>,
cumulative_token_usage: TokenUsage,
/// The per-field maximum usage snapshot already added to
/// `cumulative_token_usage` for the in-flight completion request. Reset at
@@ -2292,14 +2292,18 @@ impl Thread {
cx.notify();
}
- pub fn truncate(&mut self, message_id: UserMessageId, cx: &mut Context<Self>) -> Result<()> {
+ pub fn truncate(
+ &mut self,
+ client_user_message_id: ClientUserMessageId,
+ cx: &mut Context<Self>,
+ ) -> Result<()> {
self.cancel(cx).detach();
// Clear pending message since cancel will try to flush it asynchronously,
// and we don't want that content to be added after we truncate
self.pending_message.take();
- let Some(position) = self.messages.iter().position(
- |msg| matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &message_id),
- ) else {
+ let Some(position) = self.messages.iter().position(|msg| {
+ matches!(&**msg, Message::User(UserMessage { id, .. }) if id == &client_user_message_id)
+ }) else {
return Err(anyhow!("Message not found"));
};
@@ -2346,8 +2350,8 @@ impl Thread {
/// - `target_id` is the first message (no previous message)
/// - The previous message hasn't received a response yet (no usage data)
/// - `target_id` is not found in the messages
- pub fn tokens_before_message(&self, target_id: &UserMessageId) -> Option<u64> {
- let mut previous_user_message_id: Option<&UserMessageId> = None;
+ pub fn tokens_before_message(&self, target_id: &ClientUserMessageId) -> Option<u64> {
+ let mut previous_user_message_id: Option<&ClientUserMessageId> = None;
for message in &self.messages {
if let Message::User(user_msg) = &**message {
@@ -2407,7 +2411,7 @@ impl Thread {
/// The returned channel will report all the occurrences in which the model stops before erroring or ending its turn.
pub fn send<T>(
&mut self,
- id: UserMessageId,
+ id: ClientUserMessageId,
content: impl IntoIterator<Item = T>,
cx: &mut Context<Self>,
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>
@@ -2443,7 +2447,7 @@ impl Thread {
/// regardless of the current token usage or context window size.
pub fn compact(
&mut self,
- id: UserMessageId,
+ id: ClientUserMessageId,
cx: &mut Context<Self>,
) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>> {
let model = self
@@ -2535,7 +2539,7 @@ impl Thread {
pub fn push_acp_user_block(
&mut self,
- id: UserMessageId,
+ id: ClientUserMessageId,
blocks: impl IntoIterator<Item = acp::ContentBlock>,
path_style: PathStyle,
cx: &mut Context<Self>,
@@ -4607,7 +4611,7 @@ enum CompactionInsertion {
/// (which may be before a trailing not-yet-answered user message).
Auto { insertion_ix: usize },
/// Manual `/compact` appends a zero-content user message followed by the summary.
- Manual { marker_id: UserMessageId },
+ Manual { marker_id: ClientUserMessageId },
}
struct RunningTurn {
@@ -6484,7 +6488,7 @@ mod tests {
);
}
- fn user_text_message(id: UserMessageId, text: &str) -> Arc<Message> {
+ fn user_text_message(id: ClientUserMessageId, text: &str) -> Arc<Message> {
Arc::new(Message::User(UserMessage {
id,
content: vec![UserMessageContent::Text(text.to_string())].into(),
@@ -6520,7 +6524,7 @@ mod tests {
async fn test_compaction_threshold_uses_percentage_setting(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -6556,7 +6560,7 @@ mod tests {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
model.set_max_output_tokens(Some(32_000));
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -6619,7 +6623,7 @@ mod tests {
async fn test_compaction_threshold_respects_enabled_setting(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
set_auto_compact_settings(
@@ -6651,7 +6655,7 @@ mod tests {
async fn test_compaction_threshold_respects_token_settings(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
set_auto_compact_settings(
@@ -6723,7 +6727,7 @@ mod tests {
let model = Arc::new(FakeLanguageModel::default());
// A context window below the minimum disables auto-compaction.
model.set_max_token_count(MIN_COMPACTION_CONTEXT_WINDOW - 1);
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -6750,8 +6754,8 @@ mod tests {
) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
- let old_user_message_id = UserMessageId::new();
- let new_user_message_id = UserMessageId::new();
+ let old_user_message_id = ClientUserMessageId::new();
+ let new_user_message_id = ClientUserMessageId::new();
cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -6829,8 +6833,8 @@ mod tests {
// A context window below the minimum and no recorded token usage would
// both disable *automatic* compaction. Manual compaction forces it anyway.
model.set_max_token_count(MIN_COMPACTION_CONTEXT_WINDOW - 1);
- let user_message_id = UserMessageId::new();
- let compact_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
+ let compact_message_id = ClientUserMessageId::new();
cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -6913,13 +6917,17 @@ mod tests {
thread.set_model(model.clone(), cx);
thread
.messages
- .push(user_text_message(UserMessageId::new(), "old user"));
+ .push(user_text_message(ClientUserMessageId::new(), "old user"));
thread.messages.push(agent_text_message("old assistant"));
});
});
let _events = cx
- .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))
+ .update(|cx| {
+ thread.update(cx, |thread, cx| {
+ thread.compact(ClientUserMessageId::new(), cx)
+ })
+ })
.unwrap();
cx.run_until_parked();
// The compaction request is in flight but hasn't streamed a summary.
@@ -6948,13 +6956,17 @@ mod tests {
thread.set_model(model.clone(), cx);
thread
.messages
- .push(user_text_message(UserMessageId::new(), "old user"));
+ .push(user_text_message(ClientUserMessageId::new(), "old user"));
thread.messages.push(agent_text_message("old assistant"));
});
});
let mut events = cx
- .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))
+ .update(|cx| {
+ thread.update(cx, |thread, cx| {
+ thread.compact(ClientUserMessageId::new(), cx)
+ })
+ })
.unwrap();
cx.run_until_parked();
@@ -6989,7 +7001,11 @@ mod tests {
cx.update(|cx| thread.update(cx, |thread, cx| thread.set_model(model.clone(), cx)));
let _events = cx
- .update(|cx| thread.update(cx, |thread, cx| thread.compact(UserMessageId::new(), cx)))
+ .update(|cx| {
+ thread.update(cx, |thread, cx| {
+ thread.compact(ClientUserMessageId::new(), cx)
+ })
+ })
.unwrap();
cx.run_until_parked();
@@ -7005,13 +7021,13 @@ mod tests {
#[gpui::test]
async fn test_manual_compact_marker_replays_as_empty_user_message(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
- let marker_id = UserMessageId::new();
+ let marker_id = ClientUserMessageId::new();
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread
.messages
- .push(user_text_message(UserMessageId::new(), "before"));
+ .push(user_text_message(ClientUserMessageId::new(), "before"));
thread.messages.push(agent_text_message("answer"));
thread.messages.push(Arc::new(Message::User(UserMessage {
id: marker_id.clone(),
@@ -7049,8 +7065,8 @@ mod tests {
async fn test_compaction_usage_counts_toward_cumulative_usage(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
let model = Arc::new(FakeLanguageModel::default());
- let old_user_message_id = UserMessageId::new();
- let new_user_message_id = UserMessageId::new();
+ let old_user_message_id = ClientUserMessageId::new();
+ let new_user_message_id = ClientUserMessageId::new();
let prior_usage = TokenUsage {
input_tokens: 960_000,
output_tokens: 25,
@@ -7149,7 +7165,7 @@ mod tests {
#[gpui::test]
async fn test_replay_emits_context_compaction(cx: &mut TestAppContext) {
let (thread, _event_stream) = setup_thread_for_test(cx).await;
- let user_message_id = UserMessageId::new();
+ let user_message_id = ClientUserMessageId::new();
let mut replay_events = cx.update(|cx| {
thread.update(cx, |thread, cx| {
@@ -7201,18 +7217,20 @@ mod tests {
let request_messages = cx.update(|cx| {
thread.update(cx, |thread, cx| {
- thread
- .messages
- .push(user_text_message(UserMessageId::new(), "before native"));
+ thread.messages.push(user_text_message(
+ ClientUserMessageId::new(),
+ "before native",
+ ));
thread.messages.push(Arc::new(Message::Compaction(
CompactionInfo::ProviderNative {
provider: LanguageModelProviderId::from("openai".to_string()),
items: vec![json!({"type": "compaction"})],
},
)));
- thread
- .messages
- .push(user_text_message(UserMessageId::new(), "after native"));
+ thread.messages.push(user_text_message(
+ ClientUserMessageId::new(),
+ "after native",
+ ));
thread.build_request_messages(Vec::new(), cx)
})
@@ -7234,7 +7252,7 @@ mod tests {
let request_messages = cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread.messages.push(user_text_message(
- UserMessageId::new(),
+ ClientUserMessageId::new(),
"dropped older user",
));
thread
@@ -7242,15 +7260,15 @@ mod tests {
.push(agent_text_message("dropped assistant"));
thread
.messages
- .push(user_text_message(UserMessageId::new(), &long_text));
+ .push(user_text_message(ClientUserMessageId::new(), &long_text));
thread
.messages
- .push(user_text_message(UserMessageId::new(), "new"));
+ .push(user_text_message(ClientUserMessageId::new(), "new"));
thread.messages.push(summary_compaction("summary context"));
thread.messages.push(agent_text_message("after assistant"));
thread
.messages
- .push(user_text_message(UserMessageId::new(), "after user"));
+ .push(user_text_message(ClientUserMessageId::new(), "after user"));
thread.build_request_messages(Vec::new(), cx)
})
diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs
index c3f920d36cb..ddec4877c7d 100644
--- a/crates/agent_servers/src/acp.rs
+++ b/crates/agent_servers/src/acp.rs
@@ -1857,7 +1857,6 @@ impl AgentConnection for AcpConnection {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
params: acp::PromptRequest,
cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
@@ -1993,8 +1992,8 @@ pub mod test_support {
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use acp_thread::{
- AgentSessionConfigOptions, AgentSessionModes, AgentSessionRetry, AgentSessionSetTitle,
- AgentSessionTruncate, AgentTelemetry, UserMessageId,
+ AgentSessionClientUserMessageIds, AgentSessionConfigOptions, AgentSessionModes,
+ AgentSessionRetry, AgentSessionSetTitle, AgentSessionTruncate, AgentTelemetry,
};
use super::*;
@@ -2207,13 +2206,19 @@ pub mod test_support {
self.inner.logout(cx)
}
+ fn client_user_message_ids(
+ &self,
+ cx: &App,
+ ) -> Option<Rc<dyn AgentSessionClientUserMessageIds>> {
+ self.inner.client_user_message_ids(cx)
+ }
+
fn prompt(
&self,
- user_message_id: UserMessageId,
params: acp::PromptRequest,
cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
- self.inner.prompt(user_message_id, params, cx)
+ self.inner.prompt(params, cx)
}
fn retry(
diff --git a/crates/agent_ui/src/agent_panel.rs b/crates/agent_ui/src/agent_panel.rs
index 6296d6c70ae..e8328ffc25d 100644
--- a/crates/agent_ui/src/agent_panel.rs
+++ b/crates/agent_ui/src/agent_panel.rs
@@ -6897,7 +6897,7 @@ mod tests {
active_session_id, active_thread_id, open_thread_with_connection,
open_thread_with_custom_connection, register_test_sidebar, send_message,
};
- use acp_thread::{AgentConnection, StubAgentConnection, ThreadStatus, UserMessageId};
+ use acp_thread::{AgentConnection, StubAgentConnection, ThreadStatus};
use action_log::ActionLog;
use anyhow::{Result, anyhow};
use feature_flags::FeatureFlagAppExt;
@@ -7086,7 +7086,6 @@ mod tests {
fn prompt(
&self,
- _id: UserMessageId,
params: acp::PromptRequest,
_cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
@@ -12866,7 +12865,6 @@ mod tests {
fn prompt(
&self,
- _id: UserMessageId,
params: acp::PromptRequest,
_cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index a5906ebd1a5..cb5058e9550 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -1,8 +1,8 @@
use acp_thread::{
AcpThread, AcpThreadEvent, AgentThreadEntry, AssistantMessage, AssistantMessageChunk,
- AuthRequired, LoadError, MaxOutputTokensError, MentionUri, PermissionOptionChoice,
- PermissionOptions, PermissionPattern, RetryStatus, SelectedPermissionOutcome, ThreadStatus,
- ToolCall, ToolCallContent, ToolCallStatus, UserMessageId,
+ AuthRequired, ClientUserMessageId, LoadError, MaxOutputTokensError, MentionUri,
+ PermissionOptionChoice, PermissionOptions, PermissionPattern, RetryStatus,
+ SelectedPermissionOutcome, ThreadStatus, ToolCall, ToolCallContent, ToolCallStatus,
};
use acp_thread::{AgentConnection, Plan};
use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
@@ -3757,7 +3757,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -5204,7 +5203,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -5312,7 +5310,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -5382,7 +5379,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -5498,7 +5494,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
@@ -5659,7 +5654,7 @@ pub(crate) mod tests {
let AgentThreadEntry::UserMessage(user_message) = &thread.entries()[2] else {
panic!();
};
- user_message.id.clone().unwrap()
+ user_message.client_id.clone().unwrap()
});
conversation_view.read_with(cx, |view, cx| {
@@ -6435,7 +6430,9 @@ pub(crate) mod tests {
.find_map(|entry| match entry {
AgentThreadEntry::AssistantMessage(message) => {
message.chunks.iter().find_map(|chunk| match chunk {
- AssistantMessageChunk::Message { block } => block.markdown().cloned(),
+ AssistantMessageChunk::Message { block, .. } => {
+ block.markdown().cloned()
+ }
AssistantMessageChunk::Thought { .. } => None,
})
}
@@ -10078,7 +10075,6 @@ pub(crate) mod tests {
fn prompt(
&self,
- _id: acp_thread::UserMessageId,
_params: acp::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp::PromptResponse>> {
diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
index 6563046ca1d..f936edcd35a 100644
--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs
+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
@@ -891,12 +891,12 @@ fn collect_markdowns(
AgentThreadEntry::AssistantMessage(message) => {
for (chunk_ix, chunk) in message.chunks.iter().enumerate() {
match chunk {
- AssistantMessageChunk::Message { block } => {
+ AssistantMessageChunk::Message { block, .. } => {
if let Some(md) = block.markdown() {
out.push(md.clone());
}
}
- AssistantMessageChunk::Thought { block }
+ AssistantMessageChunk::Thought { block, .. }
if entry_view_state
.thinking_block_state((entry_ix, chunk_ix), cx)
.0 =>
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index b60446071d8..2519d286281 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -1211,7 +1211,7 @@ impl ThreadView {
if let Some(AgentThreadEntry::UserMessage(user_message)) =
self.thread.read(cx).entries().get(event.entry_index)
&& self.thread.read(cx).supports_truncate(cx)
- && user_message.id.is_some()
+ && user_message.client_id.is_some()
&& !self.is_subagent()
{
self.editing_message = Some(event.entry_index);
@@ -1222,7 +1222,7 @@ impl ThreadView {
if let Some(AgentThreadEntry::UserMessage(user_message)) =
self.thread.read(cx).entries().get(event.entry_index)
&& self.thread.read(cx).supports_truncate(cx)
- && user_message.id.is_some()
+ && user_message.client_id.is_some()
&& !self.is_subagent()
{
if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
@@ -1940,8 +1940,13 @@ impl ThreadView {
}
let thread = self.thread.clone();
- let Some(user_message_id) = thread.update(cx, |thread, _| {
- thread.entries().get(entry_ix)?.user_message()?.id.clone()
+ let Some(client_id) = thread.update(cx, |thread, _| {
+ thread
+ .entries()
+ .get(entry_ix)?
+ .user_message()?
+ .client_id
+ .clone()
}) else {
return;
};
@@ -1977,7 +1982,7 @@ impl ThreadView {
}
thread
- .update(cx, |thread, cx| thread.rewind(user_message_id, cx))
+ .update(cx, |thread, cx| thread.rewind(client_id, cx))
.await?;
this.update_in(cx, |thread, window, cx| {
cx.emit(AcpThreadViewEvent::Interacted);
@@ -2684,10 +2689,10 @@ impl ThreadView {
// thread stuff
- pub fn restore_checkpoint(&mut self, message_id: &UserMessageId, cx: &mut Context<Self>) {
+ pub fn restore_checkpoint(&mut self, client_id: &ClientUserMessageId, cx: &mut Context<Self>) {
self.thread
.update(cx, |thread, cx| {
- thread.restore_checkpoint(message_id.clone(), cx)
+ thread.restore_checkpoint(client_id.clone(), cx)
})
.detach_and_log_err(cx);
}
@@ -5941,7 +5946,7 @@ impl ThreadView {
let is_subagent = self.is_subagent();
let can_rewind = self.thread.read(cx).supports_truncate(cx);
- let is_editable = can_rewind && message.id.is_some() && !is_subagent;
+ let is_editable = can_rewind && message.client_id.is_some() && !is_subagent;
let agent_name = if is_subagent {
"subagents".into()
} else {
@@ -5962,7 +5967,7 @@ impl ThreadView {
.gap_1p5()
.w_full()
.when(is_editable && has_checkpoint_button, |this| {
- this.children(message.id.clone().map(|message_id| {
+ this.children(message.client_id.clone().map(|client_id| {
h_flex()
.px_3()
.gap_2()
@@ -5974,7 +5979,7 @@ impl ThreadView {
.color(Color::Muted)
.tooltip(Tooltip::text("Restores all files in the project to the content they had at this point in the conversation."))
.on_click(cx.listener(move |this, _, _window, cx| {
- this.restore_checkpoint(&message_id, cx);
+ this.restore_checkpoint(&client_id, cx);
}))
)
.child(Divider::horizontal())
@@ -6112,7 +6117,7 @@ impl ThreadView {
.gap_3()
.children(chunks.iter().enumerate().filter_map(
|(chunk_ix, chunk)| match chunk {
- AssistantMessageChunk::Message { block } => {
+ AssistantMessageChunk::Message { block, .. } => {
block.markdown().and_then(|md| {
let this_is_blank = md.read(cx).source().trim().is_empty();
is_blank = is_blank && this_is_blank;
@@ -6126,7 +6131,7 @@ impl ThreadView {
)
})
}
- AssistantMessageChunk::Thought { block } => {
+ AssistantMessageChunk::Thought { block, .. } => {
block.markdown().and_then(|md| {
let this_is_blank = md.read(cx).source().trim().is_empty();
is_blank = is_blank && this_is_blank;
@@ -7098,8 +7103,12 @@ impl ThreadView {
.map(|chunks| {
chunks.iter().any(|chunk| {
let md = match chunk {
- AssistantMessageChunk::Message { block } => block.markdown(),
- AssistantMessageChunk::Thought { block } => block.markdown(),
+ AssistantMessageChunk::Message { block, .. } => {
+ block.markdown()
+ }
+ AssistantMessageChunk::Thought { block, .. } => {
+ block.markdown()
+ }
};
md.map_or(false, |m| m.read(cx).selected_text().is_some())
})
@@ -7109,8 +7118,8 @@ impl ThreadView {
let context_menu_link = chunks.and_then(|chunks| {
chunks.iter().find_map(|chunk| {
let md = match chunk {
- AssistantMessageChunk::Message { block } => block.markdown(),
- AssistantMessageChunk::Thought { block } => block.markdown(),
+ AssistantMessageChunk::Message { block, .. } => block.markdown(),
+ AssistantMessageChunk::Thought { block, .. } => block.markdown(),
};
md.and_then(|m| m.read(cx).context_menu_link().cloned())
})
@@ -7216,7 +7225,7 @@ impl ThreadView {
.chunks
.iter()
.filter_map(|chunk| match chunk {
- AssistantMessageChunk::Message { block } => {
+ AssistantMessageChunk::Message { block, .. } => {
let markdown = block.to_markdown(cx);
if markdown.trim().is_empty() {
None
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index fd1b2867f0b..d19a1067bae 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -235,7 +235,7 @@ impl EntryViewState {
match thread_entry {
AgentThreadEntry::UserMessage(message) => {
let can_rewind = thread.read(cx).supports_truncate(cx);
- let has_id = message.id.is_some();
+ let has_client_id = message.client_id.is_some();
let is_subagent = thread.read(cx).parent_session_id().is_some();
let chunks = message.chunks.clone();
if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) {
@@ -262,7 +262,7 @@ impl EntryViewState {
window,
cx,
);
- if !can_rewind || !has_id || is_subagent {
+ if !can_rewind || !has_client_id || is_subagent {
editor.set_read_only(true, cx);
}
editor.set_message(chunks, window, cx);
diff --git a/crates/eval_cli/src/main.rs b/crates/eval_cli/src/main.rs
index ef00fc87e24..fc8074914c6 100644
--- a/crates/eval_cli/src/main.rs
+++ b/crates/eval_cli/src/main.rs
@@ -970,7 +970,7 @@ fn log_acp_thread_event(
let entries = acp_thread.read(cx).entries();
if let Some(acp_thread::AgentThreadEntry::AssistantMessage(message)) = entries.last() {
for chunk in &message.chunks {
- if let acp_thread::AssistantMessageChunk::Message { block } = chunk {
+ if let acp_thread::AssistantMessageChunk::Message { id: _, block } = chunk {
if let acp_thread::ContentBlock::Markdown { markdown } = block {
let text = markdown.read(cx).source().to_string();
if !text.is_empty() {