Skip to content

armgit / zed

Public Imported from GitHub
0

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

agent_servers: Integrate inactive v2 receipt submissions (#65653)

Ben Brandt28d0a3547f16
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index ea7abde2464..dda463aa577 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -4171,6 +4171,7 @@ impl AcpThread {
fn track_submission(
&mut self,
id: SubmissionId,
+ applied: Option<oneshot::Sender<bool>>,
cx: &mut Context<Self>,
complete: impl 'static
+ AsyncFnOnce(
@@ -4224,6 +4225,11 @@ impl AcpThread {
Err(error) => SubmissionState::Failed(format!("{error:#}").into()),
};
let changed = this.submissions.settle(id, state);
+ if let Some(applied) = applied
+ && applied.send(response.is_ok()).is_err()
+ {
+ log::debug!("Receipt transport ended before application acknowledgement");
+ }
// The thread owns settlement even when the response observer has gone away.
if let Err(Err(error)) = sender.send(response) {
log::debug!("Submission observer was dropped: {error:#}");
@@ -6403,9 +6409,10 @@ impl AcpThread {
push_user_message: bool,
cx: &mut Context<Self>,
) -> Submission {
- if let Some(submissions) = self.submissions.receipt_transport() {
- let response = submissions.prompt(message.clone(), cx);
- self.submit_receipt(message, response, cx)
+ if let Some(submissions) = self.submissions.receipt_transport().cloned() {
+ let id = self.register_submission(message.clone().into(), cx);
+ let request = submissions.submit(message, cx);
+ self.track_receipt_submission(id, request, cx)
} else {
let id = self.register_submission(message.clone().into(), cx);
self.send_inner(id, message, push_user_message, cx)
@@ -6415,11 +6422,21 @@ impl AcpThread {
pub fn submit_receipt(
&mut self,
content: Vec<acp_v2::ContentBlock>,
- response: Task<Result<acp_v2::PromptResponse>>,
+ request: impl Into<ReceiptSubmission>,
cx: &mut Context<Self>,
) -> Submission {
let id = self.register_submission(content.into(), cx);
- self.track_submission(id, cx, async move |_, _| {
+ self.track_receipt_submission(id, request.into(), cx)
+ }
+
+ fn track_receipt_submission(
+ &mut self,
+ id: SubmissionId,
+ request: ReceiptSubmission,
+ cx: &mut Context<Self>,
+ ) -> Submission {
+ let ReceiptSubmission { response, applied } = request;
+ self.track_submission(id, applied, cx, async move |_, _| {
Ok(Some(SubmissionResponse::Accepted(response.await?)))
})
}
@@ -6519,7 +6536,7 @@ impl AcpThread {
) -> Submission {
let request = acp_v2::PromptRequest::new(self.session_id().clone(), message);
if let Err(error) = self.validate_prompt_content(&request.prompt) {
- return self.track_submission(id, cx, async move |_, _| Err(error));
+ return self.track_submission(id, None, cx, async move |_, _| Err(error));
}
let language_registry = self.project.read(cx).languages().clone();
let path_style = self.project.read(cx).path_style(cx);
@@ -6602,13 +6619,11 @@ impl AcpThread {
.unwrap_or_default();
let id = self.register_submission(content.clone(), cx);
if let Err(error) = self.validate_prompt_content(&content) {
- return self.track_submission(id, cx, async move |_, _| Err(error));
+ return self.track_submission(id, None, cx, async move |_, _| Err(error));
}
if let Some(submissions) = self.submissions.receipt_transport() {
- let response = submissions.retry(cx);
- return self.track_submission(id, cx, async move |_, _| {
- Ok(Some(SubmissionResponse::Accepted(response.await?)))
- });
+ let request = submissions.retry(cx);
+ return self.track_receipt_submission(id, request, cx);
}
self.run_turn(id, cx, async move |this, cx| {
this.update(cx, |this, cx| {
@@ -6788,7 +6803,7 @@ impl AcpThread {
}
})?
};
- self.track_submission(id, cx, async move |thread, cx| {
+ self.track_submission(id, None, cx, async move |thread, cx| {
Ok(completion(thread, cx)
.await?
.map(SubmissionResponse::LegacyCompleted))
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 95b1f9b08e8..19b53e0afe1 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -1,9 +1,9 @@
-use crate::{AcpThread, ElicitationStore};
+use crate::{AcpThread, ElicitationStore, ReceiptSubmission};
use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use anyhow::Result;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
-use gpui::{Entity, SharedString, Task};
+use gpui::{Context, Entity, SharedString, Task};
use language_model::DisabledReason;
use project::{AgentId, Project};
use serde::{Deserialize, Serialize};
@@ -196,6 +196,8 @@ pub trait AgentConnection {
None
}
+ /// Selected during thread construction, before backend registration may be complete.
+ /// Validate the submitting owner when publishing, not when selecting this capability.
fn receipt_submissions(
&self,
_session_id: &acp_v2::SessionId,
@@ -321,20 +323,22 @@ pub trait AgentSessionClientUserMessageIds {
pub trait ReceiptSessionSubmissions {
/// Transport loss must carry [`crate::SubmissionDisconnected`] (which may be
/// added as error context) rather than claiming that the agent rejected insertion.
- fn prompt(
+ /// The owner context binds publication even when capability selection preceded registration.
+ fn submit(
&self,
content: Vec<acp_v2::ContentBlock>,
- cx: &mut App,
- ) -> Task<Result<acp_v2::PromptResponse>>;
+ cx: &mut Context<AcpThread>,
+ ) -> ReceiptSubmission;
fn supports_retry(&self) -> bool {
false
}
- fn retry(&self, _cx: &mut App) -> Task<Result<acp_v2::PromptResponse>> {
+ fn retry(&self, _cx: &mut Context<AcpThread>) -> ReceiptSubmission {
Task::ready(Err(anyhow::anyhow!(
"Receipt-driven retry is not supported"
)))
+ .into()
}
}
@@ -1406,19 +1410,20 @@ mod test_support {
}
impl ReceiptSessionSubmissions for StubReceiptSessionSubmissions {
- fn prompt(
+ fn submit(
&self,
content: Vec<acp_v2::ContentBlock>,
- cx: &mut App,
- ) -> Task<Result<acp_v2::PromptResponse>> {
+ cx: &mut gpui::Context<AcpThread>,
+ ) -> ReceiptSubmission {
if !self.sessions.lock().contains_key(&self.session_id) {
- return Task::ready(Err(anyhow::Error::msg("Unknown receipt session")));
+ return Task::ready(Err(anyhow::Error::msg("Unknown receipt session"))).into();
}
*self.receipt_prompt.lock() = Some(content);
match self.next_receipt_response.lock().take() {
- Some(receiver) => cx.spawn(async move |_| Ok(receiver.await??)),
+ Some(receiver) => cx.spawn(async move |_, _| Ok(receiver.await??)),
None => Task::ready(Err(anyhow::Error::msg("No deferred receipt response"))),
}
+ .into()
}
}
diff --git a/crates/acp_thread/src/submission.rs b/crates/acp_thread/src/submission.rs
index 59a4abd5a7b..574ce0fc5d8 100644
--- a/crates/acp_thread/src/submission.rs
+++ b/crates/acp_thread/src/submission.rs
@@ -1,6 +1,9 @@
use crate::ReceiptSessionSubmissions;
use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
-use futures::{channel::oneshot, future::BoxFuture};
+use futures::{
+ channel::oneshot,
+ future::{BoxFuture, LocalBoxFuture},
+};
use gpui::{SharedString, Task};
use std::collections::BTreeMap;
use std::{
@@ -28,6 +31,37 @@ pub enum SubmissionResponse {
Accepted(acp_v2::PromptResponse),
}
+/// The transport response and, for ordered transports, acknowledgement of model application.
+/// The shared tracker applies the outcome before acknowledging; transports must not
+/// wait for that acknowledgement before producing their response.
+pub struct ReceiptSubmission {
+ pub(crate) response: LocalBoxFuture<'static, anyhow::Result<acp_v2::PromptResponse>>,
+ pub(crate) applied: Option<oneshot::Sender<bool>>,
+}
+
+impl ReceiptSubmission {
+ /// The acknowledgement reports successful or failed model application.
+ /// Dropping it instead means application was abandoned.
+ pub fn ordered(
+ response: LocalBoxFuture<'static, anyhow::Result<acp_v2::PromptResponse>>,
+ applied: oneshot::Sender<bool>,
+ ) -> Self {
+ Self {
+ response,
+ applied: Some(applied),
+ }
+ }
+}
+
+impl From<Task<anyhow::Result<acp_v2::PromptResponse>>> for ReceiptSubmission {
+ fn from(response: Task<anyhow::Result<acp_v2::PromptResponse>>) -> Self {
+ Self {
+ response: Box::pin(response),
+ applied: None,
+ }
+ }
+}
+
/// A local receipt withdrawn by cancellation before the message was accepted.
#[derive(Debug)]
pub struct SubmissionCancelled;
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index c259ea64b38..a1807fc36e7 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -3309,24 +3309,26 @@ struct NativeSessionSubmissions {
}
impl acp_thread::ReceiptSessionSubmissions for NativeSessionSubmissions {
- fn prompt(
+ fn submit(
&self,
content: Vec<acp_v2::ContentBlock>,
- cx: &mut App,
- ) -> Task<Result<acp_v2::PromptResponse>> {
+ cx: &mut Context<acp_thread::AcpThread>,
+ ) -> acp_thread::ReceiptSubmission {
self.connection
.submit_native(self.session_id.clone(), Some(content), cx)
.0
+ .into()
}
fn supports_retry(&self) -> bool {
true
}
- fn retry(&self, cx: &mut App) -> Task<Result<acp_v2::PromptResponse>> {
+ fn retry(&self, cx: &mut Context<acp_thread::AcpThread>) -> acp_thread::ReceiptSubmission {
self.connection
.submit_native(self.session_id.clone(), None, cx)
.0
+ .into()
}
}
@@ -5131,14 +5133,10 @@ mod internal_tests {
"_future",
Default::default(),
));
- cx.update(|cx| {
- connection
- .receipt_submissions(&session_id, cx)
- .expect("native receipts")
- .prompt(vec![invalid], cx)
- })
- .await
- .expect_err("invalid follow-up must not cancel accepted work");
+ acp_thread
+ .update(cx, |thread, cx| thread.send(vec![invalid], cx))
+ .await
+ .expect_err("invalid follow-up must not cancel accepted work");
fake.send_text(&model, &request, "done");
fake.end_stream(&model, &request);
cx.run_until_parked();
@@ -5186,15 +5184,13 @@ mod internal_tests {
.expect("cancelled"),
acp_v2::StopReason::Cancelled
);
- let submissions = cx.update(|cx| {
- connection
- .receipt_submissions(&session_id, cx)
- .expect("native receipts")
- });
- let retry_receipt = cx
- .update(|cx| submissions.retry(cx))
+ let retry_receipt = acp_thread
+ .update(cx, |thread, cx| thread.retry(cx))
.await
.expect("retry accepted");
+ let Some(acp_thread::SubmissionResponse::Accepted(retry_receipt)) = retry_receipt else {
+ panic!("retry returns acceptance");
+ };
assert_eq!(retry_receipt.message_id, second_receipt.message_id);
cx.run_until_parked();
let saved = thread.read_with(cx, |thread, cx| thread.to_db(cx)).await;
@@ -5994,13 +5990,8 @@ mod internal_tests {
for text in ["ordinary prompt", "/compact"] {
let content = vec![text.into(), unknown.clone()];
assert!(connection.validate_prompt_content(&content).is_err());
- let error = cx
- .update(|cx| {
- connection
- .receipt_submissions(&session_id, cx)
- .expect("native receipts")
- .prompt(content, cx)
- })
+ let error = acp_thread
+ .update(cx, |thread, cx| thread.send(content, cx))
.await
.expect_err("unsupported content must not reach command dispatch or the model");
assert!(error.to_string().contains("Native agent does not support"));
diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs
index c600d0242fc..f89cab41839 100644
--- a/crates/agent/src/tests/mod.rs
+++ b/crates/agent/src/tests/mod.rs
@@ -4505,9 +4505,8 @@ async fn test_agent_connection(cx: &mut TestAppContext) {
let result = cx
.update(|cx| {
connection
- .receipt_submissions(&session_id, cx)
- .expect("native receipts")
- .prompt(vec!["ghi".into()], cx)
+ .submit_native(session_id.clone(), Some(vec!["ghi".into()]), cx)
+ .0
})
.await;
assert_eq!(
diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs
index 12981019ccc..e95d3aaf595 100644
--- a/crates/agent_servers/src/acp/v2.rs
+++ b/crates/agent_servers/src/acp/v2.rs
@@ -4,7 +4,10 @@ use super::{
enqueue_notification, first_class_terminal_auth_task, map_acp_error,
mcp_configurations_for_project, runtime, transport, with_v2_client_ingress,
};
-use acp_thread::{AcpThread, AgentConnection, AgentSessionConfigOptions, ElicitationStore};
+use acp_thread::{
+ AcpThread, AgentConnection, AgentSessionConfigOptions, ElicitationStore,
+ ReceiptSessionSubmissions, ReceiptSubmission, SubmissionDisconnected,
+};
use action_log::ActionLog;
use agent_client_protocol::{
Agent, Client, ConnectTo, JsonRpcRequest, Lines, V2ConnectionTo,
@@ -12,8 +15,12 @@ use agent_client_protocol::{
};
use anyhow::{Context as _, Result, anyhow};
use collections::HashMap;
-use futures::{FutureExt as _, channel::mpsc, future::Shared};
-use gpui::{App, AppContext as _, AsyncApp, Entity, SharedString, Task, WeakEntity};
+use futures::{
+ FutureExt as _,
+ channel::mpsc,
+ future::{LocalBoxFuture, Shared},
+};
+use gpui::{App, AppContext as _, AsyncApp, Context, Entity, SharedString, Task, WeakEntity};
use project::{AgentId, AgentServerStore, Project, agent_server_store::AgentServerCommand};
use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc};
use task::SpawnInTerminal;
@@ -48,7 +55,28 @@ fn finish_request(request_id: acp::RequestId, cx: &mut AsyncApp, context: &Clien
});
}
-/// An unselected v2 backend with initialization, auth and initial session/config support.
+#[derive(Debug, thiserror::Error)]
+#[error("ACP ordered response callback ended")]
+struct ResponseCallbackDropped;
+
+fn validate_prompt_content(
+ capabilities: &acp::PromptCapabilities,
+ content: &[acp::ContentBlock],
+) -> Result<()> {
+ for block in content {
+ let supported = match block {
+ acp::ContentBlock::Text(_) | acp::ContentBlock::ResourceLink(_) => true,
+ acp::ContentBlock::Image(_) => capabilities.image.is_some(),
+ acp::ContentBlock::Audio(_) => capabilities.audio.is_some(),
+ acp::ContentBlock::Resource(_) => capabilities.embedded_context.is_some(),
+ _ => false,
+ };
+ anyhow::ensure!(supported, "Prompt content is not supported by this agent");
+ }
+ Ok(())
+}
+
+/// An unselected v2 backend with auth, initial sessions/config and receipt-driven prompts.
pub struct AcpV2Connection {
id: AgentId,
connection: V2ConnectionTo<Agent>,
@@ -307,7 +335,19 @@ impl AcpV2Connection {
if self.initialize_response.capabilities.session.is_none() {
return Task::ready(Err(anyhow!("Sessions are not advertised by this agent")));
}
- self.scoped_request(request, cx)
+ if let Err(error) = self.validate_prompt_content(&request.prompt) {
+ return Task::ready(Err(error));
+ }
+ let response = Self::ordered_request(
+ &self.connection,
+ &self.dispatch_tx,
+ request,
+ || Ok(()),
+ |_| None,
+ |response, _| Ok(response),
+ cx,
+ );
+ cx.foreground_executor().spawn(response)
}
fn scoped_request<Request: JsonRpcRequest + 'static>(
@@ -417,30 +457,48 @@ impl AcpV2Connection {
.mcp_servers(servers))
}
- fn ordered_request<Request: JsonRpcRequest + 'static, Output: 'static>(
+ fn ordered_response<Request: JsonRpcRequest + 'static>(
connection: &V2ConnectionTo<Agent>,
dispatch_tx: &mpsc::UnboundedSender<ForegroundWork>,
request: Request,
preflight: impl FnOnce() -> Result<()> + 'static,
abandoned_session: fn(&Request::Response) -> Option<acp::SessionId>,
- apply: impl FnOnce(Request::Response, &mut AsyncApp) -> Result<Output> + 'static,
- cx: &App,
- ) -> Task<Result<Output>> {
+ ) -> (
+ LocalBoxFuture<'static, Result<Request::Response>>,
+ futures::channel::oneshot::Sender<bool>,
+ ) {
let connection = connection.clone();
let dispatch_tx = dispatch_tx.clone();
- cx.spawn(async move |cx| {
+ let (applied, application_finished) = futures::channel::oneshot::channel();
+ let response = async move {
preflight()?;
let (sender, received) = futures::channel::oneshot::channel();
- let (applied, application_finished) = futures::channel::oneshot::channel();
let request = connection.prepare_request(request);
let request_id = request.id().clone();
let cancellation = request.cancellation_handle();
enqueue_notification(&dispatch_tx, request_id.clone(), register_request);
let published = request.on_receiving_result({
let connection = connection.clone();
+ let dispatch_tx = dispatch_tx.clone();
+ let request_id = request_id.clone();
async move |result: Result<Request::Response, agent_client_protocol::Error>| {
let abandoned = result.as_ref().ok().and_then(abandoned_session);
- if !(sender.send(result).is_ok() && application_finished.await.is_ok())
+ let successful_response = result.is_ok();
+ let application = if sender.send(result).is_ok() {
+ application_finished.await.ok()
+ } else {
+ None
+ };
+ enqueue_notification(
+ &dispatch_tx,
+ request_id,
+ if successful_response && application == Some(true) {
+ finish_request
+ } else {
+ cancel_request_elicitations
+ },
+ );
+ if application.is_none()
&& let Some(session_id) = abandoned
{
// Register cleanup, but never await later traffic in an ordered callback.
@@ -452,6 +510,7 @@ impl AcpV2Connection {
})
.log_err();
}
+ drain_foreground_queue(&dispatch_tx).await.log_err();
Ok(())
}
});
@@ -467,32 +526,45 @@ impl AcpV2Connection {
enqueue_notification(&dispatch_tx, request_id, cancel_request_elicitations);
}
});
- let response = received
- .await
- .context("ACP ordered response callback ended")?
- .map_err(map_acp_error)?;
- match apply(response, cx) {
- Ok(output) => {
- enqueue_notification(&dispatch_tx, request_id, finish_request);
- // Keep abandonment cleanup armed until the result can be returned without yielding.
- drain_foreground_queue(&dispatch_tx).await?;
- applied.send(()).map_err(|_| {
- anyhow!("ACP response ordering callback ended before application")
- })?;
- guard.abort();
- Ok(output)
- }
- Err(error) => {
- enqueue_notification(&dispatch_tx, request_id, cancel_request_elicitations);
- // A rejected duplicate ID belongs to an existing owner, not an abandoned creation.
- applied.send(()).map_err(|_| {
- anyhow!("ACP response ordering callback ended before application")
- })?;
- guard.abort();
- Err(error)
- }
+ let response = received.await.context(ResponseCallbackDropped)?;
+ guard.abort();
+ response.map_err(map_acp_error)
+ }
+ .boxed_local();
+ (response, applied)
+ }
+
+ fn ordered_request<Request: JsonRpcRequest + 'static, Output: 'static>(
+ connection: &V2ConnectionTo<Agent>,
+ dispatch_tx: &mpsc::UnboundedSender<ForegroundWork>,
+ request: Request,
+ preflight: impl FnOnce() -> Result<()> + 'static,
+ abandoned_session: fn(&Request::Response) -> Option<acp::SessionId>,
+ apply: impl FnOnce(Request::Response, &mut AsyncApp) -> Result<Output> + 'static,
+ cx: &App,
+ ) -> LocalBoxFuture<'static, Result<Output>> {
+ let (response, applied) = Self::ordered_response(
+ connection,
+ dispatch_tx,
+ request,
+ preflight,
+ abandoned_session,
+ );
+ let dispatch_tx = dispatch_tx.clone();
+ let mut cx = cx.to_async();
+ async move {
+ let result = response.await.and_then(|response| apply(response, &mut cx));
+ if result.is_ok() {
+ drain_foreground_queue(&dispatch_tx).await?;
}
- })
+ if applied.send(result.is_ok()).is_err() && result.is_ok() {
+ return Err(anyhow!(
+ "ACP response ordering callback ended before application"
+ ));
+ }
+ result
+ }
+ .boxed_local()
}
}
@@ -535,7 +607,7 @@ impl AgentConnection for AcpV2Connection {
)
.collect::<Vec<_>>(),
);
- Self::ordered_request(
+ let response = Self::ordered_request(
&self.connection,
&self.dispatch_tx,
request,
@@ -612,7 +684,33 @@ impl AgentConnection for AcpV2Connection {
}
},
cx,
- )
+ );
+ cx.foreground_executor().spawn(response)
+ }
+
+ fn receipt_submissions(
+ &self,
+ session_id: &acp::SessionId,
+ _cx: &App,
+ ) -> Option<Rc<dyn ReceiptSessionSubmissions>> {
+ let session = self.initialize_response.capabilities.session.as_ref()?;
+ Some(Rc::new(V2SessionSubmissions {
+ session_id: session_id.clone(),
+ sessions: self.sessions.clone(),
+ capabilities: session.prompt.clone().unwrap_or_default(),
+ connection: self.connection.clone(),
+ dispatch_tx: self.dispatch_tx.clone(),
+ }))
+ }
+
+ fn validate_prompt_content(&self, content: &[acp::ContentBlock]) -> Result<()> {
+ let session = self
+ .initialize_response
+ .capabilities
+ .session
+ .as_ref()
+ .context("This agent does not advertise session support")?;
+ validate_prompt_content(&session.prompt.clone().unwrap_or_default(), content)
}
fn supports_session_additional_directories(&self) -> bool {
@@ -771,7 +869,7 @@ impl AgentSessionConfigOptions for V2SessionConfigOptions {
let value = value.clone();
move || this.validate(&config_id, &value)
};
- AcpV2Connection::ordered_request(
+ let response = AcpV2Connection::ordered_request(
&self.connection,
&self.dispatch_tx,
acp::SetSessionConfigOptionRequest::new(session_id.clone(), config_id, value),
@@ -800,7 +898,74 @@ impl AgentSessionConfigOptions for V2SessionConfigOptions {
Ok(response.config_options)
},
cx,
- )
+ );
+ cx.foreground_executor().spawn(response)
+ }
+}
+
+struct V2SessionSubmissions {
+ session_id: acp::SessionId,
+ sessions: Rc<RefCell<HashMap<acp::SessionId, AcpSession>>>,
+ capabilities: acp::PromptCapabilities,
+ connection: V2ConnectionTo<Agent>,
+ dispatch_tx: mpsc::UnboundedSender<ForegroundWork>,
+}
+
+impl V2SessionSubmissions {
+ fn request(
+ &self,
+ owner: WeakEntity<AcpThread>,
+ content: Vec<acp::ContentBlock>,
+ ) -> ReceiptSubmission {
+ if let Err(error) = validate_prompt_content(&self.capabilities, &content) {
+ return Task::ready(Err(error)).into();
+ }
+ let sessions = self.sessions.clone();
+ let session_id = self.session_id.clone();
+ let connection = self.connection.clone();
+ let (response, applied) = AcpV2Connection::ordered_response(
+ &self.connection,
+ &self.dispatch_tx,
+ acp::PromptRequest::new(self.session_id.clone(), content),
+ move || {
+ anyhow::ensure!(
+ owner.upgrade().is_some()
+ && sessions
+ .borrow()
+ .get(&session_id)
+ .is_some_and(|session| session.thread.entity_id() == owner.entity_id()),
+ "Session has been released or replaced"
+ );
+ Ok(())
+ },
+ |_| None,
+ );
+ let response = async move {
+ response.await.map_err(|error| {
+ if error.is::<ResponseCallbackDropped>()
+ || connection.is_incoming_closed()
+ || error
+ .downcast_ref::<agent_client_protocol::Error>()
+ .is_some_and(agent_client_protocol::is_incoming_transport_closed)
+ {
+ error.context(SubmissionDisconnected)
+ } else {
+ error
+ }
+ })
+ }
+ .boxed_local();
+ ReceiptSubmission::ordered(response, applied)
+ }
+}
+
+impl ReceiptSessionSubmissions for V2SessionSubmissions {
+ fn submit(
+ &self,
+ content: Vec<acp::ContentBlock>,
+ cx: &mut Context<AcpThread>,
+ ) -> ReceiptSubmission {
+ self.request(cx.entity().downgrade(), content)
}
}
@@ -841,6 +1006,7 @@ mod tests {
struct SessionHarness {
client: Rc<AcpV2Connection>,
project: Entity<Project>,
+ prompts: async_channel::Receiver<(acp::PromptRequest, Responder<acp::PromptResponse>)>,
new_requests: async_channel::Receiver<(acp::NewSessionRequest, acp::RequestId)>,
new_responses:
async_channel::Sender<Result<acp::NewSessionResponse, agent_client_protocol::Error>>,
@@ -878,6 +1044,7 @@ mod tests {
Result<acp::SetSessionConfigOptionResponse, agent_client_protocol::Error>,
>();
let (close_sender, closes) = async_channel::unbounded();
+ let (prompt_sender, prompts) = async_channel::unbounded();
let (sender, received) = futures::channel::oneshot::channel();
let (client_transport, agent_transport) = agent_client_protocol::Channel::duplex();
let agent_task = cx.background_spawn(
@@ -958,6 +1125,15 @@ mod tests {
},
agent_client_protocol::on_receive_request!(),
)
+ .on_receive_request(
+ async move |request: acp::PromptRequest, responder, _| {
+ prompt_sender
+ .try_send((request, responder))
+ .expect("prompt receiver");
+ Ok(())
+ },
+ agent_client_protocol::on_receive_request!(),
+ )
.connect_with(agent_transport, async move |agent| {
assert!(sender.send(agent).is_ok());
futures::future::pending::<Result<(), agent_client_protocol::Error>>().await
@@ -980,6 +1156,7 @@ mod tests {
Self {
client: Rc::new(client),
project,
+ prompts,
new_requests,
new_responses,
config_requests,
@@ -1047,6 +1224,334 @@ mod tests {
.meta(meta("delivery-not-session"))
}
+ #[gpui::test]
+ async fn v2_receipt_sdk_correlates_echoes_without_completing_activity(cx: &mut TestAppContext) {
+ use acp_thread::{
+ AgentThreadEntry, ForegroundActivity, SubmissionResponse, SubmissionState,
+ };
+ for echo_first in [true, false] {
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let thread = harness.thread(cx).await;
+ assert!(thread.read_with(cx, |thread, _| thread.uses_reported_activity()));
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ harness
+ .agent
+ .send_notification(acp::UpdateSessionNotification::new(
+ session_id.clone(),
+ acp::SessionUpdate::StateUpdate(acp::StateUpdate::Running(
+ acp::RunningStateUpdate::new(),
+ )),
+ ))
+ .expect("autonomous running");
+ cx.run_until_parked();
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.foreground_activity()),
+ ForegroundActivity::Running
+ );
+ let content = vec![acp::ContentBlock::from("question")];
+ let submission = thread.update(cx, |thread, cx| thread.send(content.clone(), cx));
+ let submission_id = submission.id;
+ let (request, responder) = bounded(harness.prompts.recv(), cx).await.expect("prompt");
+ assert_eq!(request.prompt, content);
+ assert_eq!(request.session_id, session_id);
+ let echo = acp::UpdateSessionNotification::new(
+ session_id.clone(),
+ acp::SessionUpdate::UserMessage(
+ acp::UserMessage::new("message").content(content.clone()),
+ ),
+ );
+ if echo_first {
+ harness
+ .agent
+ .send_notification(echo.clone())
+ .expect("early echo");
+ }
+ let receipt = acp::PromptResponse::new("message").meta(meta("receipt"));
+ responder.respond(receipt.clone()).expect("acceptance");
+ assert!(matches!(bounded(submission, cx).await.expect("receipt"),
+ Some(SubmissionResponse::Accepted(accepted)) if accepted == receipt));
+ if !echo_first {
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.submission(submission_id).expect("un-echoed").state,
+ SubmissionState::Accepted { echoed: false, .. }
+ ));
+ });
+ harness.agent.send_notification(echo).expect("late echo");
+ }
+ cx.run_until_parked();
+ thread.read_with(cx, |thread, _| {
+ let [AgentThreadEntry::UserMessage(message)] = thread.entries() else {
+ panic!("one authoritative user message");
+ };
+ assert_eq!(message.content.source_blocks(), content.as_slice());
+ assert!(matches!(
+ thread.submission(submission_id).expect("echoed").state,
+ SubmissionState::Accepted { echoed: true, .. }
+ ));
+ assert_eq!(thread.foreground_activity(), ForegroundActivity::Running);
+ });
+ for state in [
+ acp::StateUpdate::RequiresAction(acp::RequiresActionStateUpdate::new()),
+ acp::StateUpdate::Idle(
+ acp::IdleStateUpdate::new().stop_reason(acp::StopReason::EndTurn),
+ ),
+ ] {
+ harness
+ .agent
+ .send_notification(acp::UpdateSessionNotification::new(
+ session_id.clone(),
+ acp::SessionUpdate::StateUpdate(state),
+ ))
+ .expect("reported state with no prompt RPC");
+ cx.run_until_parked();
+ }
+ assert_eq!(
+ thread.read_with(cx, |thread, _| thread.foreground_activity()),
+ ForegroundActivity::Idle
+ );
+ }
+ }
+
+ #[gpui::test]
+ async fn v2_receipt_sdk_holds_later_traffic_until_model_application(cx: &mut TestAppContext) {
+ use acp_thread::SubmissionState;
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let thread = harness.thread(cx).await;
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ let content = vec![acp::ContentBlock::from("question")];
+ let (response, applied) = AcpV2Connection::ordered_response(
+ &harness.client.connection,
+ &harness.client.dispatch_tx,
+ acp::PromptRequest::new(session_id.clone(), content.clone()),
+ || Ok(()),
+ |_| None,
+ );
+ let (delivered, received) = futures::channel::oneshot::channel();
+ let (release, held) = futures::channel::oneshot::channel();
+ let request = ReceiptSubmission::ordered(
+ async move {
+ let response = response.await;
+ delivered.send(()).expect("receipt delivery");
+ held.await.expect("application gate");
+ response
+ }
+ .boxed_local(),
+ applied,
+ );
+ let submission = thread.update(cx, |thread, cx| {
+ thread.submit_receipt(content.clone(), request, cx)
+ });
+ let id = submission.id;
+ drop(submission);
+ let (_, responder) = bounded(harness.prompts.recv(), cx).await.expect("prompt");
+ responder
+ .respond(acp::PromptResponse::new("message"))
+ .expect("acceptance");
+ harness
+ .agent
+ .send_notification(acp::UpdateSessionNotification::new(
+ session_id,
+ acp::SessionUpdate::UserMessage(acp::UserMessage::new("message").content(content)),
+ ))
+ .expect("following echo");
+ bounded(received, cx)
+ .await
+ .expect("transport received receipt");
+ cx.run_until_parked();
+ thread.read_with(cx, |thread, _| {
+ assert!(
+ thread.entries().is_empty(),
+ "later traffic must wait for model application"
+ );
+ assert!(matches!(
+ thread.submission(id).expect("pending").state,
+ SubmissionState::Pending
+ ));
+ });
+ release.send(()).expect("apply receipt");
+ cx.run_until_parked();
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(thread.entries().len(), 1);
+ assert!(matches!(
+ thread.submission(id).expect("echoed").state,
+ SubmissionState::Accepted { echoed: true, .. }
+ ));
+ });
+ }
+
+ #[gpui::test]
+ async fn v2_receipt_sdk_distinguishes_preflight_rejection_and_transport_loss(
+ cx: &mut TestAppContext,
+ ) {
+ use acp_thread::{SubmissionDisconnected, SubmissionState};
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let thread = harness.thread(cx).await;
+ let unsupported: acp::ContentBlock = serde_json::from_value(json!({
+ "type": "image", "data": "AA==", "mimeType": "image/png"
+ }))
+ .expect("image content");
+ let submission = thread.update(cx, |thread, cx| thread.send(vec![unsupported], cx));
+ assert!(bounded(submission, cx).await.is_err());
+ assert!(harness.prompts.is_empty(), "preflight must not publish");
+ let rejected = thread.update(cx, |thread, cx| thread.send(vec!["rejected".into()], cx));
+ let rejected_id = rejected.id;
+ let (_, responder) = bounded(harness.prompts.recv(), cx).await.expect("prompt");
+ let rejection =
+ agent_client_protocol::Error::invalid_params().data(json!({"reason": "not inserted"}));
+ responder
+ .respond_with_error(rejection.clone())
+ .expect("reject");
+ let error = bounded(rejected, cx).await.expect_err("wire rejection");
+ assert_eq!(
+ error.downcast_ref::<agent_client_protocol::Error>(),
+ Some(&rejection)
+ );
+ let pending = thread.update(cx, |thread, cx| thread.send(vec!["unknown".into()], cx));
+ let pending_id = pending.id;
+ let (_, _responder) = bounded(harness.prompts.recv(), cx)
+ .await
+ .expect("pending prompt");
+ drop(harness._agent_task);
+ drop(harness.agent);
+ let error = bounded(pending, cx).await.expect_err("EOF");
+ assert!(
+ error.is::<SubmissionDisconnected>()
+ || error
+ .downcast_ref::<agent_client_protocol::Error>()
+ .is_some_and(agent_client_protocol::is_incoming_transport_closed)
+ );
+ bounded(harness.client.connection.incoming_closed(), cx).await;
+ thread.read_with(cx, |thread, _| {
+ assert!(matches!(
+ thread.submission(rejected_id).expect("rejection").state,
+ SubmissionState::Failed(_)
+ ));
+ assert!(matches!(
+ thread.submission(pending_id).expect("uncertain").state,
+ SubmissionState::Disconnected { receipt: None }
+ ));
+ assert!(!thread.has_unsettled_submissions());
+ });
+ assert!(harness.prompts.is_empty(), "loss must not resend");
+ }
+
+ #[gpui::test]
+ async fn v2_receipt_sdk_rechecks_owner_before_publication(cx: &mut TestAppContext) {
+ let harness = SessionHarness::new(session_capabilities(), vec![], vec![], cx).await;
+ let thread = harness.thread(cx).await;
+ harness.client.sessions.borrow_mut().clear();
+ let replacement = harness.thread(cx).await;
+ let stale = thread.update(cx, |thread, cx| thread.send(vec!["stale owner".into()], cx));
+ cx.run_until_parked();
+ assert!(
+ harness.prompts.is_empty(),
+ "a stale owner cannot submit through its replacement"
+ );
+ assert!(bounded(stale, cx).await.is_err());
+
+ let submission =
+ replacement.update(cx, |thread, cx| thread.send(vec!["not sent".into()], cx));
+ harness.client.sessions.borrow_mut().clear();
+ assert!(bounded(submission, cx).await.is_err());
+ assert!(harness.prompts.is_empty());
+ }
+
+ #[cfg(unix)]
+ #[gpui::test]
+ async fn v2_receipt_stdio_preserves_acceptance_before_immediate_eof(cx: &mut TestAppContext) {
+ use acp_thread::{SubmissionResponse, SubmissionState};
+ cx.update(|cx| {
+ let store = settings::SettingsStore::test(cx);
+ cx.set_global(store);
+ release_channel::init("0.0.0".parse().expect("version"), cx);
+ });
+ cx.executor().allow_parking();
+ let directory = tempfile::tempdir().expect("working directory");
+ let project = Project::example([directory.path()], &mut cx.to_async()).await;
+ let client = bounded(AcpV2Connection::stdio(
+ AgentId::new("receipt-stdio"), project.clone(),
+ AgentServerCommand {
+ path: "/bin/sh".into(),
+ args: vec!["-c".into(), r#"
+while IFS= read -r request; do
+ id=${request#*\"id\":}
+ id=${id%%,*}
+ case "$request" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":2,"info":{"name":"receipt-agent","version":"1"},"capabilities":{"session":{}}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"stdio-session"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"messageId":"accepted","_meta":{"scope":"receipt"}}}\n' "$id"
+ exit 0
+ ;;
+ *) exit 43 ;;
+ esac
+done
+"#.into()],
+ env: None,
+ },
+ WeakEntity::new_invalid(), &mut cx.to_async(),
+ ), cx).await.expect("stdio connection");
+ let client = Rc::new(client);
+ let creation = cx.update(|cx| {
+ client
+ .clone()
+ .new_session(project, PathList::new(&[directory.path()]), cx)
+ });
+ let thread = bounded(creation, cx).await.expect("stdio owner");
+ let submission = thread.update(cx, |thread, cx| thread.send(vec!["question".into()], cx));
+ let id = submission.id;
+ let expected = acp::PromptResponse::new("accepted").meta(meta("receipt"));
+ assert!(
+ matches!(bounded(submission, cx).await.expect("acceptance before EOF"),
+ Some(SubmissionResponse::Accepted(receipt)) if receipt == expected)
+ );
+ bounded(client.connection.incoming_closed(), cx).await;
+ bounded(drain_foreground_queue(&client.dispatch_tx), cx)
+ .await
+ .expect("disconnect barrier");
+ thread.read_with(cx, |thread, _| {
+ assert!(
+ matches!(&thread.submission(id).expect("retained acceptance").state,
+ SubmissionState::Disconnected { receipt: Some(receipt) } if receipt == &expected)
+ );
+ assert!(!thread.has_unsettled_submissions());
+ });
+ }
+
+ #[test]
+ fn v2_receipt_content_extensions_require_capabilities() {
+ for (block, capabilities) in [
+ (
+ json!({"type":"image","data":"AA==","mimeType":"image/png"}),
+ acp::PromptCapabilities::new().image(acp::PromptImageCapabilities::new()),
+ ),
+ (
+ json!({"type":"audio","data":"AA==","mimeType":"audio/wav"}),
+ acp::PromptCapabilities::new().audio(acp::PromptAudioCapabilities::new()),
+ ),
+ (
+ json!({"type":"resource","resource":{"uri":"file:///context","text":"context"}}),
+ acp::PromptCapabilities::new()
+ .embedded_context(acp::PromptEmbeddedContextCapabilities::new()),
+ ),
+ ] {
+ let block = serde_json::from_value(block).expect("prompt block");
+ assert!(
+ validate_prompt_content(
+ &acp::PromptCapabilities::default(),
+ std::slice::from_ref(&block)
+ )
+ .is_err()
+ );
+ assert!(validate_prompt_content(&capabilities, &[block]).is_ok());
+ }
+ }
+
#[gpui::test]
async fn v2_session_sdk_registers_initial_state_before_immediate_notifications(
cx: &mut TestAppContext,
@@ -1099,8 +1604,9 @@ mod tests {
harness
.client
.receipt_submissions(thread.session_id(), cx)
- .is_none()
+ .is_some()
);
+ assert!(thread.uses_reported_activity());
assert!(
!harness.client.supports_load_session() && !harness.client.supports_close_session()
);
@@ -1433,7 +1939,8 @@ mod tests {
.config_options
.borrow_mut()
.clear();
- assert!(bounded(setting, cx).await.is_err());
+ let error = bounded(setting, cx).await.expect_err("stale config");
+ assert!(error.to_string().contains("not offered"), "{error}");
assert!(
harness.config_requests.is_empty(),
"stale preflight must not publish a config RPC"