acp_thread: Use v2 content for outbound prompts (#65165)

Carry SDK v2 content through outbound composition, drafts, queues, and
submissions. Shared prompt inputs use v2 requests; existing v1/native
adapters still own wire conversion. **This does not enable a v2 backend
or change protocol selection.**

- Preserve full source in drafts and submission records, including
unknown v2 payloads and metadata. Native draft storage reads valid
legacy JSON without a database version bump.
- Keep legacy turn-completion responses distinct from v2 acceptance
receipts. Receipt transports receive exact v2 content without a legacy
representability gate.
- Lower complete requests only at v1/native adapter entry. Borrowed,
transport-aware preflight rejects before turn cancellation, optimistic
history, queue removal/processing effects, or backend retry.
- Keep unsupported composer/queue source authoritative while rendering a
read-only projection. Prevent projection autosave/resend, including
queue blur and recovery/authentication restoration. An explicit
**Discard draft** action clears and unlocks a protected composer.

## Review guide

- [Shared transport and receipt
contracts](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/acp_thread/src/connection.rs#L203),
[request
lowering](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/acp_thread/src/content.rs#L4),
and [source
ownership](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/acp_thread/src/submission.rs#L65).
- [Core send/retry
preflight](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/acp_thread/src/acp_thread.rs#L6049);
actual
[v1](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent_servers/src/acp.rs#L1879)
and
[native](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent/src/agent.rs#L2835)
adapters.
- [Queued
dispatch](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent_ui/src/conversation_view/thread_view.rs#L2612),
[queue blur
preservation](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent_ui/src/conversation_view/thread_view.rs#L2539),
and [explicit draft
discard](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent_ui/src/conversation_view/thread_view.rs#L4926).

- [Native steering
preflight](https://github.com/zed-industries/zed/blob/cf591b00a001c412e6f5b20242da233877b19469/crates/agent_ui/src/conversation_view/thread_view.rs#L2595)
also gates the end-at-boundary flag; the existing test checks the actual
native flag for supported and unsupported source.

Release Notes:

- N/A
This commit is contained in:
Ben Brandt
2026-10-05 12:56:38 +00:00
committed by GitHub
parent cd5bdc41c4
commit dff535449c
19 changed files with 948 additions and 288 deletions
+145 -33
View File
@@ -3394,7 +3394,7 @@ pub struct AcpThread {
pending_terminal_exit: HashMap<acp_v1::TerminalId, acp_v1::TerminalExitStatus>,
had_error: bool,
/// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
/// The initial scroll position for the thread view, set during session registration.
ui_scroll_position: Option<gpui::ListOffset>,
/// A cursor over retained source, rather than a second text store, lets the UI
@@ -3747,13 +3747,13 @@ impl AcpThread {
self.entries().is_empty()
}
pub fn draft_prompt(&self) -> Option<&[acp_v1::ContentBlock]> {
pub fn draft_prompt(&self) -> Option<&[acp_v2::ContentBlock]> {
self.draft_prompt.as_deref()
}
pub fn set_draft_prompt(
&mut self,
prompt: Option<Vec<acp_v1::ContentBlock>>,
prompt: Option<Vec<acp_v2::ContentBlock>>,
cx: &mut Context<Self>,
) {
cx.emit(AcpThreadEvent::PromptUpdated);
@@ -3979,7 +3979,7 @@ impl AcpThread {
fn register_submission(
&mut self,
content: Arc<[acp_v1::ContentBlock]>,
content: Arc<[acp_v2::ContentBlock]>,
cx: &mut Context<Self>,
) -> SubmissionId {
let id = self.submissions.register(content);
@@ -6011,7 +6011,7 @@ impl AcpThread {
pub fn send(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
cx: &mut Context<Self>,
) -> Submission {
self.submit(message, true, cx)
@@ -6023,7 +6023,7 @@ impl AcpThread {
/// typed command isn't sent to the model as an ordinary user turn.
pub fn send_command(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
cx: &mut Context<Self>,
) -> Submission {
self.submit(message, false, cx)
@@ -6031,7 +6031,7 @@ impl AcpThread {
fn submit(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
push_user_message: bool,
cx: &mut Context<Self>,
) -> Submission {
@@ -6046,26 +6046,32 @@ impl AcpThread {
}
}
pub fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
if self.submissions.receipt_transport().is_some() {
Ok(())
} else {
self.connection.validate_prompt_content(content)
}
}
fn send_inner(
&mut self,
id: SubmissionId,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
push_user_message: bool,
cx: &mut Context<Self>,
) -> Submission {
let request =
acp_v2::PromptRequest::new(acp_v2::SessionId::new(self.session_id.0.clone()), message);
if let Err(error) = self.validate_prompt_content(&request.prompt) {
return self.track_submission(id, cx, async move |_, _| Err(error));
}
let language_registry = self.project.read(cx).languages().clone();
let path_style = self.project.read(cx).path_style(cx);
let mut block = MessageContent::default();
for chunk in &message {
let chunk = match content::from_v1(chunk.clone()) {
Ok(chunk) => chunk,
Err(error) => {
return self.track_submission(id, cx, async move |_, _| Err(error));
}
};
block.append_prompt(chunk, &language_registry, path_style, cx);
for chunk in &request.prompt {
block.append_prompt(chunk.clone(), &language_registry, path_style, cx);
}
let request = acp_v1::PromptRequest::new(self.session_id.clone(), message);
let git_store = self.project.read(cx).git_store().clone();
let client_user_message_ids = self.connection.client_user_message_ids(cx);
@@ -6119,7 +6125,13 @@ impl AcpThread {
}
pub fn can_retry(&self, cx: &App) -> bool {
!self.uses_reported_activity() && self.connection.retry(&self.session_id, cx).is_some()
!self.uses_reported_activity()
&& self.connection.retry(&self.session_id, cx).is_some()
&& self
.submissions
.latest_id()
.and_then(|id| self.submissions.get(id))
.is_none_or(|submission| self.validate_prompt_content(&submission.content).is_ok())
}
pub fn retry(&mut self, cx: &mut Context<Self>) -> Submission {
@@ -6129,12 +6141,15 @@ impl AcpThread {
.and_then(|id| self.submissions.get(id))
.map(|submission| submission.content.clone())
.unwrap_or_default();
let id = self.register_submission(content, cx);
let id = self.register_submission(content.clone(), cx);
if self.uses_reported_activity() {
return self.track_submission(id, cx, async move |_, _| {
Err(anyhow!("Receipt-driven retry is not supported"))
});
}
if let Err(error) = self.validate_prompt_content(&content) {
return self.track_submission(id, cx, async move |_, _| Err(error));
}
self.run_turn(id, cx, async move |this, cx| {
this.update(cx, |this, cx| {
this.connection
@@ -10381,6 +10396,88 @@ mod tests {
}
}
#[gpui::test]
async fn test_unsupported_legacy_prompt_preserves_running_turn(cx: &mut TestAppContext) {
init_test(cx);
let project = Project::test(FakeFs::new(cx.executor()), [], cx).await;
let connection = Rc::new(StubAgentConnection::new().with_retry());
let thread = cx
.update(|cx| {
connection.clone().new_session(
project,
PathList::new(&[Path::new(path!("/test"))]),
cx,
)
})
.await
.expect("legacy session");
let complete = connection.defer_next_prompt_response();
let running = thread.update(cx, |thread, cx| {
thread.send(vec!["keep running".into()], cx)
});
cx.run_until_parked();
let before = thread.read_with(cx, |thread, _| {
assert_eq!(thread.status(), ThreadStatus::Generating);
(
thread.turn_id,
thread.entries.len(),
thread.activity_generation(),
)
});
assert!(thread.read_with(cx, |thread, cx| thread.can_retry(cx)));
let source = vec![acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
std::collections::BTreeMap::from([(
"payload".into(),
json!({"private": [null, true]}),
)]),
))];
let rejected = thread.update(cx, |thread, cx| thread.send(source.clone(), cx));
let rejected_id = rejected.id;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(thread.status(), ThreadStatus::Generating);
assert_eq!(
(
thread.turn_id,
thread.entries.len(),
thread.activity_generation()
),
before
);
let record = thread.submission(rejected_id).expect("rejected submission");
assert_eq!(record.content.as_ref(), source.as_slice());
assert!(matches!(record.state, SubmissionState::Failed(_)));
});
assert!(rejected.await.is_err());
assert!(!thread.read_with(cx, |thread, cx| thread.can_retry(cx)));
let retry = thread.update(cx, |thread, cx| thread.retry(cx));
let retry_id = retry.id;
cx.run_until_parked();
thread.read_with(cx, |thread, _| {
assert_eq!(
(
thread.turn_id,
thread.entries.len(),
thread.activity_generation()
),
before
);
let record = thread.submission(retry_id).expect("rejected retry");
assert_eq!(record.content.as_ref(), source.as_slice());
assert!(matches!(record.state, SubmissionState::Failed(_)));
});
assert!(retry.await.is_err());
complete
.send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("the original turn must still be pending");
assert!(matches!(
running.await.expect("original turn completes"),
Some(SubmissionResponse::LegacyCompleted(_))
));
}
async fn new_receipt_test_thread(
cx: &mut TestAppContext,
) -> (Entity<AcpThread>, Rc<StubAgentConnection>) {
@@ -10430,7 +10527,18 @@ mod tests {
});
let first_sender = connection.defer_next_receipt_response();
let first = thread.update(cx, |thread, cx| thread.send(vec!["outgoing".into()], cx));
let outgoing = vec![
"outgoing".into(),
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
std::collections::BTreeMap::from([
("payload".into(), json!({"nested": [null, true]})),
("_meta".into(), json!({"origin": "outgoing"})),
]),
)),
];
let first = thread.update(cx, |thread, cx| thread.send(outgoing.clone(), cx));
assert_eq!(connection.take_receipt_prompt().as_ref(), Some(&outgoing));
let first_id = first.id;
thread.read_with(cx, |thread, _| {
assert_eq!(thread.latest_submission_id(), Some(first_id));
@@ -10440,7 +10548,7 @@ mod tests {
));
assert_eq!(
thread.submission(first_id).expect("first").content.as_ref(),
&["outgoing".into()]
outgoing.as_slice()
);
assert!(thread.entries().is_empty());
assert!(thread.has_unsettled_submissions());
@@ -11945,7 +12053,7 @@ mod tests {
move |request, thread, mut cx| {
let received_prompt = received_prompt.clone();
async move {
if let Some(acp_v1::ContentBlock::Text(text)) = request.prompt.first() {
if let Some(acp_v2::ContentBlock::Text(text)) = request.prompt.first() {
*received_prompt.borrow_mut() = Some(text.text.clone());
}
// Simulate a native command producing its own thread entry
@@ -12017,7 +12125,9 @@ mod tests {
.without_truncate_support()
.on_user_message(|request, thread, mut cx| {
async move {
let prompt = request.prompt.first().cloned().unwrap_or_else(|| "".into());
let prompt = content::to_v1(
request.prompt.first().cloned().unwrap_or_else(|| "".into()),
)?;
thread.update(&mut cx, |thread, cx| {
thread
@@ -14998,7 +15108,7 @@ mod tests {
fs.write(Path::new(&filename), b"").await?;
}
let acp_v1::ContentBlock::Text(content) = &request.prompt[0] else {
let acp_v2::ContentBlock::Text(content) = &request.prompt[0] else {
panic!("expected text content block");
};
thread.update(&mut cx, |thread, cx| {
@@ -15439,7 +15549,7 @@ mod tests {
return Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal));
}
let acp_v1::ContentBlock::Text(content) = &request.prompt[0] else {
let acp_v2::ContentBlock::Text(content) = &request.prompt[0] else {
panic!("expected text content block");
};
thread.update(&mut cx, |thread, cx| {
@@ -16149,9 +16259,10 @@ mod tests {
fn request_test_session_elicitation(
thread: WeakEntity<AcpThread>,
session_id: acp_v1::SessionId,
session_id: acp_v2::SessionId,
cx: &mut AsyncApp,
) -> Result<Task<acp_v1::CreateElicitationResponse>> {
let session_id = acp_v1::SessionId::new(session_id.0);
thread.update(cx, |thread, cx| {
thread
.request_elicitation(
@@ -16955,7 +17066,7 @@ mod tests {
on_user_message: Option<
Rc<
dyn Fn(
acp_v1::PromptRequest,
acp_v2::PromptRequest,
WeakEntity<AcpThread>,
AsyncApp,
)
@@ -16990,7 +17101,7 @@ mod tests {
fn on_user_message(
mut self,
handler: impl Fn(
acp_v1::PromptRequest,
acp_v2::PromptRequest,
WeakEntity<AcpThread>,
AsyncApp,
) -> LocalBoxFuture<'static, Result<acp_v1::PromptResponse>>
@@ -17064,11 +17175,12 @@ mod tests {
fn prompt(
&self,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
let sessions = self.sessions.lock();
let thread = sessions.get(&params.session_id).unwrap();
let session_id = acp_v1::SessionId::new(params.session_id.0.clone());
let thread = sessions.get(&session_id).unwrap();
if let Some(handler) = &self.on_user_message {
let handler = handler.clone();
let thread = thread.clone();
@@ -17151,7 +17263,7 @@ mod tests {
fn prompt(
&self,
_client_user_message_id: ClientUserMessageId,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>> {
self.connection.prompt(params, cx)
@@ -17688,7 +17800,7 @@ mod tests {
move |params, _thread, _cx| {
let first_complete_rx = first_complete_rx.borrow_mut().take();
let is_first = params.prompt.iter().any(
|c| matches!(c, acp_v1::ContentBlock::Text(t) if t.text.contains("first")),
|c| matches!(c, acp_v2::ContentBlock::Text(t) if t.text.contains("first")),
);
let second_complete_rx = if is_first {
None
@@ -17851,7 +17963,7 @@ mod tests {
move |params, thread, mut cx| {
let first_complete_rx = first_complete_rx.borrow_mut().take();
let is_first = params.prompt.iter().any(|content| {
matches!(content, acp_v1::ContentBlock::Text(text) if text.text.contains("first"))
matches!(content, acp_v2::ContentBlock::Text(text) if text.text.contains("first"))
});
let compaction_id = compaction_id.clone();
+55 -6
View File
@@ -200,9 +200,17 @@ pub trait AgentConnection {
None
}
/// Preflight without starting transport work so rejection cannot interrupt an
/// existing turn. Adapters must also validate when called directly.
fn validate_prompt_content(&self, _content: &[acp_v2::ContentBlock]) -> Result<()> {
Ok(())
}
/// This completion-based path retains a legacy response; receipt transports
/// acknowledge acceptance separately through `receipt_submissions`.
fn prompt(
&self,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>>;
@@ -295,7 +303,7 @@ pub trait AgentSessionClientUserMessageIds {
fn prompt(
&self,
client_user_message_id: ClientUserMessageId,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>>;
}
@@ -305,7 +313,7 @@ pub trait AgentSessionClientUserMessageIds {
pub trait ReceiptSessionSubmissions {
fn prompt(
&self,
content: Vec<acp_v1::ContentBlock>,
content: Vec<acp_v2::ContentBlock>,
cx: &mut App,
) -> Task<Result<acp_v2::PromptResponse>>;
}
@@ -808,8 +816,10 @@ mod test_support {
next_prompt_response: Arc<Mutex<Option<oneshot::Receiver<Result<acp_v1::PromptResponse>>>>>,
next_receipt_response:
Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,
next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
supports_receipt_submissions: bool,
supports_retry: bool,
supports_load_session: bool,
supports_session_additional_directories: bool,
supports_set_title: bool,
@@ -834,10 +844,12 @@ mod test_support {
next_prompt_updates: Default::default(),
next_prompt_response: Default::default(),
next_receipt_response: Default::default(),
receipt_prompt: Default::default(),
next_truncate: Default::default(),
permission_requests: HashMap::default(),
sessions: Arc::default(),
supports_receipt_submissions: false,
supports_retry: false,
supports_load_session: false,
supports_session_additional_directories: false,
supports_set_title: true,
@@ -871,6 +883,10 @@ mod test_support {
sender
}
pub fn take_receipt_prompt(&self) -> Option<Vec<acp_v2::ContentBlock>> {
self.receipt_prompt.lock().take()
}
pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {
let (sender, receiver) = oneshot::channel();
assert!(self.next_truncate.lock().replace(receiver).is_none());
@@ -895,6 +911,11 @@ mod test_support {
self
}
pub fn with_retry(mut self) -> Self {
self.supports_retry = true;
self
}
pub fn with_supports_session_additional_directories(
mut self,
supports_session_additional_directories: bool,
@@ -1053,11 +1074,19 @@ mod test_support {
unimplemented!()
}
fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
crate::content::validate_prompt_content_for_v1(content)
}
fn prompt(
&self,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
let params = match crate::content::prompt_to_v1(params) {
Ok(params) => params,
Err(error) => return Task::ready(Err(error)),
};
let mut sessions = self.sessions.lock();
let Session {
thread,
@@ -1132,10 +1161,20 @@ mod test_support {
session_id: session_id.clone(),
sessions: self.sessions.clone(),
next_receipt_response: self.next_receipt_response.clone(),
receipt_prompt: self.receipt_prompt.clone(),
}) as Rc<dyn ReceiptSessionSubmissions>
})
}
fn retry(
&self,
_session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionRetry>> {
self.supports_retry
.then(|| Rc::new(StubAgentSessionRetry) as Rc<dyn AgentSessionRetry>)
}
fn cancel(&self, session_id: &acp_v1::SessionId, _cx: &mut App) {
if let Some(end_turn_tx) = self
.sessions
@@ -1190,7 +1229,7 @@ mod test_support {
fn prompt(
&self,
_client_user_message_id: ClientUserMessageId,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>> {
self.connection.prompt(params, cx)
@@ -1202,17 +1241,19 @@ mod test_support {
sessions: Arc<Mutex<HashMap<acp_v1::SessionId, Session>>>,
next_receipt_response:
Arc<Mutex<Option<oneshot::Receiver<Result<acp_v2::PromptResponse>>>>>,
receipt_prompt: Arc<Mutex<Option<Vec<acp_v2::ContentBlock>>>>,
}
impl ReceiptSessionSubmissions for StubReceiptSessionSubmissions {
fn prompt(
&self,
_content: Vec<acp_v1::ContentBlock>,
content: Vec<acp_v2::ContentBlock>,
cx: &mut App,
) -> Task<Result<acp_v2::PromptResponse>> {
if !self.sessions.lock().contains_key(&self.session_id) {
return Task::ready(Err(anyhow::Error::msg("Unknown receipt session")));
}
*self.receipt_prompt.lock() = Some(content);
match self.next_receipt_response.lock().take() {
Some(receiver) => cx.spawn(async move |_| Ok(receiver.await??)),
None => Task::ready(Err(anyhow::Error::msg("No deferred receipt response"))),
@@ -1220,6 +1261,14 @@ mod test_support {
}
}
struct StubAgentSessionRetry;
impl AgentSessionRetry for StubAgentSessionRetry {
fn run(&self, _cx: &mut App) -> Task<Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
}
struct StubAgentSessionEditor {
next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
}
+60
View File
@@ -1,6 +1,25 @@
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use anyhow::{Result, bail};
pub fn validate_prompt_content_for_v1(content: &[acp_v2::ContentBlock]) -> Result<()> {
if !content.iter().all(can_convert_to_v1) {
bail!("This prompt contains content not supported by ACP v1");
}
Ok(())
}
pub fn prompt_to_v1(request: acp_v2::PromptRequest) -> Result<acp_v1::PromptRequest> {
let prompt = request
.prompt
.into_iter()
.map(to_v1)
.collect::<Result<Vec<_>>>()?;
Ok(
acp_v1::PromptRequest::new(acp_v1::SessionId::new(request.session_id.0), prompt)
.meta(request.meta),
)
}
pub fn from_v1(block: acp_v1::ContentBlock) -> Result<acp_v2::ContentBlock> {
Ok(match block {
acp_v1::ContentBlock::Text(content) => acp_v2::ContentBlock::Text(
@@ -247,6 +266,47 @@ mod tests {
assert!(to_v1(block).is_err());
}
#[test]
fn legacy_prompt_conversion_preserves_envelope_and_rejects_unsupported_content() -> Result<()> {
let request = acp_v2::PromptRequest::new(
"opaque-session",
vec![acp_v2::ContentBlock::Text(
acp_v2::TextContent::new("prompt").meta(acp_v2::Meta::from_iter([(
"block".into(),
json!({"value": 1}),
)])),
)],
)
.meta(acp_v2::Meta::from_iter([(
"request".into(),
json!([null, true]),
)]));
validate_prompt_content_for_v1(&request.prompt)?;
assert_eq!(
serde_json::to_value(prompt_to_v1(request)?)?,
json!({
"sessionId": "opaque-session",
"prompt": [{"type": "text", "text": "prompt", "_meta": {"block": {"value": 1}}}],
"_meta": {"request": [null, true]}
})
);
let request = acp_v2::PromptRequest::new(
"opaque-session",
vec![
"visible text".into(),
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
BTreeMap::from([("payload".into(), json!("private-payload"))]),
)),
],
);
assert!(validate_prompt_content_for_v1(&request.prompt).is_err());
let error = prompt_to_v1(request).expect_err("the entire prompt must be representable");
assert!(!error.to_string().contains("private-payload"));
Ok(())
}
#[test]
fn preserves_all_v1_content_variants_and_metadata() {
round_trip(acp_v1::ContentBlock::Text(
+2 -2
View File
@@ -63,7 +63,7 @@ pub enum SubmissionState {
}
pub struct SubmissionRecord {
pub content: Arc<[acp_v1::ContentBlock]>,
pub content: Arc<[acp_v2::ContentBlock]>,
pub state: SubmissionState,
task: Option<Task<()>>,
}
@@ -134,7 +134,7 @@ impl SessionSubmissions {
})
}
pub(crate) fn register(&mut self, content: Arc<[acp_v1::ContentBlock]>) -> SubmissionId {
pub(crate) fn register(&mut self, content: Arc<[acp_v2::ContentBlock]>) -> SubmissionId {
self.next_id += 1;
let id = SubmissionId(self.next_id);
self.latest_id = Some(id);
+28 -19
View File
@@ -34,6 +34,7 @@ use acp_thread::{
AgentSessionListRequest, AgentSessionListResponse, ClientUserMessageId, TokenUsageRatio,
};
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_skills::{
AGENTS_DIR_NAME, MAX_SKILL_DESCRIPTIONS_SIZE, MAX_SKILL_FILE_SIZE, ProjectSkillGroup,
SKILL_FILE_NAME, Skill, SkillIndex, SkillLoadError, SkillLoadWarning, SkillScopeId,
@@ -240,7 +241,7 @@ struct Session {
}
impl Session {
fn draft_prompt(&self, cx: &App) -> Option<Vec<acp_v1::ContentBlock>> {
fn draft_prompt(&self, cx: &App) -> Option<Vec<acp_v2::ContentBlock>> {
match self.acp_thread.upgrade() {
Some(acp_thread) => acp_thread.read(cx).draft_prompt().map(Vec::from),
None => self.thread.read(cx).draft_prompt().map(Vec::from),
@@ -1774,7 +1775,7 @@ impl NativeAgent {
&mut self,
session_id: &acp_v1::SessionId,
acp_thread_id: EntityId,
draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
cx: &mut Context<Self>,
) {
let Some(session) = self.sessions.get(session_id) else {
@@ -1810,7 +1811,7 @@ impl NativeAgent {
fn enqueue_save(
&mut self,
id: &acp_v1::SessionId,
draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
cx: &mut Context<Self>,
) {
let Some(session) = self.sessions.get(id) else {
@@ -1873,7 +1874,7 @@ impl NativeAgent {
fn thread_save_payload(
&self,
session: &Session,
draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
cx: &mut App,
) -> Option<(acp_v1::SessionId, PathList, Task<DbThread>)> {
if session.thread.read(cx).is_empty() {
@@ -2831,9 +2832,13 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
Some(prompt)
}
fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
acp_thread::content::validate_prompt_content_for_v1(content)
}
fn prompt(
&self,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>> {
acp_thread::AgentSessionClientUserMessageIds::prompt(
@@ -2918,9 +2923,13 @@ impl acp_thread::AgentSessionClientUserMessageIds for NativeAgentConnection {
fn prompt(
&self,
client_user_message_id: acp_thread::ClientUserMessageId,
params: acp_v1::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp_v1::PromptResponse>> {
let params = match acp_thread::content::prompt_to_v1(params) {
Ok(params) => params,
Err(error) => return Task::ready(Err(error)),
};
let session_id = params.session_id.clone();
log::info!("Received prompt request for session: {}", session_id);
log::debug!("Prompt blocks count: {}", params.prompt.len());
@@ -4271,7 +4280,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
compact_message_id,
acp_v1::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),
acp_v2::PromptRequest::new(session_id.0.clone(), vec!["/compact".into()]),
cx,
)
});
@@ -4478,7 +4487,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
acp_v1::PromptRequest::new(session_id.clone(), vec!["old user".into()]),
acp_v2::PromptRequest::new(session_id.0.clone(), vec!["old user".into()]),
cx,
)
});
@@ -4507,7 +4516,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
acp_v1::PromptRequest::new(session_id, vec!["new user".into()]),
acp_v2::PromptRequest::new(session_id.0, vec!["new user".into()]),
cx,
)
});
@@ -4750,7 +4759,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
acp_v1::PromptRequest::new(session_id.clone(), vec!["use a tool".into()]),
acp_v2::PromptRequest::new(session_id.0.clone(), vec!["use a tool".into()]),
cx,
)
});
@@ -4881,7 +4890,7 @@ mod internal_tests {
});
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.set_draft_prompt(
Some(vec![acp_v1::ContentBlock::from("draft in progress")]),
Some(vec![acp_v2::ContentBlock::from("draft in progress")]),
cx,
);
});
@@ -4918,7 +4927,7 @@ mod internal_tests {
);
assert_eq!(
restored.draft_prompt,
Some(vec![acp_v1::ContentBlock::from("draft in progress")]),
Some(vec![acp_v2::ContentBlock::from("draft in progress")]),
"the current draft prompt should be captured by the quit flush"
);
assert!(
@@ -7265,7 +7274,7 @@ mod internal_tests {
thread.send(
vec![
"What does ".into(),
acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"b.md",
MentionUri::File {
abs_path: path!("/a/b.md").into(),
@@ -7329,9 +7338,9 @@ mod internal_tests {
// AFTER run_until_parked, so the only save that captures these
// changes is the one performed by close_session itself.
let draft_blocks = vec![
acp_v1::ContentBlock::Text(acp_v1::TextContent::new("Check out ")),
acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new("b.md", uri.to_string())),
acp_v1::ContentBlock::Text(acp_v1::TextContent::new(" please")),
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("Check out ")),
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new("b.md", uri.to_string())),
acp_v2::ContentBlock::Text(acp_v2::TextContent::new(" please")),
];
acp_thread.update(cx, |thread, cx| {
thread.set_draft_prompt(Some(draft_blocks.clone()), cx);
@@ -7456,7 +7465,7 @@ mod internal_tests {
// This means no observe-triggered save has run for this change.
// The only way this data gets persisted is if close_session
// itself performs the save.
let draft_blocks = vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
let draft_blocks = vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"unsaved draft",
))];
acp_thread.update(cx, |thread, cx| {
@@ -7618,7 +7627,7 @@ mod internal_tests {
let database = cx.update(|cx| ThreadsDatabase::connect(cx)).await.unwrap();
let [first_draft, second_draft, third_draft] = ["draft one", "draft two", "draft three"]
.map(|text| vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(text))]);
.map(|text| vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(text))]);
let (first_gate_tx, first_gate_rx) = oneshot::channel();
database.set_write_gate(first_gate_rx);
@@ -8007,7 +8016,7 @@ mod internal_tests {
agent: &Entity<NativeAgent>,
acp_thread: &Entity<AcpThread>,
thread: &Entity<Thread>,
draft: Vec<acp_v1::ContentBlock>,
draft: Vec<acp_v2::ContentBlock>,
cx: &mut TestAppContext,
) {
acp_thread.update(cx, |acp_thread, cx| {
+54 -1
View File
@@ -1,6 +1,7 @@
use crate::{AgentMessage, AgentMessageContent, UserMessage, UserMessageContent};
use acp_thread::ClientUserMessageId;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_settings::AgentProfileId;
use anyhow::Result;
use chrono::{DateTime, Utc};
@@ -76,7 +77,7 @@ pub struct DbThread {
#[serde(default)]
pub thinking_effort: Option<String>,
#[serde(default)]
pub draft_prompt: Option<Vec<acp::ContentBlock>>,
pub draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
#[serde(default)]
pub ui_scroll_position: Option<SerializedScrollPosition>,
#[serde(default)]
@@ -929,6 +930,58 @@ mod tests {
);
}
#[gpui::test]
async fn test_draft_prompt_preserves_legacy_and_v2_content(cx: &mut TestAppContext) {
let legacy_draft = serde_json::to_value(vec![
acp::ContentBlock::Text(acp::TextContent::new("legacy draft")),
acp::ContentBlock::ResourceLink(acp::ResourceLink::new("file", "file:///a.md")),
])
.expect("serialize v1 draft");
let mut thread: DbThread = serde_json::from_value(serde_json::json!({
"title": "Draft Thread",
"messages": [],
"updated_at": "2024-01-01T00:00:00Z",
"draft_prompt": legacy_draft,
}))
.expect("decode legacy thread with v2 draft blocks");
assert_eq!(
serde_json::to_value(&thread.draft_prompt).expect("serialize decoded draft"),
legacy_draft
);
let extension = serde_json::json!({
"type": "_draft_card",
"payload": {"items": [1, {"enabled": true}], "optional": null},
"_meta": {"source": "draft", "nested": {"version": 2}},
});
let extension_block: acp_v2::ContentBlock =
serde_json::from_value(extension.clone()).expect("decode v2-only draft block");
assert!(matches!(extension_block, acp_v2::ContentBlock::Other(_)));
thread
.draft_prompt
.as_mut()
.expect("legacy draft exists")
.push(extension_block);
let mut expected = legacy_draft.as_array().expect("draft is an array").clone();
expected.push(extension);
let database = ThreadsDatabase::new(cx.executor()).expect("create database");
let thread_id = session_id("draft-thread");
database
.save_thread(thread_id.clone(), thread, PathList::default())
.await
.expect("save mixed-version draft");
let restored = database
.load_thread(thread_id)
.await
.expect("load draft")
.expect("saved thread exists");
assert_eq!(
serde_json::to_value(restored.draft_prompt).expect("serialize restored draft"),
serde_json::Value::Array(expected)
);
}
#[test]
fn test_sandboxed_terminal_temp_dir_defaults_to_none() {
let json = r#"{
+2 -1
View File
@@ -4,6 +4,7 @@ use acp_thread::{
PermissionOptions, ThreadStatus,
};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_settings::{AgentProfileId, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT};
use anyhow::Result;
use client::{Client, RefreshLlmTokenListener, UserStore};
@@ -4500,7 +4501,7 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
acp_thread::AgentSessionClientUserMessageIds::prompt(
&connection,
acp_thread::ClientUserMessageId::new(),
acp::PromptRequest::new(session_id.clone(), vec!["ghi".into()]),
acp_v2::PromptRequest::new(session_id.0.clone(), vec!["ghi".into()]),
cx,
)
})
+4 -3
View File
@@ -17,6 +17,7 @@ use crate::sandboxing::{
sandboxing_enabled_for_project,
};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_settings::{
AgentProfileId, AgentProfileSettings, AgentSettings, AutoCompactThreshold, COMPACTION_PROMPT,
SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, builtin_profiles,
@@ -1318,7 +1319,7 @@ pub struct Thread {
/// If this is a subagent thread, contains context about the parent
subagent_context: Option<SubagentContext>,
/// The user's unsent prompt text, persisted so it can be restored when reloading the thread.
draft_prompt: Option<Vec<acp::ContentBlock>>,
draft_prompt: Option<Vec<acp_v2::ContentBlock>>,
ui_scroll_position: Option<gpui::ListOffset>,
/// Weak references to running subagent threads for cancellation propagation
running_subagents: Vec<WeakEntity<Thread>>,
@@ -1990,11 +1991,11 @@ impl Thread {
self.messages.is_empty() && self.title.is_none()
}
pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
pub fn draft_prompt(&self) -> Option<&[acp_v2::ContentBlock]> {
self.draft_prompt.as_deref()
}
pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp::ContentBlock>>) {
pub fn set_draft_prompt(&mut self, prompt: Option<Vec<acp_v2::ContentBlock>>) {
self.draft_prompt = prompt;
}
+14 -2
View File
@@ -1876,11 +1876,19 @@ impl AgentConnection for AcpConnection {
})
}
fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
acp_thread::content::validate_prompt_content_for_v1(content)
}
fn prompt(
&self,
params: acp::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
let params = match acp_thread::content::prompt_to_v1(params) {
Ok(params) => params,
Err(error) => return Task::ready(Err(error)),
};
let conn = self.connection.clone();
let sessions = self.sessions.clone();
let session_id = params.session_id.clone();
@@ -2255,9 +2263,13 @@ pub mod test_support {
self.inner.client_user_message_ids(cx)
}
fn validate_prompt_content(&self, content: &[acp_v2::ContentBlock]) -> Result<()> {
self.inner.validate_prompt_content(content)
}
fn prompt(
&self,
params: acp::PromptRequest,
params: acp_v2::PromptRequest,
cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
self.inner.prompt(params, cx)
+4 -2
View File
@@ -1,6 +1,6 @@
use crate::{AgentServer, AgentServerDelegate};
use acp_thread::{AcpThread, AgentThreadEntry, ToolCallStatus};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::{v1 as acp, v2 as acp_v2};
use client::RefreshLlmTokenListener;
use futures::{FutureExt, StreamExt, channel::mpsc, select};
use gpui::AppContext;
@@ -72,7 +72,9 @@ where
thread.send(
vec![
"Read the file ".into(),
acp::ContentBlock::ResourceLink(acp::ResourceLink::new("foo.rs", "foo.rs")),
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"foo.rs", "foo.rs",
)),
" and tell me what the content of the println! is".into(),
],
cx,
+59 -41
View File
@@ -12,7 +12,7 @@ use std::{
use acp_thread::{AcpThread, AcpThreadEvent, MentionUri, line_range_suffix};
use agent::{ContextServerRegistry, SharedThread, ThreadStore};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::{v1 as acp, v2 as acp_v2};
use agent_servers::AgentServer;
use agent_settings::UserAgentsMd;
use collections::HashSet;
@@ -539,14 +539,14 @@ pub fn init(cx: &mut App) {
let diff_uri = mention_uri.to_uri().to_string();
let content_blocks = vec![
acp::ContentBlock::Text(acp::TextContent::new(
acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"Please review this branch diff carefully. Point out any issues, \
potential bugs, or improvement opportunities you find.\n\n"
.to_string(),
)),
acp::ContentBlock::Resource(acp::EmbeddedResource::new(
acp::EmbeddedResourceResource::TextResourceContents(
acp::TextResourceContents::new(
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
acp_v2::EmbeddedResourceResource::TextResourceContents(
acp_v2::TextResourceContents::new(
action.diff_text.to_string(),
diff_uri,
),
@@ -779,19 +779,19 @@ fn mention_path_for_terminal(
}
}
fn conflict_resource_block(conflict: &ConflictContent) -> acp::ContentBlock {
fn conflict_resource_block(conflict: &ConflictContent) -> acp_v2::ContentBlock {
let mention_uri = MentionUri::MergeConflict {
file_path: conflict.file_path.clone(),
};
acp::ContentBlock::Resource(acp::EmbeddedResource::new(
acp::EmbeddedResourceResource::TextResourceContents(acp::TextResourceContents::new(
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
acp_v2::EmbeddedResourceResource::TextResourceContents(acp_v2::TextResourceContents::new(
conflict.conflict_text.clone(),
mention_uri.to_uri().to_string(),
)),
))
}
fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::ContentBlock> {
fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp_v2::ContentBlock> {
if conflicts.is_empty() {
return Vec::new();
}
@@ -801,18 +801,17 @@ fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::C
if conflicts.len() == 1 {
let conflict = &conflicts[0];
blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
blocks.push(acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"Please resolve the following merge conflict in ",
)));
let mention = MentionUri::File {
abs_path: PathBuf::from(conflict.file_path.clone()),
};
blocks.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
mention.name(),
mention.to_uri(),
)));
blocks.push(acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new(mention.name(), mention.to_uri()),
));
blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
blocks.push(acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
indoc::formatdoc!(
"\nThe conflict is between branch `{ours}` (ours) and `{theirs}` (theirs).
@@ -830,7 +829,7 @@ fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::C
let unique_files: HashSet<&str> = conflicts.iter().map(|c| c.file_path.as_str()).collect();
let ours = &conflicts[0].ours_branch_name;
let theirs = &conflicts[0].theirs_branch_name;
blocks.push(acp::ContentBlock::Text(acp::TextContent::new(
blocks.push(acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
indoc::formatdoc!(
"Please resolve all {n} merge conflicts below.
@@ -855,7 +854,7 @@ fn build_conflict_resolution_prompt(conflicts: &[ConflictContent]) -> Vec<acp::C
fn build_conflicted_files_resolution_prompt(
conflicted_file_paths: &[String],
) -> Vec<acp::ContentBlock> {
) -> Vec<acp_v2::ContentBlock> {
if conflicted_file_paths.is_empty() {
return Vec::new();
}
@@ -872,16 +871,17 @@ fn build_conflicted_files_resolution_prompt(
",
);
let mut content = vec![acp::ContentBlock::Text(acp::TextContent::new(instruction))];
let mut content = vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
instruction,
))];
for path in conflicted_file_paths {
let mention = MentionUri::File {
abs_path: PathBuf::from(path),
};
content.push(acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
mention.name(),
mention.to_uri(),
)));
content.push(acp::ContentBlock::Text(acp::TextContent::new("\n")));
content.push(acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new(mention.name(), mention.to_uri()),
));
content.push(acp_v2::ContentBlock::Text(acp_v2::TextContent::new("\n")));
}
content
}
@@ -3443,7 +3443,7 @@ impl AgentPanel {
&self,
id: ThreadId,
cx: &App,
) -> Option<Vec<acp::ContentBlock>> {
) -> Option<Vec<acp_v2::ContentBlock>> {
let cv = self
.retained_threads
.get(&id)
@@ -3462,6 +3462,22 @@ impl AgentPanel {
})?;
let thread_view = cv.read(cx).root_thread_view()?;
let thread_view = thread_view.read(cx);
if thread_view
.message_editor
.read(cx)
.editor()
.read(cx)
.read_only(cx)
{
return Some(
thread_view
.thread
.read(cx)
.draft_prompt()
.map(|blocks| blocks.to_vec())
.unwrap_or_default(),
);
}
Some(
thread_view
.message_editor
@@ -4856,7 +4872,7 @@ impl agent::SiblingThreadHost for AgentPanelSiblingHost {
};
let initial_content = AgentInitialContent::ContentBlock {
blocks: vec![acp::ContentBlock::Text(acp::TextContent::new(
blocks: vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
request.prompt.clone(),
))],
auto_submit: true,
@@ -7203,10 +7219,11 @@ mod tests {
fn prompt(
&self,
params: acp::PromptRequest,
params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
if !self.sessions.lock().contains(&params.session_id) {
let session_id = acp::SessionId::new(params.session_id.0);
if !self.sessions.lock().contains(&session_id) {
return Task::ready(Err(anyhow!("Session not found")));
}
@@ -8298,19 +8315,19 @@ mod tests {
}
/// Extracts the text from a Text content block, panicking if it's not Text.
fn expect_text_block(block: &acp::ContentBlock) -> &str {
fn expect_text_block(block: &acp_v2::ContentBlock) -> &str {
match block {
acp::ContentBlock::Text(t) => t.text.as_str(),
acp_v2::ContentBlock::Text(t) => t.text.as_str(),
other => panic!("expected Text block, got {:?}", other),
}
}
/// Extracts the (text_content, uri) from a Resource content block, panicking
/// if it's not a TextResourceContents resource.
fn expect_resource_block(block: &acp::ContentBlock) -> (&str, &str) {
fn expect_resource_block(block: &acp_v2::ContentBlock) -> (&str, &str) {
match block {
acp::ContentBlock::Resource(r) => match &r.resource {
acp::EmbeddedResourceResource::TextResourceContents(t) => {
acp_v2::ContentBlock::Resource(r) => match &r.resource {
acp_v2::EmbeddedResourceResource::TextResourceContents(t) => {
(t.text.as_str(), t.uri.as_str())
}
other => panic!("expected TextResourceContents, got {:?}", other),
@@ -8370,7 +8387,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.set_draft_prompt(
Some(vec![acp::ContentBlock::Text(acp::TextContent::new(
Some(vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"stale prompt",
))]),
cx,
@@ -8389,7 +8406,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.set_draft_prompt(
Some(vec![acp::ContentBlock::Text(acp::TextContent::new(
Some(vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"stale prompt after clear",
))]),
cx,
@@ -8522,7 +8539,7 @@ mod tests {
);
match &blocks[1] {
acp::ContentBlock::ResourceLink(link) => {
acp_v2::ContentBlock::ResourceLink(link) => {
assert!(
link.uri.contains("file://"),
"resource link URI should use file scheme"
@@ -8688,7 +8705,7 @@ mod tests {
let newline_index = link_index + 1;
match &blocks[link_index] {
acp::ContentBlock::ResourceLink(link) => {
acp_v2::ContentBlock::ResourceLink(link) => {
assert!(
link.uri.contains("file://"),
"resource link URI should use file scheme"
@@ -9531,8 +9548,8 @@ mod tests {
let selections = contents
.iter()
.filter_map(|block| match block {
acp::ContentBlock::Resource(resource) => match &resource.resource {
acp::EmbeddedResourceResource::TextResourceContents(content) => {
acp_v2::ContentBlock::Resource(resource) => match &resource.resource {
acp_v2::EmbeddedResourceResource::TextResourceContents(content) => {
Some(content.text.as_str())
}
_ => None,
@@ -14062,11 +14079,12 @@ mod tests {
fn prompt(
&self,
params: acp::PromptRequest,
params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<Result<acp::PromptResponse>> {
if !self.sessions.lock().contains(&params.session_id) {
self.missing_prompt_sessions.lock().push(params.session_id);
let session_id = acp::SessionId::new(params.session_id.0);
if !self.sessions.lock().contains(&session_id) {
self.missing_prompt_sessions.lock().push(session_id);
return Task::ready(Err(anyhow!("Session not found")));
}
+4 -4
View File
@@ -41,7 +41,7 @@ use std::rc::Rc;
use std::sync::Arc;
use ::ui::IconName;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use agent_settings::{AgentProfileId, AgentSettings};
use command_palette_hooks::CommandPaletteFilter;
use editor::{Editor, SelectionEffects, scroll::Autoscroll};
@@ -430,7 +430,7 @@ where
#[action(namespace = agent)]
#[serde(deny_unknown_fields)]
pub struct NewNativeAgentThreadFromSummary {
from_session_id: acp::SessionId,
from_session_id: acp_v1::SessionId,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
@@ -513,11 +513,11 @@ impl Agent {
/// Content to initialize new external agent with.
pub enum AgentInitialContent {
ThreadSummary {
session_id: acp::SessionId,
session_id: acp_v1::SessionId,
title: Option<SharedString>,
},
ContentBlock {
blocks: Vec<acp::ContentBlock>,
blocks: Vec<acp_v2::ContentBlock>,
auto_submit: bool,
},
FromExternalSource(ExternalSourcePrompt),
+240 -41
View File
@@ -1974,15 +1974,11 @@ impl ConversationView {
.message_queue
.first()
.is_some_and(|entry| entry.editor.focus_handle(cx).is_focused(window));
if let Some(entry) = active
.message_queue
.on_generation_stopped(is_first_editor_focused)
{
active.dispatch_queued_entry(entry, window, cx);
true
} else {
false
}
active.send_queued_message_after_generation_stopped(
is_first_editor_focused,
window,
cx,
)
})
} else {
false
@@ -2163,7 +2159,7 @@ impl ConversationView {
if !thread.is_draft_thread() {
return None;
}
let snapshot: Vec<acp_v1::ContentBlock> = thread
let snapshot: Vec<acp_v2::ContentBlock> = thread
.draft_prompt()
.map(|p| p.to_vec())
.unwrap_or_default();
@@ -4337,6 +4333,144 @@ pub(crate) mod tests {
});
}
#[gpui::test]
async fn test_unsupported_composer_draft_preserves_source_until_discard(
cx: &mut TestAppContext,
) {
init_test(cx);
let source = vec![
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("protected draft").annotations(
acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_future".into())]),
)),
acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
)),
];
let (conversation_view, cx) = setup_conversation_view_with_initial_content(
StubAgentServer::new(StubAgentConnection::new().with_receipt_submissions(true)),
AgentInitialContent::ContentBlock {
blocks: source.clone(),
auto_submit: true,
},
cx,
)
.await;
add_to_workspace_with_size(conversation_view.clone(), true, cx);
let thread_view = active_thread(&conversation_view, cx);
let message_editor = message_editor(&conversation_view, cx);
let thread_id = conversation_view.read_with(cx, |view, _| view.thread_id);
thread_view.read_with(cx, |view, cx| {
assert!(view.message_editor.read(cx).editor().read(cx).read_only(cx));
assert_eq!(view.thread.read(cx).draft_prompt(), Some(source.as_slice()));
assert!(view.thread.read(cx).entries().is_empty());
});
message_editor.update(cx, |_, cx| cx.notify());
cx.run_until_parked();
conversation_view.update(cx, |view, cx| view.schedule_draft_prompt_persist(cx));
cx.run_until_parked();
cx.executor().advance_clock(DRAFT_PROMPT_PERSIST_DEBOUNCE);
cx.run_until_parked();
assert_eq!(
cx.update(|_, cx| crate::draft_prompt_store::read(thread_id, cx)),
Some(source.clone()),
);
thread_view.update_in(cx, |view, window, cx| {
view.send_impl(message_editor.clone(), window, cx);
});
cx.run_until_parked();
thread_view.read_with(cx, |view, cx| {
assert!(!view.is_loading_contents);
assert!(matches!(
&view.thread_error,
Some(ThreadError::Other { message, .. }) if message.contains("unsupported content")
));
assert_eq!(view.thread.read(cx).draft_prompt(), Some(source.as_slice()));
assert!(view.thread.read(cx).entries().is_empty());
assert!(view.thread.read(cx).latest_submission_id().is_none());
});
thread_view.update_in(cx, |view, window, cx| {
view.thread.update(cx, |thread, cx| {
thread
.update_session_state(
acp_v2::StateUpdate::Running(acp_v2::RunningStateUpdate::new()),
cx,
)
.expect("independent running state");
});
view.add_to_queue(vec!["queued message".into()], vec![], window, cx);
view.interrupt_and_send(window, cx);
assert_eq!(view.thread.read(cx).status(), ThreadStatus::Generating);
assert!(
view.message_queue.on_generation_stopped(false).is_some(),
"rejecting the protected draft must not pause the ongoing turn's queue"
);
view.thread.update(cx, |thread, cx| {
thread
.update_session_state(
acp_v2::StateUpdate::Idle(acp_v2::IdleStateUpdate::new()),
cx,
)
.expect("independent activity finished");
});
});
cx.run_until_parked();
let discard = cx
.debug_bounds("discard-protected-draft")
.expect("protected draft should have an explicit discard control");
cx.simulate_click(discard.center(), gpui::Modifiers::default());
cx.run_until_parked();
cx.executor().advance_clock(DRAFT_PROMPT_PERSIST_DEBOUNCE);
cx.run_until_parked();
thread_view.read_with(cx, |view, cx| {
assert!(!view.message_editor.read(cx).editor().read(cx).read_only(cx));
assert!(view.message_editor.read(cx).is_empty(cx));
assert!(view.thread.read(cx).draft_prompt().is_none());
assert!(view.thread_error.is_none());
});
assert_eq!(
cx.update(|_, cx| crate::draft_prompt_store::read(thread_id, cx)),
None,
);
let (queued_id, queued_editor) = thread_view.update_in(cx, |view, window, cx| {
view.add_to_queue(source.clone(), vec![], window, cx);
let queued_id = view.message_queue.last_id().expect("queued source");
assert!(!view.move_queued_message_to_main_editor(queued_id, None, None, window, cx,));
let entry = view
.message_queue
.entry_by_id(queued_id)
.expect("source retained");
assert_eq!(entry.content, source);
assert!(
entry
.editor
.read(cx)
.text(cx)
.contains("Unsupported message content")
);
assert!(view.message_editor.read(cx).is_empty(cx));
assert!(view.thread.read(cx).draft_prompt().is_none());
(queued_id, entry.editor.clone())
});
queued_editor.update(cx, |_, cx| cx.emit(MessageEditorEvent::LostFocus));
cx.run_until_parked();
thread_view.read_with(cx, |view, cx| {
assert_eq!(
view.message_queue
.entry_by_id(queued_id)
.expect("queued source")
.content,
source
);
assert!(view.message_editor.read(cx).is_empty(cx));
assert!(view.thread.read(cx).draft_prompt().is_none());
});
}
#[gpui::test]
async fn test_agent_code_span_resolver_resolves_worktree_paths(cx: &mut TestAppContext) {
init_test(cx);
@@ -4470,7 +4604,7 @@ pub(crate) mod tests {
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -4509,13 +4643,22 @@ pub(crate) mod tests {
async fn test_queued_message_steer_defaults_off_and_toggles(cx: &mut TestAppContext) {
init_test(cx);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::default_response(), cx).await;
let fs = FakeFs::new(cx.executor());
let server = cx.update(|cx| {
language_model::LanguageModelRegistry::test(cx);
<dyn fs::Fs>::set_global(fs.clone(), cx);
let thread_store = cx.new(|cx| ThreadStore::new(cx));
NativeAgentServer::new(fs, thread_store)
});
let (conversation_view, cx) = setup_conversation_view(server, cx).await;
add_to_workspace(conversation_view.clone(), cx);
let native_thread = conversation_view
.read_with(cx, |view, cx| view.as_native_thread(cx))
.expect("native steering target");
let id = active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -4535,8 +4678,10 @@ pub(crate) mod tests {
);
});
active_thread(&conversation_view, cx).update(cx, |thread, _cx| {
assert!(!native_thread.read_with(cx, |thread, _| thread.end_turn_at_next_boundary()));
active_thread(&conversation_view, cx).update(cx, |thread, cx| {
thread.message_queue.toggle_steer(id);
thread.sync_queue_flag_to_native_thread(cx);
});
active_thread(&conversation_view, cx).read_with(cx, |thread, _cx| {
assert!(
@@ -4544,6 +4689,19 @@ pub(crate) mod tests {
"steering should be on after toggling"
);
});
assert!(native_thread.read_with(cx, |thread, _| thread.end_turn_at_next_boundary()));
active_thread(&conversation_view, cx).update(cx, |view, cx| {
view.message_queue
.entry_by_id_mut(id)
.expect("front source")
.content = vec![acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
))];
view.sync_queue_flag_to_native_thread(cx);
assert!(view.message_queue.front_wants_steer());
});
assert!(!native_thread.read_with(cx, |thread, _| thread.end_turn_at_next_boundary()));
}
#[gpui::test]
@@ -4814,7 +4972,7 @@ pub(crate) mod tests {
.expect("retained original")
.content
.as_ref(),
&[acp_v1::ContentBlock::from("first rejected text")],
&[acp_v2::ContentBlock::from("first rejected text")],
);
});
assert!(cx.debug_bounds(first_copy).is_some());
@@ -4980,7 +5138,7 @@ pub(crate) mod tests {
assert_eq!(view.thread.read(cx).status(), ThreadStatus::Generating);
assert!(matches!(
view.in_flight_prompt(cx).as_deref(),
Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"
Some([acp_v2::ContentBlock::Text(text)]) if text.text == "second"
));
}
assert!(view.thread_error.is_none());
@@ -5007,7 +5165,7 @@ pub(crate) mod tests {
assert!(view.turn_fields.turn_started_at.is_some());
assert!(matches!(
view.in_flight_prompt(cx).as_deref(),
Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"
Some([acp_v2::ContentBlock::Text(text)]) if text.text == "second"
));
assert!(view.thread_error.is_none());
});
@@ -5031,7 +5189,7 @@ pub(crate) mod tests {
));
assert!(matches!(
view.in_flight_prompt(cx).as_deref(),
Some([acp_v1::ContentBlock::Text(text)]) if text.text == "second"
Some([acp_v2::ContentBlock::Text(text)]) if text.text == "second"
));
} else {
assert!(view.thread_error.is_none());
@@ -5058,10 +5216,51 @@ pub(crate) mod tests {
.update_in(cx, |view, window, cx| view.send(window, cx));
cx.run_until_parked();
active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
let source = vec![acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
"_future",
Default::default(),
))];
view.add_to_queue(source.clone(), vec![], window, cx);
let id = view
.message_queue
.first_id()
.expect("unsupported queued source");
let latest = view.thread.read(cx).latest_submission_id();
view.send_queued_message_now(id, window, cx);
assert_eq!(
view.message_queue
.entry_by_id(id)
.expect("source retained")
.content,
source
);
assert!(view.message_queue.can_fast_track());
view.send(window, cx);
assert_eq!(
view.message_queue
.entry_by_id(id)
.expect("fast-track source retained")
.content,
source
);
assert!(!view.send_queued_message_after_generation_stopped(false, window, cx));
assert_eq!(
view.message_queue
.entry_by_id(id)
.expect("automatic source retained")
.content,
source
);
assert_eq!(view.thread.read(cx).status(), ThreadStatus::Generating);
assert_eq!(view.thread.read(cx).latest_submission_id(), latest);
view.remove_from_queue(id, cx);
});
// Queue a follow-up while the agent is generating.
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -5557,7 +5756,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -5920,16 +6119,16 @@ pub(crate) mod tests {
.await
.expect("pending selections must resolve after retry");
let [
acp_v1::ContentBlock::Resource(first),
acp_v1::ContentBlock::Text(separator),
acp_v1::ContentBlock::Resource(second),
acp_v2::ContentBlock::Resource(first),
acp_v2::ContentBlock::Text(separator),
acp_v2::ContentBlock::Resource(second),
] = contents.as_slice()
else {
panic!("expected exactly two resolved selections, got {contents:?}");
};
assert_eq!(separator.text, " ");
for (selection, expected) in [(first, "first selection"), (second, "second selection")] {
let acp_v1::EmbeddedResourceResource::TextResourceContents(selection) =
let acp_v2::EmbeddedResourceResource::TextResourceContents(selection) =
&selection.resource
else {
panic!("expected selected text");
@@ -6062,10 +6261,10 @@ pub(crate) mod tests {
.update(cx, |editor, cx| editor.contents(true, cx))
.await
.expect("pending selection must resolve after authentication");
let [acp_v1::ContentBlock::Resource(selection)] = contents.as_slice() else {
let [acp_v2::ContentBlock::Resource(selection)] = contents.as_slice() else {
panic!("expected one resolved selection, got {contents:?}");
};
let acp_v1::EmbeddedResourceResource::TextResourceContents(selection) = &selection.resource
let acp_v2::EmbeddedResourceResource::TextResourceContents(selection) = &selection.resource
else {
panic!("expected selected text");
};
@@ -7565,7 +7764,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -7696,7 +7895,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -7808,7 +8007,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -7880,7 +8079,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -7987,7 +8186,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
unimplemented!()
@@ -8056,7 +8255,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal)))
@@ -8171,7 +8370,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -16075,7 +16274,7 @@ pub(crate) mod tests {
// Add a plain-text message to the queue directly.
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -16114,7 +16313,7 @@ pub(crate) mod tests {
// Seed the main editor with existing content.
message_editor(&conversation_view, cx).update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"existing content".to_string(),
))],
window,
@@ -16125,7 +16324,7 @@ pub(crate) mod tests {
// Add a plain-text message to the queue.
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -16161,7 +16360,7 @@ pub(crate) mod tests {
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"first queued".to_string(),
))],
vec![],
@@ -16169,7 +16368,7 @@ pub(crate) mod tests {
cx,
);
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"second queued".to_string(),
))],
vec![],
@@ -16280,7 +16479,7 @@ pub(crate) mod tests {
.write()
.set_prompt_capabilities(acp_v1::PromptCapabilities::new().image(true));
thread.add_to_queue(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -16528,7 +16727,7 @@ pub(crate) mod tests {
fn prompt(
&self,
_params: acp_v1::PromptRequest,
_params: acp_v2::PromptRequest,
_cx: &mut App,
) -> Task<gpui::Result<acp_v1::PromptResponse>> {
Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
@@ -7,7 +7,7 @@ pub struct QueueEntryId(usize);
pub struct QueueEntry {
pub id: QueueEntryId,
pub content: Vec<acp_v1::ContentBlock>,
pub content: Vec<acp_v2::ContentBlock>,
pub tracked_buffers: Vec<Entity<Buffer>>,
/// When true, this message interrupts the agent at the next turn boundary
/// instead of waiting for generation to fully complete. Only the front
@@ -146,6 +146,15 @@ impl MessageQueue {
/// Handles a generation Stopped event, returning the entry to auto-send,
/// if any.
pub fn auto_send_candidate(&self, is_first_editor_focused: bool) -> Option<&QueueEntry> {
if matches!(self.processing_state, ProcessingState::AutoProcess) && !is_first_editor_focused
{
self.entries.front()
} else {
None
}
}
pub fn on_generation_stopped(&mut self, is_first_editor_focused: bool) -> Option<QueueEntry> {
match self.processing_state {
ProcessingState::AbsorbingCancel => {
@@ -157,10 +166,10 @@ impl MessageQueue {
ProcessingState::Paused => None,
ProcessingState::AutoProcess => {
// Don't auto-send while the user is editing the next message.
if is_first_editor_focused {
None
} else {
if self.auto_send_candidate(is_first_editor_focused).is_some() {
self.entries.pop_front()
} else {
None
}
}
}
@@ -827,33 +827,42 @@ impl ThreadView {
window,
cx,
);
if let Some(content) = initial_content {
let content_blocks = if let Some(content) = initial_content {
match content {
AgentInitialContent::ThreadSummary { session_id, title } => {
editor.insert_thread_summary(session_id, title, window, cx);
None
}
AgentInitialContent::ContentBlock {
blocks,
auto_submit,
} => {
should_auto_submit = auto_submit;
editor.set_message(blocks, window, cx);
Some(blocks)
}
AgentInitialContent::FromExternalSource(prompt) => {
show_external_source_prompt_warning = true;
// SECURITY: Be explicit about not auto submitting prompt from external source.
should_auto_submit = false;
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
prompt.into_string(),
))],
window,
cx,
);
Some(vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
prompt.into_string(),
))])
}
}
} else if let Some(draft) = thread.read(cx).draft_prompt() {
editor.set_message(draft.to_vec(), window, cx);
} else {
thread.read(cx).draft_prompt().map(|draft| draft.to_vec())
};
if let Some(blocks) = content_blocks {
if blocks.iter().all(acp_thread::content::can_convert_to_v1) {
editor.set_message(blocks, window, cx);
} else {
should_auto_submit = false;
thread.update(cx, |thread, cx| {
thread.set_draft_prompt(Some(blocks.clone()), cx);
});
editor.set_read_only(true, cx);
editor.set_source_message(blocks, window, cx);
}
}
editor
});
@@ -960,6 +969,10 @@ impl ThreadView {
}
subscriptions.push(cx.observe(&message_editor, |this, editor, cx| {
if editor.read(cx).editor().read(cx).read_only(cx) {
this._draft_resolve_task.take();
return;
}
let is_empty = editor.read(cx).text(cx).is_empty();
let draft_contents_task = if is_empty {
None
@@ -974,6 +987,9 @@ impl ThreadView {
None
};
this.update(cx, |this, cx| {
if this.message_editor.read(cx).editor().read(cx).read_only(cx) {
return;
}
this.thread.update(cx, |thread, cx| {
thread.set_draft_prompt(draft, cx);
});
@@ -1209,7 +1225,12 @@ impl ThreadView {
&self,
message_editor: &Entity<MessageEditor>,
cx: &mut App,
) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
) -> Task<Result<(Vec<acp_v2::ContentBlock>, Vec<Entity<Buffer>>)>> {
if message_editor.read(cx).editor().read(cx).read_only(cx) {
return Task::ready(Err(anyhow!(
"This draft contains unsupported content and cannot be edited or sent. Discard the draft to write a new message."
)));
}
let expand = self.as_native_thread(cx).is_some_and(|thread| {
let thread = thread.read(cx);
AgentSettings::get_global(cx)
@@ -1504,27 +1525,27 @@ impl ThreadView {
}
}
pub(crate) fn in_flight_prompt(&self, cx: &App) -> Option<Arc<[acp_v1::ContentBlock]>> {
pub(crate) fn in_flight_prompt(&self, cx: &App) -> Option<Arc<[acp_v2::ContentBlock]>> {
let record = self.thread.read(cx);
let record = record.submission(self.current_submission?)?;
(!matches!(record.state, SubmissionState::Completed)).then(|| record.content.clone())
}
fn submission_text_parts(content: &[acp_v1::ContentBlock]) -> impl Iterator<Item = &str> {
fn submission_text_parts(content: &[acp_v2::ContentBlock]) -> impl Iterator<Item = &str> {
content.iter().map(|block| match block {
acp_v1::ContentBlock::Text(text) => text.text.as_str(),
acp_v1::ContentBlock::ResourceLink(link) => link.name.as_str(),
acp_v1::ContentBlock::Resource(resource) => match &resource.resource {
acp_v1::EmbeddedResourceResource::TextResourceContents(resource) => {
acp_v2::ContentBlock::Text(text) => text.text.as_str(),
acp_v2::ContentBlock::ResourceLink(link) => link.name.as_str(),
acp_v2::ContentBlock::Resource(resource) => match &resource.resource {
acp_v2::EmbeddedResourceResource::TextResourceContents(resource) => {
resource.uri.as_str()
}
acp_v1::EmbeddedResourceResource::BlobResourceContents(resource) => {
acp_v2::EmbeddedResourceResource::BlobResourceContents(resource) => {
resource.uri.as_str()
}
_ => "[Resource attachment]",
},
acp_v1::ContentBlock::Image(_) => "[Image attachment]",
acp_v1::ContentBlock::Audio(_) => "[Audio attachment]",
acp_v2::ContentBlock::Image(_) => "[Image attachment]",
acp_v2::ContentBlock::Audio(_) => "[Audio attachment]",
_ => "[Unsupported attachment]",
})
}
@@ -1550,6 +1571,15 @@ impl ThreadView {
.then(|| record.content.to_vec())
});
if let Some(content) = content {
if !content.iter().all(acp_thread::content::can_convert_to_v1) {
self.handle_thread_error(
anyhow!(
"This saved submission contains unsupported content and cannot be restored. The original submission has been kept."
),
cx,
);
return;
}
self.message_editor.update(cx, |editor, cx| {
editor.set_message(content, window, cx);
});
@@ -1737,6 +1767,15 @@ impl ThreadView {
}
pub fn send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.message_editor.read(cx).editor().read(cx).read_only(cx) {
self.handle_thread_error(
anyhow!(
"This draft contains unsupported content and cannot be edited or sent. Discard the draft to write a new message."
),
cx,
);
return;
}
let thread = &self.thread;
if self.is_loading_contents {
@@ -1749,6 +1788,12 @@ impl ThreadView {
let is_generating = thread.read(cx).status() != ThreadStatus::Idle;
if is_editor_empty {
if self.message_queue.can_fast_track()
&& let Some(id) = self.message_queue.first_id()
&& !self.validate_queued_entry(id, cx)
{
return;
}
if let Some(entry) = self.message_queue.try_fast_track(is_generating) {
self.dispatch_queued_entry(entry, window, cx);
}
@@ -1841,18 +1886,18 @@ impl ThreadView {
// Strip the leading `/command` from the first text block; whatever
// remains (including any later mention blocks) becomes the queued
// follow-up message.
if let Some(acp_v1::ContentBlock::Text(text_content)) = content.first_mut() {
if let Some(acp_v2::ContentBlock::Text(text_content)) = content.first_mut() {
text_content.text = strip_leading_command(&text_content.text, &command_name);
}
if matches!(
content.first(),
Some(acp_v1::ContentBlock::Text(text)) if text.text.trim().is_empty()
Some(acp_v2::ContentBlock::Text(text)) if text.text.trim().is_empty()
) {
content.remove(0);
}
let command_block =
acp_v1::ContentBlock::Text(acp_v1::TextContent::new(format!("/{command_name}")));
acp_v2::ContentBlock::Text(acp_v2::TextContent::new(format!("/{command_name}")));
this.update_in(cx, |this, window, cx| {
// Queue the remainder first, then start the command turn; the
@@ -1917,7 +1962,7 @@ impl ThreadView {
pub fn send_content(
&mut self,
contents_task: Task<
anyhow::Result<Option<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>>,
anyhow::Result<Option<(Vec<acp_v2::ContentBlock>, Vec<Entity<Buffer>>)>>,
>,
is_native_command: bool,
window: &mut Window,
@@ -1981,8 +2026,8 @@ impl ThreadView {
let text: String = contents
.iter()
.filter_map(|block| match block {
acp_v1::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
acp_v1::ContentBlock::ResourceLink(resource_link) => {
acp_v2::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
acp_v2::ContentBlock::ResourceLink(resource_link) => {
Some(format!("@{}", resource_link.name))
}
_ => None,
@@ -2089,6 +2134,15 @@ impl ThreadView {
}
pub fn interrupt_and_send(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.message_editor.read(cx).editor().read(cx).read_only(cx) {
self.handle_thread_error(
anyhow!(
"This draft contains unsupported content and cannot be edited or sent. Discard the draft to write a new message."
),
cx,
);
return;
}
let thread = &self.thread;
if self.is_loading_contents {
@@ -2403,7 +2457,7 @@ impl ThreadView {
pub fn add_to_queue(
&mut self,
content: Vec<acp_v1::ContentBlock>,
content: Vec<acp_v2::ContentBlock>,
tracked_buffers: Vec<Entity<Buffer>>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -2428,7 +2482,7 @@ impl ThreadView {
cx,
);
editor.set_read_only(true, cx);
editor.set_message(content.clone(), window, cx);
editor.set_source_message(content.clone(), window, cx);
editor
});
@@ -2486,6 +2540,13 @@ impl ThreadView {
let Some(entry) = self.message_queue.entry_by_id(id) else {
return;
};
if !entry
.content
.iter()
.all(acp_thread::content::can_convert_to_v1)
{
return;
}
let contents_task = entry
.editor
.update(cx, |editor, cx| editor.contents(false, cx));
@@ -2495,6 +2556,13 @@ impl ThreadView {
this.update(cx, |this, cx| {
if let Some(entry) = this.message_queue.entry_by_id_mut(id) {
if !entry
.content
.iter()
.all(acp_thread::content::can_convert_to_v1)
{
return;
}
entry.content = content;
entry.tracked_buffers = tracked_buffers;
}
@@ -2528,19 +2596,64 @@ impl ThreadView {
if let Some(native_thread) = self.as_native_thread(cx) {
// By default queued messages wait for the turn to fully complete.
// Only a "steering" front message ends the turn at the next boundary.
let end_at_boundary = self.message_queue.front_wants_steer();
let end_at_boundary = self.message_queue.front_wants_steer()
&& self.message_queue.first().is_some_and(|entry| {
self.thread
.read(cx)
.validate_prompt_content(&entry.content)
.is_ok()
});
native_thread.update(cx, |thread, _| {
thread.set_end_turn_at_next_boundary(end_at_boundary);
});
}
}
fn validate_queued_entry(&mut self, id: QueueEntryId, cx: &mut Context<Self>) -> bool {
let Some(entry) = self.message_queue.entry_by_id(id) else {
return false;
};
if let Err(error) = self.thread.read(cx).validate_prompt_content(&entry.content) {
self.handle_thread_error(error, cx);
return false;
}
true
}
pub fn send_queued_message_after_generation_stopped(
&mut self,
is_first_editor_focused: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
if let Some(id) = self
.message_queue
.auto_send_candidate(is_first_editor_focused)
.map(|entry| entry.id)
&& !self.validate_queued_entry(id, cx)
{
self.message_queue.pause();
}
if let Some(entry) = self
.message_queue
.on_generation_stopped(is_first_editor_focused)
{
self.dispatch_queued_entry(entry, window, cx);
true
} else {
false
}
}
pub fn send_queued_message_now(
&mut self,
id: QueueEntryId,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.validate_queued_entry(id, cx) {
return;
}
let is_generating = self.thread.read(cx).status() == acp_thread::ThreadStatus::Generating;
if let Some(entry) = self.message_queue.send_now(id, is_generating) {
self.dispatch_queued_entry(entry, window, cx);
@@ -2550,7 +2663,7 @@ impl ThreadView {
/// The shared "actually send this entry" path, used by fast-track,
/// auto-processing on Stopped, and "Send Now". The entry must already have
/// been removed from the queue.
pub fn dispatch_queued_entry(
fn dispatch_queued_entry(
&mut self,
entry: QueueEntry,
window: &mut Window,
@@ -2572,7 +2685,7 @@ impl ThreadView {
let is_native_command = content
.first()
.and_then(|block| match block {
acp_v1::ContentBlock::Text(text) => Some(text.text.as_str()),
acp_v2::ContentBlock::Text(text) => Some(text.text.as_str()),
_ => None,
})
.and_then(|text| {
@@ -2609,6 +2722,25 @@ impl ThreadView {
window: &mut Window,
cx: &mut Context<Self>,
) -> bool {
if self.message_editor.read(cx).editor().read(cx).read_only(cx) {
self.handle_thread_error(
anyhow!("Discard the unsupported draft before moving a queued message into the composer."),
cx,
);
return false;
}
if self.message_queue.entry_by_id(id).is_some_and(|entry| {
!entry
.content
.iter()
.all(acp_thread::content::can_convert_to_v1)
}) {
self.handle_thread_error(
anyhow!("This queued message contains unsupported content and cannot be edited."),
cx,
);
return false;
}
let Some(queued_message) = self.remove_from_queue(id, cx) else {
return false;
};
@@ -4788,6 +4920,23 @@ impl ThreadView {
let max_content_width = AgentSettings::get_global(cx).max_content_width;
let has_messages = self.list_state.item_count() > 0;
let fills_container = !has_messages || editor_expanded;
let composer_is_read_only = self.message_editor.read(cx).editor().read(cx).read_only(cx);
let discard_draft_button = composer_is_read_only.then(|| {
div()
.debug_selector(|| "discard-protected-draft".into())
.child(
Button::new("discard-protected-draft", "Discard draft")
.label_size(LabelSize::Small)
.on_click(cx.listener(|this, _, window, cx| {
this._draft_resolve_task.take();
this.message_editor.update(cx, |editor, cx| {
editor.set_read_only(false, cx);
editor.set_message(Vec::new(), window, cx);
});
this.clear_thread_error(cx);
})),
)
});
h_flex()
.py_2()
@@ -4879,6 +5028,7 @@ impl ThreadView {
.min_w_0()
.flex_wrap()
.gap_1()
.children(discard_draft_button)
.children(self.render_token_usage(cx))
.children(self.profile_selector.clone())
.map(|this| match self.config_options_view.clone() {
@@ -11999,6 +12149,17 @@ impl ThreadView {
this.clear_thread_error(cx);
if let Some(message) = this.in_flight_prompt(cx) {
if !message.iter().all(acp_thread::content::can_convert_to_v1)
|| this.message_editor.read(cx).editor().read(cx).read_only(cx)
{
this.handle_thread_error(
anyhow!(
"This saved submission cannot be restored into the composer. The original submission and draft have been kept."
),
cx,
);
return;
}
if !this.thread.read(cx).uses_reported_activity()
&& let Some(submission_id) = this.current_submission
&& this.thread.read(cx).submission(submission_id).is_some_and(
+7 -7
View File
@@ -9,7 +9,7 @@
//! the format we persist.
use agent::ZED_AGENT_ID;
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::v2 as acp_v2;
use anyhow::Context as _;
use db::kvp::KeyValueStore;
use gpui::{App, AppContext as _, Entity, Task};
@@ -27,7 +27,7 @@ const NAMESPACE: &str = "agent_draft_prompts";
/// Maximum length (in characters) of a draft label rendered in the sidebar.
const MAX_LABEL_CHARS: usize = 250;
pub fn read(thread_id: ThreadId, cx: &App) -> Option<Vec<acp::ContentBlock>> {
pub fn read(thread_id: ThreadId, cx: &App) -> Option<Vec<acp_v2::ContentBlock>> {
let kvp = KeyValueStore::global(cx);
let raw = kvp
.scoped(NAMESPACE)
@@ -39,7 +39,7 @@ pub fn read(thread_id: ThreadId, cx: &App) -> Option<Vec<acp::ContentBlock>> {
pub fn write(
thread_id: ThreadId,
prompt: &[acp::ContentBlock],
prompt: &[acp_v2::ContentBlock],
cx: &App,
) -> Task<anyhow::Result<()>> {
let kvp = KeyValueStore::global(cx);
@@ -85,9 +85,9 @@ pub fn draft_has_user_content<'a>(
}
}
fn blocks_have_user_content(blocks: &[acp::ContentBlock]) -> bool {
fn blocks_have_user_content(blocks: &[acp_v2::ContentBlock]) -> bool {
blocks.iter().any(|block| match block {
acp::ContentBlock::Text(text) => !text.text.trim().is_empty(),
acp_v2::ContentBlock::Text(text) => !text.text.trim().is_empty(),
_ => true,
})
}
@@ -158,8 +158,8 @@ pub fn display_label_for_draft(
let raw = blocks
.iter()
.filter_map(|block| match block {
acp::ContentBlock::Text(text) => Some(text.text.as_str()),
acp::ContentBlock::ResourceLink(link) => Some(link.uri.as_str()),
acp_v2::ContentBlock::Text(text) => Some(text.text.as_str()),
acp_v2::ContentBlock::ResourceLink(link) => Some(link.uri.as_str()),
_ => None,
})
.join(" ");
+56 -83
View File
@@ -11,7 +11,7 @@ use crate::{
};
use acp_thread::MentionUri;
use agent::ThreadStore;
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use anyhow::{Result, anyhow};
use base64::Engine as _;
use editor::{
@@ -843,7 +843,7 @@ impl MessageEditor {
&self,
full_mention_content: bool,
cx: &mut Context<Self>,
) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
) -> Task<Result<(Vec<acp_v2::ContentBlock>, Vec<Entity<Buffer>>)>> {
let text = self.editor.read(cx).text(cx);
let (available_commands, available_skills) = {
let session_capabilities = self.session_capabilities.read();
@@ -869,7 +869,7 @@ impl MessageEditor {
pub fn draft_contents(
&self,
cx: &mut Context<Self>,
) -> Task<Result<Vec<acp_v1::ContentBlock>>> {
) -> Task<Result<Vec<acp_v2::ContentBlock>>> {
let build_task = self.build_content_blocks(false, cx);
cx.spawn(async move |_, _cx| {
let (blocks, _tracked_buffers) = build_task.await?;
@@ -881,7 +881,7 @@ impl MessageEditor {
&self,
full_mention_content: bool,
cx: &mut Context<Self>,
) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
) -> Task<Result<(Vec<acp_v2::ContentBlock>, Vec<Entity<Buffer>>)>> {
let contents = self
.mention_set
.update(cx, |store, cx| store.contents(full_mention_content, cx));
@@ -912,7 +912,7 @@ impl MessageEditor {
/// Snapshots the editor's current draft into a list of `ContentBlock`s
/// without awaiting any pending mention resolution.
pub fn draft_content_blocks_snapshot(&self, cx: &App) -> Vec<acp_v1::ContentBlock> {
pub fn draft_content_blocks_snapshot(&self, cx: &App) -> Vec<acp_v2::ContentBlock> {
let editor = self.editor.read(cx);
let crease_snapshot = editor.display_map.read(cx).crease_snapshot();
let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
@@ -1694,7 +1694,7 @@ impl MessageEditor {
pub fn set_message(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -1708,50 +1708,27 @@ impl MessageEditor {
pub fn set_source_message(
&mut self,
source_blocks: Vec<agent_client_protocol::schema::v2::ContentBlock>,
source_blocks: Vec<acp_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,
);
}
}
self.set_message(source_blocks, 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,
)));
if acp_thread::content::can_convert_to_v1(&block)
|| matches!(&block, acp_v2::ContentBlock::Text(_))
{
visible.push(block);
}
}
visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
visible.push(acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"\n[Unsupported message content — this message cannot be edited or resent]",
)));
self.set_message(visible, window, cx);
@@ -1759,7 +1736,7 @@ impl MessageEditor {
pub fn append_message(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
separator: Option<&str>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -1782,7 +1759,7 @@ impl MessageEditor {
fn insert_message_blocks(
&mut self,
message: Vec<acp_v1::ContentBlock>,
message: Vec<acp_v2::ContentBlock>,
append_to_existing: bool,
window: &mut Window,
cx: &mut Context<Self>,
@@ -1801,11 +1778,11 @@ impl MessageEditor {
for chunk in message {
match chunk {
acp_v1::ContentBlock::Text(text_content) => {
acp_v2::ContentBlock::Text(text_content) => {
append_normalized(&mut text, text_content.text);
}
acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource {
resource: acp_v1::EmbeddedResourceResource::TextResourceContents(resource),
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource {
resource: acp_v2::EmbeddedResourceResource::TextResourceContents(resource),
..
}) => {
let Some(mention_uri) = MentionUri::parse(&resource.uri, path_style).log_err()
@@ -1824,7 +1801,7 @@ impl MessageEditor {
},
));
}
acp_v1::ContentBlock::ResourceLink(resource) => {
acp_v2::ContentBlock::ResourceLink(resource) => {
if let Some(mention_uri) =
MentionUri::parse(&resource.uri, path_style).log_err()
{
@@ -1834,7 +1811,7 @@ impl MessageEditor {
mentions.push((start..end, mention_uri, Mention::Link));
}
}
acp_v1::ContentBlock::Image(acp_v1::ImageContent {
acp_v2::ContentBlock::Image(acp_v2::ImageContent {
uri,
data,
mime_type,
@@ -1850,7 +1827,7 @@ impl MessageEditor {
let Some(mention_uri) = mention_uri.log_err() else {
continue;
};
let Some(format) = ImageFormat::from_mime_type(&mime_type) else {
let Some(format) = ImageFormat::from_mime_type(&mime_type.0) else {
log::error!("failed to parse MIME type for image: {mime_type:?}");
continue;
};
@@ -2141,7 +2118,7 @@ fn build_chunks_from_creases(
buffer_snapshot: &MultiBufferSnapshot,
supports_embedded_context: bool,
mut resolve: impl FnMut(&CreaseId) -> Option<(MentionUri, Option<Mention>)>,
) -> (Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>) {
) -> (Vec<acp_v2::ContentBlock>, Vec<Entity<Buffer>>) {
let mut ix = text
.char_indices()
.find(|(_, c)| !c.is_whitespace())
@@ -2205,7 +2182,7 @@ fn mention_to_content_block(
mention: Option<&Mention>,
supports_embedded_context: bool,
tracked_buffers: &mut Vec<Entity<Buffer>>,
) -> acp_v1::ContentBlock {
) -> acp_v2::ContentBlock {
match mention {
Some(Mention::Text {
content,
@@ -2213,23 +2190,23 @@ fn mention_to_content_block(
}) => {
tracked_buffers.extend(mention_tracked_buffers.iter().cloned());
if supports_embedded_context {
acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new(
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
acp_v2::EmbeddedResourceResource::TextResourceContents(
acp_v2::TextResourceContents::new(
content.clone(),
uri.to_uri().to_string(),
),
),
))
} else {
acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
uri.name(),
uri.to_uri().to_string(),
))
}
}
Some(Mention::Image(mention_image)) => acp_v1::ContentBlock::Image(
acp_v1::ImageContent::new(mention_image.data.clone(), mention_image.format.mime_type())
Some(Mention::Image(mention_image)) => acp_v2::ContentBlock::Image(
acp_v2::ImageContent::new(mention_image.data.clone(), mention_image.format.mime_type())
.uri(match uri {
MentionUri::File { .. } | MentionUri::PastedImage { .. } => {
Some(uri.to_uri().to_string())
@@ -2240,7 +2217,7 @@ fn mention_to_content_block(
}
}),
),
_ => acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
_ => acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
uri.name(),
uri.to_uri().to_string(),
)),
@@ -2317,7 +2294,7 @@ mod tests {
use super::PromptLocalCommand;
use acp_thread::MentionUri;
use agent::{ThreadStore, outline};
use agent_client_protocol::schema::v1 as acp_v1;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use base64::Engine as _;
use editor::{
AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects,
@@ -2681,7 +2658,7 @@ mod tests {
.unwrap();
// We don't send a resource link for the deleted crease.
pretty_assertions::assert_matches!(content.as_slice(), [acp_v1::ContentBlock::Text { .. }]);
pretty_assertions::assert_matches!(content.as_slice(), [acp_v2::ContentBlock::Text { .. }]);
}
#[gpui::test]
@@ -2790,7 +2767,7 @@ mod tests {
.unwrap();
assert_eq!(content.len(), 1);
if let acp_v1::ContentBlock::Text(text) = &content[0] {
if let acp_v2::ContentBlock::Text(text) = &content[0] {
assert_eq!(text.text, "Hello Claude!");
} else {
panic!("Expected ContentBlock::Text");
@@ -2808,7 +2785,7 @@ mod tests {
.unwrap();
assert_eq!(content.len(), 1);
if let acp_v1::ContentBlock::Text(text) = &content[0] {
if let acp_v2::ContentBlock::Text(text) = &content[0] {
assert_eq!(text.text, "Check this @");
} else {
panic!("Expected ContentBlock::Text");
@@ -4251,7 +4228,7 @@ mod tests {
content,
vec![
"What is in ".into(),
acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"main.rs",
main_rs_uri
))
@@ -4276,9 +4253,9 @@ mod tests {
content,
vec![
"What is in ".into(),
acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents::new(file_content, main_rs_uri)
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
acp_v2::EmbeddedResourceResource::TextResourceContents(
acp_v2::TextResourceContents::new(file_content, main_rs_uri)
)
))
]
@@ -4971,10 +4948,10 @@ mod tests {
let resource_uris: Vec<&str> = blocks
.iter()
.filter_map(|block| match block {
acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource {
acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource {
resource:
acp_v1::EmbeddedResourceResource::TextResourceContents(
acp_v1::TextResourceContents { uri, .. },
acp_v2::EmbeddedResourceResource::TextResourceContents(
acp_v2::TextResourceContents { uri, .. },
),
..
}) => Some(uri.as_str()),
@@ -4988,7 +4965,7 @@ mod tests {
);
assert!(resource_uris.contains(&fixture.first_uri.to_uri().to_string().as_str()));
for block in &blocks {
if let acp_v1::ContentBlock::Text(text) = block {
if let acp_v2::ContentBlock::Text(text) = block {
assert!(
!text.text.split_whitespace().any(|word| word == "selection"),
"text block must not contain bare fold placeholder: {:?}",
@@ -5628,7 +5605,7 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"hello world".to_string(),
))],
window,
@@ -5648,9 +5625,9 @@ mod tests {
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"),
)],
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"original",
))],
window,
cx,
);
@@ -5683,8 +5660,6 @@ mod tests {
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| {
@@ -5707,8 +5682,6 @@ mod tests {
#[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| {
@@ -5736,8 +5709,8 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![
acp_v1::ContentBlock::Text(acp_v1::TextContent::new("before\r\n".to_string())),
acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
acp_v2::ContentBlock::Text(acp_v2::TextContent::new("before\r\n".to_string())),
acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"file.txt",
"file:///project/file.txt",
)),
@@ -5763,7 +5736,7 @@ mod tests {
// Set initial content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"old content".to_string(),
))],
window,
@@ -5774,7 +5747,7 @@ mod tests {
// Replace with new content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"new content".to_string(),
))],
window,
@@ -5796,7 +5769,7 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"appended".to_string(),
))],
Some("\n\n"),
@@ -5820,7 +5793,7 @@ mod tests {
// Seed initial content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"initial".to_string(),
))],
window,
@@ -5831,7 +5804,7 @@ mod tests {
// Append with separator.
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"appended".to_string(),
))],
Some("\n\n"),
@@ -5884,7 +5857,7 @@ mod tests {
// Seed plain-text prefix so the editor is non-empty before appending.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"prefix text".to_string(),
))],
window,
@@ -5895,8 +5868,8 @@ mod tests {
// Append a message that contains a ResourceLink mention.
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
vec![acp_v1::ContentBlock::ResourceLink(
acp_v1::ResourceLink::new("file.txt", "file:///project/file.txt"),
vec![acp_v2::ContentBlock::ResourceLink(
acp_v2::ResourceLink::new("file.txt", "file:///project/file.txt"),
)],
Some("\n\n"),
window,
+2 -2
View File
@@ -41,7 +41,7 @@ use std::time::{Duration, Instant};
use acp_thread::AgentConnection as _;
use agent::{NativeAgent, NativeAgentConnection, Templates, ThreadStore};
use agent_client_protocol::schema::v1 as acp;
use agent_client_protocol::schema::{v1 as acp, v2 as acp_v2};
use anyhow::{Context, Result};
use clap::Parser;
use feature_flags::FeatureFlagAppExt as _;
@@ -815,7 +815,7 @@ async fn run_agent(
log_acp_thread_event(&acp_thread, event, cx);
});
let message = vec![acp::ContentBlock::Text(acp::TextContent::new(
let message = vec![acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
instruction.to_string(),
))];
+6 -5
View File
@@ -1,6 +1,7 @@
use super::*;
use acp_thread::{AcpThread, PermissionOptions, StubAgentConnection};
use agent::ThreadStore;
use agent_client_protocol::schema::v2 as acp_v2;
use agent_settings::AgentSettings;
use agent_ui::{
ThreadId,
@@ -2952,7 +2953,7 @@ async fn test_terminal_close_event_keeps_linked_worktree_workspace_with_live_edi
assert!(
matches!(
live_blocks.as_deref(),
Some([acp::ContentBlock::Text(text)]) if text.text == "keep this draft"
Some([acp_v2::ContentBlock::Text(text)]) if text.text == "keep this draft"
),
"edited draft should still be readable from the panel after opening the terminal"
);
@@ -3110,7 +3111,7 @@ async fn test_archive_selected_draft_archives_linked_worktree_after_last_draft(
cx.update(|_, cx| {
agent_ui::draft_prompt_store::write(
first_draft_id,
&[acp::ContentBlock::Text(acp::TextContent::new(
&[acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"first draft",
))],
cx,
@@ -3121,7 +3122,7 @@ async fn test_archive_selected_draft_archives_linked_worktree_after_last_draft(
cx.update(|_, cx| {
agent_ui::draft_prompt_store::write(
second_draft_id,
&[acp::ContentBlock::Text(acp::TextContent::new(
&[acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"second draft",
))],
cx,
@@ -3314,7 +3315,7 @@ async fn test_archive_selected_draft_archives_closed_linked_worktree(cx: &mut Te
cx.update(|_, cx| {
agent_ui::draft_prompt_store::write(
draft_id,
&[acp::ContentBlock::Text(acp::TextContent::new(
&[acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"closed draft",
))],
cx,
@@ -14871,7 +14872,7 @@ async fn test_discard_mixed_workspace_draft_closes_only_archived_worktree_items(
cx.update(|_, cx| {
agent_ui::draft_prompt_store::write(
draft_id,
&[acp::ContentBlock::Text(acp::TextContent::new(
&[acp_v2::ContentBlock::Text(acp_v2::TextContent::new(
"mixed workspace draft",
))],
cx,