Adopt shared ACP v2 content values

This commit is contained in:
Ben Brandt
2026-09-25 11:23:27 +02:00
parent b166b0c52d
commit 2d1b5345c0
10 changed files with 1107 additions and 211 deletions
+1 -1
View File
@@ -520,7 +520,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] }
accesskit_macos = "0.26.0"
accesskit_unix = "0.22"
accesskit_windows = "0.34"
agent-client-protocol = { version = "=2.2.0", features = ["unstable"] }
agent-client-protocol = { version = "=2.2.0", features = ["unstable", "unstable_protocol_v2"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" }
any_vec = "0.14"
File diff suppressed because it is too large Load Diff
+24 -4
View File
@@ -767,6 +767,7 @@ mod test_support {
sessions: Arc<Mutex<HashMap<acp_v1::SessionId, Session>>>,
permission_requests: HashMap<acp_v1::ToolCallId, PermissionOptions>,
next_prompt_updates: Arc<Mutex<Vec<acp_v1::SessionUpdate>>>,
next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
supports_load_session: bool,
supports_session_additional_directories: bool,
agent_id: AgentId,
@@ -788,6 +789,7 @@ mod test_support {
pub fn new() -> Self {
Self {
next_prompt_updates: Default::default(),
next_truncate: Default::default(),
permission_requests: HashMap::default(),
sessions: Arc::default(),
supports_load_session: false,
@@ -801,6 +803,12 @@ mod test_support {
*self.next_prompt_updates.lock() = updates;
}
pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {
let (sender, receiver) = oneshot::channel();
assert!(self.next_truncate.lock().replace(receiver).is_none());
sender
}
pub fn with_permission_requests(
mut self,
permission_requests: HashMap<acp_v1::ToolCallId, PermissionOptions>,
@@ -1060,7 +1068,10 @@ mod test_support {
_session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionTruncate>> {
Some(Rc::new(StubAgentSessionEditor))
// Capability checks also call this; only run may consume the gate.
Some(Rc::new(StubAgentSessionEditor {
next_truncate: self.next_truncate.clone(),
}))
}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
@@ -1091,11 +1102,20 @@ mod test_support {
}
}
struct StubAgentSessionEditor;
struct StubAgentSessionEditor {
next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
}
impl AgentSessionTruncate for StubAgentSessionEditor {
fn run(&self, _: ClientUserMessageId, _: &mut App) -> Task<Result<()>> {
Task::ready(Ok(()))
fn run(&self, _: ClientUserMessageId, cx: &mut App) -> Task<Result<()>> {
if let Some(receiver) = self.next_truncate.lock().take() {
cx.foreground_executor().spawn(async move {
receiver.await?;
Ok(())
})
} else {
Task::ready(Ok(()))
}
}
}
+348
View File
@@ -0,0 +1,348 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use anyhow::{Result, bail};
pub fn from_v1(block: acp_v1::ContentBlock) -> Result<acp_v2::ContentBlock> {
Ok(match block {
acp_v1::ContentBlock::Text(content) => acp_v2::ContentBlock::Text(
acp_v2::TextContent::new(content.text)
.annotations(annotations_from_v1(content.annotations)?)
.meta(content.meta),
),
acp_v1::ContentBlock::Image(content) => acp_v2::ContentBlock::Image(
acp_v2::ImageContent::new(content.data, content.mime_type)
.uri(content.uri)
.annotations(annotations_from_v1(content.annotations)?)
.meta(content.meta),
),
acp_v1::ContentBlock::Audio(content) => acp_v2::ContentBlock::Audio(
acp_v2::AudioContent::new(content.data, content.mime_type)
.annotations(annotations_from_v1(content.annotations)?)
.meta(content.meta),
),
acp_v1::ContentBlock::ResourceLink(content) => acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new(content.name, content.uri)
.title(content.title)
.description(content.description)
.mime_type(content.mime_type.map(acp_v2::MediaType::new))
.size(content.size)
.annotations(annotations_from_v1(content.annotations)?)
.meta(content.meta),
),
acp_v1::ContentBlock::Resource(content) => {
let resource = match content.resource {
acp_v1::EmbeddedResourceResource::TextResourceContents(resource) => {
acp_v2::EmbeddedResourceResource::TextResourceContents(
acp_v2::TextResourceContents::new(resource.text, resource.uri)
.mime_type(resource.mime_type.map(acp_v2::MediaType::new))
.meta(resource.meta),
)
}
acp_v1::EmbeddedResourceResource::BlobResourceContents(resource) => {
acp_v2::EmbeddedResourceResource::BlobResourceContents(
acp_v2::BlobResourceContents::new(resource.blob, resource.uri)
.mime_type(resource.mime_type.map(acp_v2::MediaType::new))
.meta(resource.meta),
)
}
_ => bail!("unsupported v1 embedded resource variant"),
};
acp_v2::ContentBlock::Resource(
acp_v2::EmbeddedResource::new(resource)
.annotations(annotations_from_v1(content.annotations)?)
.meta(content.meta),
)
}
_ => bail!("unsupported v1 content block variant"),
})
}
pub fn to_v1(block: acp_v2::ContentBlock) -> Result<acp_v1::ContentBlock> {
Ok(match block {
acp_v2::ContentBlock::Text(content) => acp_v1::ContentBlock::Text(
acp_v1::TextContent::new(content.text)
.annotations(annotations_to_v1(content.annotations)?)
.meta(content.meta),
),
acp_v2::ContentBlock::Image(content) => acp_v1::ContentBlock::Image(
acp_v1::ImageContent::new(content.data, content.mime_type.0.to_string())
.uri(content.uri)
.annotations(annotations_to_v1(content.annotations)?)
.meta(content.meta),
),
acp_v2::ContentBlock::Audio(content) => acp_v1::ContentBlock::Audio(
acp_v1::AudioContent::new(content.data, content.mime_type.0.to_string())
.annotations(annotations_to_v1(content.annotations)?)
.meta(content.meta),
),
acp_v2::ContentBlock::ResourceLink(content) => {
if content.icons.is_some() {
bail!("v2 resource link icons cannot be represented in v1");
}
acp_v1::ContentBlock::ResourceLink(
acp_v1::ResourceLink::new(content.name, content.uri)
.title(content.title)
.description(content.description)
.mime_type(content.mime_type.map(|mime_type| mime_type.0.to_string()))
.size(content.size)
.annotations(annotations_to_v1(content.annotations)?)
.meta(content.meta),
)
}
acp_v2::ContentBlock::Resource(content) => {
let resource = match content.resource {
acp_v2::EmbeddedResourceResource::TextResourceContents(resource) => {
acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new(resource.text, resource.uri)
.mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string()))
.meta(resource.meta),
)
}
acp_v2::EmbeddedResourceResource::BlobResourceContents(resource) => {
acp_v1::EmbeddedResourceResource::BlobResourceContents(
acp_v1::BlobResourceContents::new(resource.blob, resource.uri)
.mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string()))
.meta(resource.meta),
)
}
_ => bail!("unsupported v2 embedded resource variant"),
};
acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(resource)
.annotations(annotations_to_v1(content.annotations)?)
.meta(content.meta),
)
}
acp_v2::ContentBlock::Other(_) => {
bail!("v2 custom content block cannot be represented in v1")
}
_ => bail!("unsupported v2 content block variant"),
})
}
pub fn can_convert_to_v1(block: &acp_v2::ContentBlock) -> bool {
let annotations = match block {
acp_v2::ContentBlock::Text(content) => &content.annotations,
acp_v2::ContentBlock::Image(content) => &content.annotations,
acp_v2::ContentBlock::Audio(content) => &content.annotations,
acp_v2::ContentBlock::ResourceLink(content) if content.icons.is_none() => {
&content.annotations
}
acp_v2::ContentBlock::Resource(content)
if matches!(
content.resource,
acp_v2::EmbeddedResourceResource::TextResourceContents(_)
| acp_v2::EmbeddedResourceResource::BlobResourceContents(_)
) =>
{
&content.annotations
}
_ => return false,
};
annotations
.as_ref()
.and_then(|annotations| annotations.audience.as_ref())
.is_none_or(|audience| {
audience
.iter()
.all(|role| matches!(role, acp_v2::Role::Assistant | acp_v2::Role::User))
})
}
fn annotations_from_v1(
annotations: Option<acp_v1::Annotations>,
) -> Result<Option<acp_v2::Annotations>> {
annotations
.map(|annotations| {
let audience = annotations
.audience
.map(|audience| {
audience
.into_iter()
.map(|role| match role {
acp_v1::Role::Assistant => Ok(acp_v2::Role::Assistant),
acp_v1::Role::User => Ok(acp_v2::Role::User),
_ => bail!("unsupported v1 annotation role"),
})
.collect::<Result<Vec<_>>>()
})
.transpose()?;
Ok(acp_v2::Annotations::new()
.audience(audience)
.last_modified(annotations.last_modified)
.priority(annotations.priority)
.meta(annotations.meta))
})
.transpose()
}
fn annotations_to_v1(
annotations: Option<acp_v2::Annotations>,
) -> Result<Option<acp_v1::Annotations>> {
annotations
.map(|annotations| {
let audience = annotations
.audience
.map(|audience| {
audience
.into_iter()
.map(|role| match role {
acp_v2::Role::Assistant => Ok(acp_v1::Role::Assistant),
acp_v2::Role::User => Ok(acp_v1::Role::User),
acp_v2::Role::Other(_) => {
bail!("v2 annotation role cannot be represented in v1")
}
_ => bail!("unsupported v2 annotation role"),
})
.collect::<Result<Vec<_>>>()
})
.transpose()?;
Ok(acp_v1::Annotations::new()
.audience(audience)
.last_modified(annotations.last_modified)
.priority(annotations.priority)
.meta(annotations.meta))
})
.transpose()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::{Value, json};
use std::collections::BTreeMap;
fn meta() -> serde_json::Map<String, Value> {
serde_json::Map::from_iter([("origin".to_owned(), json!({"nested": [0, null, "value"]}))])
}
fn annotations() -> acp_v1::Annotations {
acp_v1::Annotations::new()
.audience(vec![acp_v1::Role::User, acp_v1::Role::Assistant])
.last_modified("2025-01-02T03:04:05Z")
.priority(0.75)
.meta(meta())
}
fn round_trip(block: acp_v1::ContentBlock) {
let original = block.clone();
let upgraded = from_v1(block).expect("v1 block should convert to v2");
assert!(can_convert_to_v1(&upgraded));
assert_eq!(
serde_json::to_value(&upgraded).expect("serialize v2 block"),
serde_json::to_value(&original).expect("serialize original block")
);
let restored = to_v1(upgraded).expect("converted block should convert back to v1");
assert_eq!(restored, original);
}
fn rejects(block: acp_v2::ContentBlock) {
assert!(!can_convert_to_v1(&block));
assert!(to_v1(block).is_err());
}
#[test]
fn preserves_all_v1_content_variants_and_metadata() {
round_trip(acp_v1::ContentBlock::Text(
acp_v1::TextContent::new("Hello \0 世界")
.annotations(annotations())
.meta(meta()),
));
round_trip(acp_v1::ContentBlock::Image(
acp_v1::ImageContent::new("AAECA/8=", "not/a valid mime ; 😀")
.uri("")
.annotations(annotations())
.meta(meta()),
));
round_trip(acp_v1::ContentBlock::Audio(
acp_v1::AudioContent::new("///+", "")
.annotations(annotations())
.meta(meta()),
));
round_trip(acp_v1::ContentBlock::ResourceLink(
acp_v1::ResourceLink::new("name", "file:///some/resource")
.title("")
.description("description")
.mime_type("??")
.size(0)
.annotations(annotations())
.meta(meta()),
));
round_trip(acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new("source text", "file:///text")
.mime_type("")
.meta(meta()),
))
.annotations(annotations())
.meta(meta()),
));
round_trip(acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents(
acp_v1::BlobResourceContents::new("AAECA/8=", "file:///blob")
.mime_type("bad mime")
.meta(meta()),
))
.annotations(annotations())
.meta(meta()),
));
}
#[test]
fn preserves_absent_and_empty_optional_fields() {
round_trip(acp_v1::ContentBlock::Text(acp_v1::TextContent::new("")));
round_trip(acp_v1::ContentBlock::Text(
acp_v1::TextContent::new("")
.annotations(acp_v1::Annotations::new().audience(Vec::new())),
));
round_trip(acp_v1::ContentBlock::Text(
acp_v1::TextContent::new("")
.annotations(acp_v1::Annotations::new())
.meta(acp_v1::Meta::new()),
));
round_trip(acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new("", "").meta(acp_v1::Meta::new()),
))
.annotations(acp_v1::Annotations::new().meta(acp_v1::Meta::new()))
.meta(acp_v1::Meta::new()),
));
round_trip(acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(
"", "",
)));
round_trip(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new(
"", "",
)));
round_trip(acp_v1::ContentBlock::ResourceLink(
acp_v1::ResourceLink::new("", ""),
));
round_trip(acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new("", ""),
)),
));
round_trip(acp_v1::ContentBlock::Resource(
acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents(
acp_v1::BlobResourceContents::new("", ""),
)),
));
}
#[test]
fn rejects_v2_only_content_and_annotations() {
rejects(acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_custom",
BTreeMap::from([("payload".to_owned(), json!({"opaque": [1, 2]}))]),
)));
rejects(acp_v2::ContentBlock::Image(
acp_v2::ImageContent::new("AAE=", "image/png").annotations(
acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_custom".into())]),
),
));
rejects(acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new("name", "uri").icons(Vec::new()),
));
rejects(acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new("name", "uri").icons(vec![acp_v2::Icon::new("file:///icon")]),
));
}
}
+10 -5
View File
@@ -1981,6 +1981,7 @@ impl NativeAgent {
for message in prompt.messages {
let context_server::types::PromptMessage { role, content } = message;
let block = mcp_message_content_to_acp_content_block(content);
let display_block = acp_thread::content::from_v1(block.clone())?;
match role {
context_server::types::Role::User => {
@@ -1989,7 +1990,7 @@ impl NativeAgent {
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
Some(id.clone()),
block.clone(),
display_block,
true,
cx,
);
@@ -2002,7 +2003,7 @@ impl NativeAgent {
context_server::types::Role::Assistant => {
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_assistant_content_block_with_indent(
block.clone(),
display_block,
false,
true,
cx,
@@ -2154,10 +2155,11 @@ impl NativeAgent {
// 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::ClientUserMessageId::new();
let display_block = acp_thread::content::from_v1(envelope_block.clone())?;
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
Some(injected_id),
envelope_block.clone(),
display_block,
true,
cx,
);
@@ -2288,11 +2290,14 @@ impl NativeAgentConnection {
match event {
ThreadEvent::UserMessage(message) => {
let content = message.content.iter().cloned()
.map(|content| acp_thread::content::from_v1(content.into()))
.collect::<Result<Vec<_>>>()?;
acp_thread.update(cx, |thread, cx| {
for content in &*message.content {
for content in content {
thread.push_user_content_block(
Some(message.id.clone()),
content.clone().into(),
content,
cx,
);
}
+221
View File
@@ -1674,6 +1674,12 @@ impl ConversationView {
});
list_state.remeasure_items(*index..*index + 1);
active.update(cx, |active, cx| {
if active.editing_message == Some(*index)
&& !active.can_edit_user_message(*index, cx)
{
active.editing_message = None;
cx.notify();
}
active.sync_elicitation_state_for_entry(*index, window, cx);
active.auto_expand_streaming_thought(cx);
active.sync_generating_indicator(cx);
@@ -9103,6 +9109,221 @@ pub(crate) mod tests {
);
}
async fn assert_unsupported_source_message_cannot_regenerate(
unsupported: agent_client_protocol::schema::v2::ContentBlock,
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
init_test(cx);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::default_response(), cx).await;
add_to_workspace(conversation_view.clone(), cx);
let thread_view = active_thread(&conversation_view, cx);
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
thread
.update(cx, |thread, cx| thread.send_raw("original", cx))
.await
.expect("send initial message");
cx.run_until_parked();
let client_id = ClientUserMessageId::new();
thread.update(cx, |thread, cx| {
thread.push_user_content_block(
Some(client_id.clone()),
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("still visible")),
cx,
);
});
cx.run_until_parked();
let index = thread.read_with(cx, |thread, _| thread.entries().len() - 1);
let entry_view_state = thread_view.read_with(cx, |view, _| view.entry_view_state.clone());
let editor = entry_view_state.read_with(cx, |state, _| {
state
.entry(index)
.and_then(|entry| entry.message_editor())
.cloned()
.expect("user message editor")
});
cx.focus(&editor);
thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, Some(index)));
thread.update(cx, |thread, cx| {
thread.push_user_content_block(Some(client_id), unsupported.clone(), cx);
});
cx.run_until_parked();
thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None));
let rendered = editor.update(cx, |editor, cx| editor.text(cx));
assert!(rendered.contains("still visible"));
assert!(rendered.contains("Unsupported message content"));
cx.simulate_input("attempted edit");
assert_eq!(editor.update(cx, |editor, cx| editor.text(cx)), rendered);
thread_view.update_in(cx, |view, window, cx| {
view.handle_entry_view_event(
&entry_view_state,
&EntryViewEvent {
entry_index: index,
view_event: ViewEvent::MessageEditorEvent(
editor.clone(),
MessageEditorEvent::Send,
),
},
window,
cx,
);
view.regenerate(index, editor.clone(), window, cx);
});
let other_editor = entry_view_state.read_with(cx, |state, _| {
state
.entry(0)
.and_then(|entry| entry.message_editor())
.cloned()
.expect("original editor")
});
cx.focus(&other_editor);
other_editor.update_in(cx, |editor, window, cx| {
assert!(editor.focus_handle(cx).is_focused(window));
});
let composer = message_editor(&conversation_view, cx);
cx.focus(&composer);
cx.run_until_parked();
thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None));
thread.read_with(cx, |thread, _| {
assert_eq!(
thread.entries()[index]
.user_message()
.expect("user message")
.content
.source_blocks()[1],
unsupported
);
assert_eq!(thread.entries().len(), index + 1);
});
}
#[gpui::test]
async fn test_unsupported_source_message_cannot_regenerate(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
assert_unsupported_source_message_cannot_regenerate(
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
)),
cx,
)
.await;
}
#[gpui::test]
async fn test_unknown_annotation_source_message_cannot_regenerate(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
assert_unsupported_source_message_cannot_regenerate(
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("annotated text").annotations(
acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_future".into())]),
)),
cx,
)
.await;
}
#[gpui::test]
async fn test_regenerate_does_not_resend_fallback_after_delayed_rewind(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
init_test(cx);
for (cancel_before_update, cancel_after_update) in
[(false, false), (true, false), (false, true)]
{
let connection = StubAgentConnection::new();
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
add_to_workspace(conversation_view.clone(), cx);
let thread_view = active_thread(&conversation_view, cx);
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
let prompt = thread.update(cx, |thread, cx| thread.send_raw("original", cx));
cx.run_until_parked();
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn);
prompt.await.expect("initial prompt should finish");
cx.run_until_parked();
let client_id = thread.read_with(cx, |thread, _| {
thread
.entries()
.first()
.and_then(|entry| entry.user_message())
.and_then(|message| message.client_id.clone())
.expect("initial user message")
});
let editor = thread_view.read_with(cx, |view, cx| {
view.entry_view_state
.read(cx)
.entry(0)
.and_then(|entry| entry.message_editor())
.cloned()
.expect("initial message editor")
});
cx.focus(&editor);
editor.update_in(cx, |editor, window, cx| {
editor.set_text("edited", window, cx);
});
let finish_truncate = connection.defer_next_truncate();
thread_view.update_in(cx, |view, window, cx| {
view.regenerate(0, editor.clone(), window, cx);
});
cx.run_until_parked();
assert_eq!(thread.read_with(cx, |thread, _| thread.entries().len()), 1);
if cancel_before_update {
thread_view.update_in(cx, |view, window, cx| {
view.cancel_editing(&Default::default(), window, cx);
});
}
thread.update(cx, |thread, cx| {
thread.push_user_content_block(
Some(client_id),
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
)),
cx,
);
});
cx.run_until_parked();
if cancel_after_update {
thread_view.update_in(cx, |view, window, cx| {
view.cancel_editing(&Default::default(), window, cx);
});
}
assert!(
editor
.update(cx, |editor, cx| editor.text(cx))
.contains("Unsupported message content")
);
finish_truncate
.send(())
.expect("truncate should be pending");
cx.run_until_parked();
let resent =
thread.read_with(cx, |thread, _| thread.status() == ThreadStatus::Generating);
if resent {
connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
cx.run_until_parked();
}
assert!(!resent, "regeneration must not submit a read-only fallback");
thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
thread_view.read_with(cx, |view, _| assert!(view.thread_error.is_some()));
}
}
#[gpui::test]
async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
init_test(cx);
@@ -957,7 +957,11 @@ mod tests {
let error = cx.new(|cx| Markdown::new("error match".into(), None, None, cx));
let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
let unsupported_block = ContentBlock::new_output(
acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new("YXVkaW8=", "audio/wav")),
acp_thread::content::from_v1(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new(
"YXVkaW8=",
"audio/wav",
)))
.expect("known v1 audio content"),
&language_registry,
cx,
);
@@ -5,7 +5,7 @@ use crate::{
open_abs_path_at_point,
thread_metadata_store::{ThreadId, ThreadMetadataStore},
};
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use std::cell::RefCell;
use acp_thread::{
@@ -1234,6 +1234,25 @@ impl ThreadView {
self.parent_session_id.is_some()
}
pub(super) fn can_edit_user_message(&self, index: usize, cx: &App) -> bool {
let thread = self.thread.read(cx);
let Some(message) = thread
.entries()
.get(index)
.and_then(|entry| entry.user_message())
else {
return false;
};
!self.is_subagent()
&& thread.supports_truncate(cx)
&& message.client_id.is_some()
&& message
.content
.source_blocks()
.iter()
.all(acp_thread::content::can_convert_to_v1)
}
/// Returns the currently active editor, either for a message that is being
/// edited or the editor for a new message.
pub(crate) fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
@@ -1285,12 +1304,7 @@ impl ThreadView {
});
}
ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
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.client_id.is_some()
&& !self.is_subagent()
{
if self.can_edit_user_message(event.entry_index, cx) {
self.editing_message = Some(event.entry_index);
cx.notify();
}
@@ -1298,9 +1312,7 @@ impl ThreadView {
ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
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.client_id.is_some()
&& !self.is_subagent()
&& self.can_edit_user_message(event.entry_index, cx)
{
if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
self.editing_message = None;
@@ -1310,7 +1322,7 @@ impl ThreadView {
}
ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
if !self.is_subagent() {
if self.can_edit_user_message(event.entry_index, cx) {
self.regenerate(event.entry_index, editor.clone(), window, cx);
}
}
@@ -2011,7 +2023,7 @@ impl ThreadView {
window: &mut Window,
cx: &mut Context<Self>,
) {
if self.is_loading_contents {
if self.is_loading_contents || !self.can_edit_user_message(entry_ix, cx) {
return;
}
let thread = self.thread.clone();
@@ -2061,6 +2073,16 @@ impl ThreadView {
.update(cx, |thread, cx| thread.rewind(client_id, cx))
.await?;
this.update_in(cx, |thread, window, cx| {
// Rewind can outlive a source update that replaces the editor with a fallback.
if message_editor.read(cx).editor().read(cx).read_only(cx) {
thread.handle_thread_error(
anyhow!(
"The conversation was rewound, but the message became read-only and was not resent."
),
cx,
);
return;
}
cx.emit(AcpThreadViewEvent::Interacted);
thread.send_impl(message_editor, window, cx);
thread.activation_focus_handle(cx).focus(window, cx);
@@ -2473,7 +2495,11 @@ impl ThreadView {
.get(index)
.and_then(|e| e.user_message())
{
editor.set_message(user_message.content.source_blocks().to_vec(), window, cx);
editor.set_source_message(
user_message.content.source_blocks().to_vec(),
window,
cx,
);
}
})
};
@@ -6194,8 +6220,15 @@ impl ThreadView {
.is_some_and(|checkpoint| checkpoint.show);
let is_subagent = self.is_subagent();
let can_rewind = self.thread.read(cx).supports_truncate(cx);
let is_editable = can_rewind && message.client_id.is_some() && !is_subagent;
let can_restore_checkpoint = self.thread.read(cx).supports_truncate(cx)
&& message.client_id.is_some()
&& !is_subagent;
let source_is_representable = message
.content
.source_blocks()
.iter()
.all(acp_thread::content::can_convert_to_v1);
let is_editable = can_restore_checkpoint && source_is_representable;
let agent_name = if is_subagent {
"subagents".into()
} else {
@@ -6215,7 +6248,7 @@ impl ThreadView {
.px_2()
.gap_1p5()
.w_full()
.when(is_editable && has_checkpoint_button, |this| {
.when(can_restore_checkpoint && has_checkpoint_button, |this| {
this.children(message.client_id.clone().map(|client_id| {
h_flex()
.px_3()
@@ -6335,10 +6368,14 @@ impl ThreadView {
.child(Label::new("Unavailable Editing"))
.child(
div().max_w_64().child(
Label::new(format!(
"Editing previous messages is not available for {} yet.",
agent_name
))
Label::new(if source_is_representable {
format!(
"Editing previous messages is not available for {} yet.",
agent_name
)
} else {
"This message contains unsupported content and cannot be edited or resent.".to_string()
})
.size(LabelSize::Small)
.color(Color::Muted),
),
@@ -10336,7 +10373,7 @@ impl ThreadView {
fn render_embedded_resource_output(
&self,
resource: &acp_v1::EmbeddedResource,
resource: &acp_v2::EmbeddedResource,
context_ix: usize,
card_layout: bool,
cx: &Context<Self>,
@@ -10360,10 +10397,10 @@ impl ThreadView {
.into_any_element()
}
fn render_embedded_resource_label(&self, resource: &acp_v1::EmbeddedResource) -> AnyElement {
fn render_embedded_resource_label(&self, resource: &acp_v2::EmbeddedResource) -> AnyElement {
let uri = match &resource.resource {
acp_v1::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),
acp_v1::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),
acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),
acp_v2::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),
_ => "",
};
if uri.is_empty() {
@@ -10378,7 +10415,7 @@ impl ThreadView {
fn render_resource_link(
&self,
resource_link: &acp_v1::ResourceLink,
resource_link: &acp_v2::ResourceLink,
cx: &Context<Self>,
) -> AnyElement {
let uri: SharedString = resource_link.uri.clone().into();
+17 -7
View File
@@ -240,16 +240,26 @@ impl EntryViewState {
let can_rewind = thread.read(cx).supports_truncate(cx);
let has_client_id = message.client_id.is_some();
let is_subagent = thread.read(cx).parent_session_id().is_some();
let chunks = message.content.source_blocks().to_vec();
let source_blocks = message.content.source_blocks();
let source_is_representable = source_blocks
.iter()
.all(acp_thread::content::can_convert_to_v1);
let is_editable =
can_rewind && has_client_id && !is_subagent && source_is_representable;
if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) {
if !editor.focus_handle(cx).is_focused(window) {
// Only update if we are not editing.
// If we are, cancelling the edit will set the message to the newest content.
// Keep focused drafts unless newly unsupported content makes
// the message read-only and needs its fallback shown.
let refreshed_source = (!source_is_representable
|| !editor.focus_handle(cx).is_focused(window))
.then(|| source_blocks.to_vec());
editor.update(cx, |editor, cx| editor.set_read_only(!is_editable, cx));
if let Some(source_blocks) = refreshed_source {
editor.update(cx, |editor, cx| {
editor.set_message(chunks, window, cx);
editor.set_source_message(source_blocks, window, cx);
});
}
} else {
let source_blocks = source_blocks.to_vec();
let message_editor = cx.new(|cx| {
let mut editor = MessageEditor::new(
self.workspace.clone(),
@@ -265,10 +275,10 @@ impl EntryViewState {
window,
cx,
);
if !can_rewind || !has_client_id || is_subagent {
if !is_editable {
editor.set_read_only(true, cx);
}
editor.set_message(chunks, window, cx);
editor.set_source_message(source_blocks, window, cx);
editor
});
cx.subscribe(&message_editor, move |_, editor, event, cx| {
+139 -1
View File
@@ -1695,6 +1695,57 @@ impl MessageEditor {
self.insert_message_blocks(message, false, window, cx);
}
pub fn set_source_message(
&mut self,
source_blocks: Vec<agent_client_protocol::schema::v2::ContentBlock>,
window: &mut Window,
cx: &mut Context<Self>,
) {
use agent_client_protocol::schema::v2::ContentBlock;
if source_blocks
.iter()
.all(acp_thread::content::can_convert_to_v1)
{
match source_blocks
.into_iter()
.map(acp_thread::content::to_v1)
.collect::<Result<Vec<_>, _>>()
{
Ok(message) => self.set_message(message, window, cx),
Err(error) => {
log::error!("failed to display representable source message: {error}");
self.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"[Unsupported message content — this message cannot be edited or resent]",
))],
window,
cx,
);
}
}
return;
}
let mut visible = Vec::new();
for block in source_blocks {
if acp_thread::content::can_convert_to_v1(&block) {
match acp_thread::content::to_v1(block) {
Ok(block) => visible.push(block),
Err(error) => log::error!("failed to display source content: {error}"),
}
} else if let ContentBlock::Text(text) = block {
visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
text.text,
)));
}
}
visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"\n[Unsupported message content — this message cannot be edited or resent]",
)));
self.set_message(visible, window, cx);
}
pub fn append_message(
&mut self,
message: Vec<acp_v1::ContentBlock>,
@@ -2266,7 +2317,7 @@ mod tests {
use futures::{FutureExt as _, StreamExt as _};
use gpui::{
AppContext, ClipboardEntry, ClipboardItem, Entity, EventEmitter, ExternalPaths,
FocusHandle, Focusable, Task, TestAppContext, VisualTestContext,
FocusHandle, Focusable, Task, TestAppContext, VisualContext, VisualTestContext,
};
use language_model::LanguageModelRegistry;
use lsp::{CompletionContext, CompletionTriggerKind};
@@ -5579,6 +5630,93 @@ mod tests {
assert!(!message_editor.update(cx, |editor, cx| editor.is_empty(cx)));
}
#[gpui::test]
async fn test_source_message_known_text_remains_editable(cx: &mut TestAppContext) {
init_test(cx);
let (message_editor, cx) = setup_message_editor(cx).await;
message_editor.update_in(cx, |editor, window, cx| {
editor.set_source_message(
vec![agent_client_protocol::schema::v2::ContentBlock::Text(
agent_client_protocol::schema::v2::TextContent::new("original"),
)],
window,
cx,
);
});
let workspace = message_editor.read_with(cx, |editor, _| {
editor.workspace.upgrade().expect("message workspace")
});
workspace.update_in(cx, |workspace, window, cx| {
workspace.active_pane().update(cx, |pane, cx| {
pane.add_item(
Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
true,
true,
None,
window,
cx,
);
});
});
cx.focus(&message_editor);
cx.simulate_input("edited");
assert!(
message_editor
.update(cx, |editor, cx| editor.text(cx))
.contains("edited")
);
}
#[gpui::test]
async fn test_source_message_unknown_content_indicated_with_known_text(
cx: &mut TestAppContext,
) {
use agent_client_protocol::schema::v2 as acp_v2;
init_test(cx);
let (message_editor, cx) = setup_message_editor(cx).await;
message_editor.update_in(cx, |editor, window, cx| {
editor.set_read_only(true, cx);
editor.set_source_message(
vec![
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("visible text")),
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
)),
],
window,
cx,
);
assert!(editor.text(cx).contains("visible text"));
assert!(editor.text(cx).contains("Unsupported message content"));
});
}
#[gpui::test]
async fn test_source_message_unknown_annotation_indicated_with_text(cx: &mut TestAppContext) {
use agent_client_protocol::schema::v2 as acp_v2;
init_test(cx);
let (message_editor, cx) = setup_message_editor(cx).await;
message_editor.update_in(cx, |editor, window, cx| {
editor.set_read_only(true, cx);
editor.set_source_message(
vec![acp_v2::ContentBlock::Text(
acp_v2::TextContent::new("annotated text").annotations(
acp_v2::Annotations::new()
.audience(vec![acp_v2::Role::Other("_future".into())]),
),
)],
window,
cx,
);
assert!(editor.text(cx).contains("annotated text"));
assert!(editor.text(cx).contains("Unsupported message content"));
});
}
#[gpui::test]
async fn test_set_message_normalizes_crlf_before_mention(cx: &mut TestAppContext) {
init_test(cx);