Skip to content

armgit / zed

Public Imported from GitHub
0

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

acp_thread: Adopt shared ACP v2 content values (#64765)

Ben Brandtee43be113e36
diff --git a/Cargo.toml b/Cargo.toml
index a2c9a4e4c44..1d44d21597f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -522,7 +522,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] }
accesskit_macos = "0.26.0"
accesskit_unix = "0.22"
accesskit_windows = "0.34"
-agent-client-protocol = { version = "=2.2.0", features = ["unstable"] }
+agent-client-protocol = { version = "=2.2.0", features = ["unstable", "unstable_protocol_v2"] }
aho-corasick = "1.1"
alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" }
any_vec = "0.14"
diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs
index cb3872789d9..e22a738ec04 100644
--- a/crates/acp_thread/src/acp_thread.rs
+++ b/crates/acp_thread/src/acp_thread.rs
@@ -1,10 +1,11 @@
mod connection;
+pub mod content;
mod diff;
mod mention;
mod terminal;
pub use ::terminal::HeadlessTerminal;
use action_log::{ActionLog, ActionLogTelemetry};
-use agent_client_protocol::schema::{MaybeUndefined, v1 as acp};
+use agent_client_protocol::schema::{MaybeUndefined, v1 as acp_v1, v2 as acp_v2};
use agent_settings::AgentSettings;
use anyhow::{Context as _, Result, anyhow};
use collections::HashSet;
@@ -67,7 +68,7 @@ impl std::error::Error for MaxOutputTokensError {}
pub const TOOL_NAME_META_KEY: &str = "tool_name";
/// Extracts a tool name from the legacy ACP metadata field.
-pub fn tool_name_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
+pub fn tool_name_from_meta(meta: &Option<acp_v1::Meta>) -> Option<SharedString> {
meta.as_ref()
.and_then(|meta| meta.get(TOOL_NAME_META_KEY))
.and_then(|value| value.as_str())
@@ -75,8 +76,8 @@ pub fn tool_name_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
}
/// Creates ACP metadata containing the legacy tool-name field.
-pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta {
- acp::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])
+pub fn meta_with_tool_name(tool_name: &str) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(TOOL_NAME_META_KEY.into(), tool_name.into())])
}
/// Key used in ACP `AvailableCommand` meta to record which source produced a
@@ -111,11 +112,11 @@ impl CommandCategory {
}
}
-pub fn meta_with_command_category(category: CommandCategory) -> acp::Meta {
- acp::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), category.as_str().into())])
+pub fn meta_with_command_category(category: CommandCategory) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), category.as_str().into())])
}
-pub fn command_category_from_meta(meta: &Option<acp::Meta>) -> Option<CommandCategory> {
+pub fn command_category_from_meta(meta: &Option<acp_v1::Meta>) -> Option<CommandCategory> {
meta.as_ref()
.and_then(|m| m.get(COMMAND_CATEGORY_META_KEY))
.and_then(|v| v.as_str())
@@ -195,15 +196,15 @@ pub struct SandboxAuthorizationDetails {
pub reason: String,
}
-pub fn meta_with_sandbox_authorization(details: SandboxAuthorizationDetails) -> acp::Meta {
- acp::Meta::from_iter([(
+pub fn meta_with_sandbox_authorization(details: SandboxAuthorizationDetails) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(
SANDBOX_AUTHORIZATION_META_KEY.into(),
serde_json::to_value(details).unwrap_or_default(),
)])
}
pub fn sandbox_authorization_details_from_meta(
- meta: &Option<acp::Meta>,
+ meta: &Option<acp_v1::Meta>,
) -> Option<SandboxAuthorizationDetails> {
meta.as_ref()
.and_then(|m| m.get(SANDBOX_AUTHORIZATION_META_KEY))
@@ -239,15 +240,15 @@ pub struct SandboxFallbackAuthorizationDetails {
pub fn meta_with_sandbox_fallback_authorization(
details: SandboxFallbackAuthorizationDetails,
-) -> acp::Meta {
- acp::Meta::from_iter([(
+) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(
SANDBOX_FALLBACK_AUTHORIZATION_META_KEY.into(),
serde_json::to_value(details).unwrap_or_default(),
)])
}
pub fn sandbox_fallback_authorization_details_from_meta(
- meta: &Option<acp::Meta>,
+ meta: &Option<acp_v1::Meta>,
) -> Option<SandboxFallbackAuthorizationDetails> {
meta.as_ref()
.and_then(|m| m.get(SANDBOX_FALLBACK_AUTHORIZATION_META_KEY))
@@ -260,14 +261,16 @@ pub fn sandbox_fallback_authorization_details_from_meta(
/// used to explain the situation to both the user and the agent.
pub const SANDBOX_NOT_APPLIED_META_KEY: &str = "sandbox_not_applied";
-pub fn meta_with_sandbox_not_applied(reason: &SandboxNotAppliedReason) -> acp::Meta {
- acp::Meta::from_iter([(
+pub fn meta_with_sandbox_not_applied(reason: &SandboxNotAppliedReason) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(
SANDBOX_NOT_APPLIED_META_KEY.into(),
serde_json::to_value(reason).unwrap_or_default(),
)])
}
-pub fn sandbox_not_applied_from_meta(meta: &Option<acp::Meta>) -> Option<SandboxNotAppliedReason> {
+pub fn sandbox_not_applied_from_meta(
+ meta: &Option<acp_v1::Meta>,
+) -> Option<SandboxNotAppliedReason> {
meta.as_ref()
.and_then(|m| m.get(SANDBOX_NOT_APPLIED_META_KEY))
.and_then(|v| serde_json::from_value(v.clone()).ok())
@@ -276,7 +279,7 @@ pub fn sandbox_not_applied_from_meta(meta: &Option<acp::Meta>) -> Option<Sandbox
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SubagentSessionInfo {
/// The session id of the subagent sessiont that was spawned
- pub session_id: acp::SessionId,
+ pub session_id: acp_v1::SessionId,
/// The index of the message of the start of the "turn" run by this tool call
pub message_start_index: usize,
/// The index of the output of the message that the subagent has returned
@@ -285,7 +288,7 @@ pub struct SubagentSessionInfo {
}
/// Helper to extract subagent session id from ACP meta
-pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<SubagentSessionInfo> {
+pub fn subagent_session_info_from_meta(meta: &Option<acp_v1::Meta>) -> Option<SubagentSessionInfo> {
meta.as_ref()
.and_then(|m| m.get(SUBAGENT_SESSION_INFO_META_KEY))
.and_then(|v| serde_json::from_value(v.clone()).ok())
@@ -293,7 +296,7 @@ pub fn subagent_session_info_from_meta(meta: &Option<acp::Meta>) -> Option<Subag
#[derive(Debug)]
pub struct UserMessage {
- pub protocol_id: Option<acp::MessageId>,
+ pub protocol_id: Option<acp_v1::MessageId>,
pub client_id: Option<ClientUserMessageId>,
pub is_optimistic: bool,
pub content: MessageContent,
@@ -348,11 +351,11 @@ impl AssistantMessage {
#[derive(Debug, PartialEq)]
pub enum AssistantMessageChunk {
Message {
- id: Option<acp::MessageId>,
+ id: Option<acp_v1::MessageId>,
block: MessageContent,
},
Thought {
- id: Option<acp::MessageId>,
+ id: Option<acp_v1::MessageId>,
block: MessageContent,
},
}
@@ -381,8 +384,8 @@ impl AssistantMessageChunk {
}
fn can_merge_message_chunks(
- existing: Option<&acp::MessageId>,
- incoming: Option<&acp::MessageId>,
+ existing: Option<&acp_v1::MessageId>,
+ incoming: Option<&acp_v1::MessageId>,
) -> bool {
match (existing, incoming) {
(Some(existing), Some(incoming)) => existing == incoming,
@@ -405,14 +408,14 @@ pub struct ElicitationEntryId(pub Arc<str>);
#[derive(Debug)]
pub struct Elicitation {
pub id: ElicitationEntryId,
- pub request: acp::CreateElicitationRequest,
+ pub request: acp_v1::CreateElicitationRequest,
pub status: ElicitationStatus,
}
#[derive(Debug)]
pub enum ElicitationStatus {
Pending {
- respond_tx: oneshot::Sender<acp::CreateElicitationResponse>,
+ respond_tx: oneshot::Sender<acp_v1::CreateElicitationResponse>,
},
Accepted,
Declined,
@@ -445,19 +448,19 @@ impl ElicitationStore {
&self.elicitations
}
- fn validate_request(request: &acp::CreateElicitationRequest) -> Result<(), acp::Error> {
+ fn validate_request(request: &acp_v1::CreateElicitationRequest) -> Result<(), acp_v1::Error> {
match &request.mode {
- acp::ElicitationMode::Form(_) => {}
- acp::ElicitationMode::Url(mode) => {
+ acp_v1::ElicitationMode::Form(_) => {}
+ acp_v1::ElicitationMode::Url(mode) => {
let url = url::Url::parse(&mode.url)
- .map_err(|_| acp::Error::invalid_params().data("invalid elicitation URL"))?;
+ .map_err(|_| acp_v1::Error::invalid_params().data("invalid elicitation URL"))?;
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
- return Err(acp::Error::invalid_params()
+ return Err(acp_v1::Error::invalid_params()
.data("elicitation URL must use HTTP or HTTPS and include a host"));
}
}
_ => {
- return Err(acp::Error::invalid_params().data("unsupported elicitation mode"));
+ return Err(acp_v1::Error::invalid_params().data("unsupported elicitation mode"));
}
}
@@ -466,10 +469,10 @@ impl ElicitationStore {
fn insert_pending_elicitation(
&mut self,
- request: acp::CreateElicitationRequest,
+ request: acp_v1::CreateElicitationRequest,
) -> (
ElicitationEntryId,
- oneshot::Receiver<acp::CreateElicitationResponse>,
+ oneshot::Receiver<acp_v1::CreateElicitationResponse>,
) {
let (respond_tx, response_rx) = oneshot::channel();
let id = ElicitationEntryId(Uuid::new_v4().to_string().into());
@@ -482,12 +485,12 @@ impl ElicitationStore {
}
fn response_task(
- response_rx: oneshot::Receiver<acp::CreateElicitationResponse>,
+ response_rx: oneshot::Receiver<acp_v1::CreateElicitationResponse>,
cx: &App,
- ) -> Task<acp::CreateElicitationResponse> {
+ ) -> Task<acp_v1::CreateElicitationResponse> {
cx.foreground_executor().spawn(async move {
response_rx.await.unwrap_or_else(|oneshot::Canceled| {
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel)
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Cancel)
})
})
}
@@ -501,7 +504,7 @@ impl ElicitationStore {
fn respond_to_elicitation_entry(
elicitation: &mut Elicitation,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
) -> bool {
if !matches!(elicitation.status, ElicitationStatus::Pending { .. }) {
return false;
@@ -536,8 +539,8 @@ impl ElicitationStore {
match mem::replace(&mut elicitation.status, ElicitationStatus::Canceled) {
ElicitationStatus::Pending { respond_tx } => {
if respond_tx
- .send(acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Cancel,
+ .send(acp_v1::CreateElicitationResponse::new(
+ acp_v1::ElicitationAction::Cancel,
))
.is_err()
{
@@ -546,7 +549,7 @@ impl ElicitationStore {
Some(ElicitationChange::Responded)
}
ElicitationStatus::Accepted
- if matches!(&elicitation.request.mode, acp::ElicitationMode::Url(_)) =>
+ if matches!(&elicitation.request.mode, acp_v1::ElicitationMode::Url(_)) =>
{
Some(ElicitationChange::Updated)
}
@@ -560,7 +563,7 @@ impl ElicitationStore {
fn respond_to_elicitation_by_id(
&mut self,
id: &ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
) -> bool {
let Some((_, elicitation)) = self.elicitation_mut(id) else {
return false;
@@ -582,18 +585,18 @@ impl ElicitationStore {
pub fn request_elicitation(
&mut self,
- request: acp::CreateElicitationRequest,
+ request: acp_v1::CreateElicitationRequest,
cx: &mut Context<Self>,
- ) -> Result<Task<acp::CreateElicitationResponse>, acp::Error> {
+ ) -> Result<Task<acp_v1::CreateElicitationResponse>, acp_v1::Error> {
self.request_elicitation_with_id(request, cx)
.map(|(_, task)| task)
}
pub fn request_elicitation_with_id(
&mut self,
- request: acp::CreateElicitationRequest,
+ request: acp_v1::CreateElicitationRequest,
cx: &mut Context<Self>,
- ) -> Result<(ElicitationEntryId, Task<acp::CreateElicitationResponse>), acp::Error> {
+ ) -> Result<(ElicitationEntryId, Task<acp_v1::CreateElicitationResponse>), acp_v1::Error> {
Self::validate_request(&request)?;
let (id, response_rx) = self.insert_pending_elicitation(request);
cx.emit(ElicitationStoreEvent::ElicitationRequested(id.clone()));
@@ -606,7 +609,7 @@ impl ElicitationStore {
pub fn respond_to_elicitation(
&mut self,
id: &ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
cx: &mut Context<Self>,
) {
if !self.respond_to_elicitation_by_id(id, response) {
@@ -619,7 +622,7 @@ impl ElicitationStore {
pub fn complete_url_elicitation(
&mut self,
- elicitation_id: &acp::ElicitationId,
+ elicitation_id: &acp_v1::ElicitationId,
cx: &mut Context<Self>,
) {
let Some(entry_id) = self.entry_id_for_url_elicitation(elicitation_id) else {
@@ -664,7 +667,7 @@ impl ElicitationStore {
let keep = matches!(
(&elicitation.status, &elicitation.request.mode),
(ElicitationStatus::Pending { .. }, _)
- | (ElicitationStatus::Accepted, acp::ElicitationMode::Url(_))
+ | (ElicitationStatus::Accepted, acp_v1::ElicitationMode::Url(_))
);
if !keep {
cleared_ids.push(elicitation.id.clone());
@@ -682,11 +685,11 @@ impl ElicitationStore {
cleared_ids
}
- pub fn cancel_request(&mut self, request_id: &acp::RequestId, cx: &mut Context<Self>) {
+ pub fn cancel_request(&mut self, request_id: &acp_v1::RequestId, cx: &mut Context<Self>) {
let changes = self.cancel_pending(|elicitation| {
matches!(
elicitation.request.scope(),
- acp::ElicitationScope::Request(scope) if &scope.request_id == request_id
+ acp_v1::ElicitationScope::Request(scope) if &scope.request_id == request_id
)
});
for (id, change) in changes {
@@ -707,10 +710,10 @@ impl ElicitationStore {
fn entry_id_for_url_elicitation(
&self,
- elicitation_id: &acp::ElicitationId,
+ elicitation_id: &acp_v1::ElicitationId,
) -> Option<ElicitationEntryId> {
self.elicitations.iter().rev().find_map(|elicitation| {
- if let acp::ElicitationMode::Url(mode) = &elicitation.request.mode
+ if let acp_v1::ElicitationMode::Url(mode) = &elicitation.request.mode
&& &mode.elicitation_id == elicitation_id
{
Some(elicitation.id.clone())
@@ -758,14 +761,14 @@ pub enum ContextCompactionStatus {
Other(Arc<str>),
}
-impl From<acp::CompactionStatus> for ContextCompactionStatus {
- fn from(status: acp::CompactionStatus) -> Self {
+impl From<acp_v1::CompactionStatus> for ContextCompactionStatus {
+ fn from(status: acp_v1::CompactionStatus) -> Self {
match status {
- acp::CompactionStatus::InProgress => Self::InProgress,
- acp::CompactionStatus::Completed => Self::Completed,
- acp::CompactionStatus::Failed => Self::Failed,
- acp::CompactionStatus::Cancelled => Self::Canceled,
- acp::CompactionStatus::Other(status) => Self::Other(status.into()),
+ acp_v1::CompactionStatus::InProgress => Self::InProgress,
+ acp_v1::CompactionStatus::Completed => Self::Completed,
+ acp_v1::CompactionStatus::Failed => Self::Failed,
+ acp_v1::CompactionStatus::Cancelled => Self::Canceled,
+ acp_v1::CompactionStatus::Other(status) => Self::Other(status.into()),
_ => Self::Other("unknown".into()),
}
}
@@ -789,12 +792,22 @@ impl ContextCompaction {
fn apply_update(
&mut self,
- update: acp::CompactionUpdate,
+ update: acp_v1::CompactionUpdate,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
- ) {
+ ) -> Result<()> {
+ let summary = match update.summary {
+ MaybeUndefined::Undefined => MaybeUndefined::Undefined,
+ MaybeUndefined::Null => MaybeUndefined::Null,
+ MaybeUndefined::Value(blocks) => MaybeUndefined::Value(
+ blocks
+ .into_iter()
+ .map(content::from_v1)
+ .collect::<Result<Vec<_>>>()?,
+ ),
+ };
self.status = update.status.into();
- match update.summary {
+ match summary {
MaybeUndefined::Undefined => {}
MaybeUndefined::Null => self.summary.clear(),
MaybeUndefined::Value(blocks) => {
@@ -815,15 +828,16 @@ impl ContextCompaction {
}
}
}
+ Ok(())
}
fn append_summary(
&mut self,
- content: acp::ContentBlock,
+ content: acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
) {
- if let acp::ContentBlock::Text(text) = &content
+ if let acp_v2::ContentBlock::Text(text) = &content
&& let Some(markdown) = self.summary.last().and_then(ContentBlock::plain_markdown)
{
markdown.update(cx, |markdown, cx| markdown.append(&text.text, cx));
@@ -906,7 +920,7 @@ impl AgentThreadEntry {
}
}
- pub fn location(&self, ix: usize) -> Option<(acp::ToolCallLocation, AgentLocation)> {
+ pub fn location(&self, ix: usize) -> Option<(acp_v1::ToolCallLocation, AgentLocation)> {
if let AgentThreadEntry::ToolCall(ToolCall {
locations,
resolved_locations,
@@ -925,13 +939,13 @@ impl AgentThreadEntry {
#[derive(Debug)]
pub struct ToolCall {
- pub id: acp::ToolCallId,
+ pub id: acp_v1::ToolCallId,
pub label: Entity<Markdown>,
title: Option<SharedString>,
- pub kind: acp::ToolKind,
+ pub kind: acp_v1::ToolKind,
structured_content: Vec<ToolCallContent>,
pub status: ToolCallStatus,
- pub locations: Vec<acp::ToolCallLocation>,
+ pub locations: Vec<acp_v1::ToolCallLocation>,
pub resolved_locations: Vec<Option<AgentLocation>>,
pub raw_input: Option<serde_json::Value>,
pub raw_input_markdown: Option<Entity<Markdown>>,
@@ -949,10 +963,10 @@ pub struct ToolCall {
impl ToolCall {
fn from_acp(
- tool_call: acp::ToolCall,
+ tool_call: acp_v1::ToolCall,
status: ToolCallStatus,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
cx: &mut App,
) -> Result<Self> {
let title =
@@ -1017,7 +1031,7 @@ impl ToolCall {
fn label_text(
title: Option<&SharedString>,
tool_name: Option<&SharedString>,
- kind: acp::ToolKind,
+ kind: acp_v1::ToolKind,
) -> SharedString {
let Some(title) = title else {
return tool_name
@@ -1026,9 +1040,9 @@ impl ToolCall {
.unwrap_or_else(|| "Tool call".into());
};
- if kind == acp::ToolKind::Execute {
+ if kind == acp_v1::ToolKind::Execute {
title.clone()
- } else if kind == acp::ToolKind::Edit {
+ } else if kind == acp_v1::ToolKind::Edit {
MarkdownEscaped(title).to_string().into()
} else if let Some((first_line, _)) = title.split_once('\n') {
(first_line.to_owned() + "…").into()
@@ -1040,13 +1054,13 @@ impl ToolCall {
fn new_label(
title: Option<&SharedString>,
tool_name: Option<&SharedString>,
- kind: acp::ToolKind,
+ kind: acp_v1::ToolKind,
language_registry: Arc<LanguageRegistry>,
cx: &mut App,
) -> Entity<Markdown> {
let text = Self::label_text(title, tool_name, kind);
cx.new(|cx| {
- if title.is_none() || kind == acp::ToolKind::Execute {
+ if title.is_none() || kind == acp_v1::ToolKind::Execute {
Markdown::new_text(text, cx)
} else {
Markdown::new(text, Some(language_registry), None, cx)
@@ -1056,13 +1070,13 @@ impl ToolCall {
fn update_fields(
&mut self,
- fields: acp::ToolCallUpdateFields,
- meta: Option<acp::Meta>,
+ fields: acp_v1::ToolCallUpdateFields,
+ meta: Option<acp_v1::Meta>,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
cx: &mut App,
) -> Result<()> {
- let acp::ToolCallUpdateFields {
+ let acp_v1::ToolCallUpdateFields {
kind,
status,
title,
@@ -1075,7 +1089,7 @@ impl ToolCall {
} = fields;
let output_changed = content.is_some() || raw_output.is_some();
- let was_plain_text = self.title.is_none() || self.kind == acp::ToolKind::Execute;
+ let was_plain_text = self.title.is_none() || self.kind == acp_v1::ToolKind::Execute;
let mut label_changed = title.is_some() || kind.is_some();
if let Some(kind) = kind {
self.kind = kind;
@@ -1114,7 +1128,7 @@ impl ToolCall {
if let Some(title) = title {
self.title = Some(SharedString::from(title)).filter(|title| !title.trim().is_empty());
- if self.kind == acp::ToolKind::Execute
+ if self.kind == acp_v1::ToolKind::Execute
&& let Some(title) = &self.title
{
// A missing tool title must not overwrite an actual terminal command.
@@ -1126,7 +1140,7 @@ impl ToolCall {
}
}
if label_changed {
- let is_plain_text = self.title.is_none() || self.kind == acp::ToolKind::Execute;
+ let is_plain_text = self.title.is_none() || self.kind == acp_v1::ToolKind::Execute;
if was_plain_text != is_plain_text {
self.label = Self::new_label(
self.title.as_ref(),
@@ -1225,21 +1239,23 @@ impl ToolCall {
fn update_status(&mut self, status: ToolCallStatus) {
match status {
- ToolCallStatus::Pending => self.update_acp_status(acp::ToolCallStatus::Pending),
- ToolCallStatus::InProgress => self.update_acp_status(acp::ToolCallStatus::InProgress),
- ToolCallStatus::Completed => self.update_acp_status(acp::ToolCallStatus::Completed),
- ToolCallStatus::Failed => self.update_acp_status(acp::ToolCallStatus::Failed),
+ ToolCallStatus::Pending => self.update_acp_status(acp_v1::ToolCallStatus::Pending),
+ ToolCallStatus::InProgress => {
+ self.update_acp_status(acp_v1::ToolCallStatus::InProgress)
+ }
+ ToolCallStatus::Completed => self.update_acp_status(acp_v1::ToolCallStatus::Completed),
+ ToolCallStatus::Failed => self.update_acp_status(acp_v1::ToolCallStatus::Failed),
status @ (ToolCallStatus::WaitingForConfirmation { .. }
| ToolCallStatus::Rejected
| ToolCallStatus::Canceled) => self.status = status,
}
}
- fn update_acp_status(&mut self, status: acp::ToolCallStatus) {
+ fn update_acp_status(&mut self, status: acp_v1::ToolCallStatus) {
if let ToolCallStatus::WaitingForConfirmation { current_status, .. } = &mut self.status
&& matches!(
status,
- acp::ToolCallStatus::Pending | acp::ToolCallStatus::InProgress
+ acp_v1::ToolCallStatus::Pending | acp_v1::ToolCallStatus::InProgress
)
{
*current_status = status;
@@ -1289,7 +1305,7 @@ impl ToolCall {
}
async fn resolve_location(
- location: acp::ToolCallLocation,
+ location: acp_v1::ToolCallLocation,
project: WeakEntity<Project>,
cx: &mut AsyncApp,
) -> Option<ResolvedLocation> {
@@ -1364,13 +1380,16 @@ pub enum SelectedPermissionParams {
#[derive(Debug, Clone)]
pub struct SelectedPermissionOutcome {
- pub option_id: acp::PermissionOptionId,
- pub option_kind: acp::PermissionOptionKind,
+ pub option_id: acp_v1::PermissionOptionId,
+ pub option_kind: acp_v1::PermissionOptionKind,
pub params: Option<SelectedPermissionParams>,
}
impl SelectedPermissionOutcome {
- pub fn new(option_id: acp::PermissionOptionId, option_kind: acp::PermissionOptionKind) -> Self {
+ pub fn new(
+ option_id: acp_v1::PermissionOptionId,
+ option_kind: acp_v1::PermissionOptionKind,
+ ) -> Self {
Self {
option_id,
option_kind,
@@ -1384,7 +1403,7 @@ impl SelectedPermissionOutcome {
}
}
-impl From<SelectedPermissionOutcome> for acp::SelectedPermissionOutcome {
+impl From<SelectedPermissionOutcome> for acp_v1::SelectedPermissionOutcome {
fn from(value: SelectedPermissionOutcome) -> Self {
Self::new(value.option_id)
}
@@ -1397,7 +1416,7 @@ pub enum RequestPermissionOutcome {
Selected(SelectedPermissionOutcome),
}
-impl From<RequestPermissionOutcome> for acp::RequestPermissionOutcome {
+impl From<RequestPermissionOutcome> for acp_v1::RequestPermissionOutcome {
fn from(value: RequestPermissionOutcome) -> Self {
match value {
RequestPermissionOutcome::Cancelled
@@ -1430,7 +1449,7 @@ pub enum ToolCallStatus {
Pending,
/// The tool call is waiting for confirmation from the user.
WaitingForConfirmation {
- current_status: acp::ToolCallStatus,
+ current_status: acp_v1::ToolCallStatus,
options: PermissionOptions,
respond_tx: oneshot::Sender<RequestPermissionOutcome>,
kind: AuthorizationKind,
@@ -1447,31 +1466,31 @@ pub enum ToolCallStatus {
Canceled,
}
-impl From<acp::ToolCallStatus> for ToolCallStatus {
- fn from(status: acp::ToolCallStatus) -> Self {
+impl From<acp_v1::ToolCallStatus> for ToolCallStatus {
+ fn from(status: acp_v1::ToolCallStatus) -> Self {
match status {
- acp::ToolCallStatus::Pending => Self::Pending,
- acp::ToolCallStatus::InProgress => Self::InProgress,
- acp::ToolCallStatus::Completed => Self::Completed,
- acp::ToolCallStatus::Failed => Self::Failed,
+ acp_v1::ToolCallStatus::Pending => Self::Pending,
+ acp_v1::ToolCallStatus::InProgress => Self::InProgress,
+ acp_v1::ToolCallStatus::Completed => Self::Completed,
+ acp_v1::ToolCallStatus::Failed => Self::Failed,
_ => Self::Pending,
}
}
}
impl ToolCallStatus {
- fn as_acp_status(&self) -> Option<acp::ToolCallStatus> {
+ fn as_acp_status(&self) -> Option<acp_v1::ToolCallStatus> {
match self {
- ToolCallStatus::Pending => Some(acp::ToolCallStatus::Pending),
+ ToolCallStatus::Pending => Some(acp_v1::ToolCallStatus::Pending),
ToolCallStatus::WaitingForConfirmation { current_status, .. } => Some(*current_status),
- ToolCallStatus::InProgress => Some(acp::ToolCallStatus::InProgress),
- ToolCallStatus::Completed => Some(acp::ToolCallStatus::Completed),
- ToolCallStatus::Failed => Some(acp::ToolCallStatus::Failed),
+ ToolCallStatus::InProgress => Some(acp_v1::ToolCallStatus::InProgress),
+ ToolCallStatus::Completed => Some(acp_v1::ToolCallStatus::Completed),
+ ToolCallStatus::Failed => Some(acp_v1::ToolCallStatus::Failed),
ToolCallStatus::Rejected | ToolCallStatus::Canceled => None,
}
}
- fn status_after_permission_grant(status: acp::ToolCallStatus) -> ToolCallStatus {
+ fn status_after_permission_grant(status: acp_v1::ToolCallStatus) -> ToolCallStatus {
match ToolCallStatus::from(status) {
ToolCallStatus::Pending => ToolCallStatus::InProgress,
status => status,
@@ -1497,18 +1516,20 @@ impl Display for ToolCallStatus {
}
}
-fn elicitation_status_for_response(response: &acp::CreateElicitationResponse) -> ElicitationStatus {
+fn elicitation_status_for_response(
+ response: &acp_v1::CreateElicitationResponse,
+) -> ElicitationStatus {
match &response.action {
- acp::ElicitationAction::Accept(_) => ElicitationStatus::Accepted,
- acp::ElicitationAction::Decline => ElicitationStatus::Declined,
- acp::ElicitationAction::Cancel => ElicitationStatus::Canceled,
+ acp_v1::ElicitationAction::Accept(_) => ElicitationStatus::Accepted,
+ acp_v1::ElicitationAction::Decline => ElicitationStatus::Declined,
+ acp_v1::ElicitationAction::Cancel => ElicitationStatus::Canceled,
_ => ElicitationStatus::Canceled,
}
}
#[derive(Debug, Default, PartialEq)]
pub struct MessageContent {
- source_blocks: Vec<acp::ContentBlock>,
+ source_blocks: Vec<acp_v2::ContentBlock>,
blocks: Vec<RenderedMessageBlock>,
}
@@ -1520,7 +1541,7 @@ struct RenderedMessageBlock {
impl MessageContent {
pub fn new(
- block: acp::ContentBlock,
+ block: acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
path_style: PathStyle,
cx: &mut App,
@@ -1531,7 +1552,7 @@ impl MessageContent {
}
/// Original content blocks, including text not yet revealed by streaming.
- pub fn source_blocks(&self) -> &[acp::ContentBlock] {
+ pub fn source_blocks(&self) -> &[acp_v2::ContentBlock] {
&self.source_blocks
}
@@ -1572,7 +1593,7 @@ impl MessageContent {
pub fn append(
&mut self,
- block: acp::ContentBlock,
+ block: acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
path_style: PathStyle,
cx: &mut App,
@@ -1583,14 +1604,14 @@ impl MessageContent {
fn append_rendered(
&mut self,
- block: &acp::ContentBlock,
+ block: &acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
path_style: PathStyle,
cx: &mut App,
) {
match block {
- acp::ContentBlock::Text(text) => self.append_text(&text.text, language_registry, cx),
- acp::ContentBlock::ResourceLink(resource) => {
+ acp_v2::ContentBlock::Text(text) => self.append_text(&text.text, language_registry, cx),
+ acp_v2::ContentBlock::ResourceLink(resource) => {
let mut text = ContentBlock::resource_link_md(&resource.uri, path_style);
if self.blocks.is_empty() {
// Legacy leading links separated the next chunk. Include that separator
@@ -1602,7 +1623,9 @@ impl MessageContent {
_ => {
let render = ContentBlock::render_from_source(block, language_registry, cx);
let source_index = match render {
- RenderBlock::EmbeddedResource { .. } => Some(self.source_blocks.len()),
+ RenderBlock::EmbeddedResource { .. } | RenderBlock::Unsupported { .. } => {
+ Some(self.source_blocks.len())
+ }
_ => None,
};
self.blocks.push(RenderedMessageBlock {
@@ -1629,15 +1652,15 @@ impl MessageContent {
}
}
- fn append_deferred_text(&mut self, text: acp::TextContent) -> usize {
+ fn append_deferred_text(&mut self, text: acp_v2::TextContent) -> usize {
let index = self.source_blocks.len();
- self.source_blocks.push(acp::ContentBlock::Text(text));
+ self.source_blocks.push(acp_v2::ContentBlock::Text(text));
index
}
fn append_prompt(
&mut self,
- block: acp::ContentBlock,
+ block: acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
path_style: PathStyle,
cx: &mut App,
@@ -1645,10 +1668,10 @@ impl MessageContent {
// Prompt text resources are mentions, not output previews. Keep their text
// inline while retaining the original payloads in the source blocks.
match &block {
- acp::ContentBlock::Resource(resource)
+ acp_v2::ContentBlock::Resource(resource)
if matches!(
resource.resource,
- acp::EmbeddedResourceResource::TextResourceContents(_)
+ acp_v2::EmbeddedResourceResource::TextResourceContents(_)
) =>
{
let text = ContentBlock::embedded_resource_string_contents(resource, path_style);
@@ -1663,7 +1686,7 @@ impl MessageContent {
#[derive(Debug, PartialEq, Clone)]
pub struct ContentBlock {
render: RenderBlock,
- source: Option<acp::ContentBlock>,
+ source: Option<acp_v2::ContentBlock>,
}
#[derive(Debug, PartialEq, Clone)]
@@ -1687,7 +1710,7 @@ enum RenderBlock {
#[derive(Clone, Copy)]
pub struct ContentBlockView<'a> {
render: &'a RenderBlock,
- source: Option<&'a acp::ContentBlock>,
+ source: Option<&'a acp_v2::ContentBlock>,
}
impl ContentBlock {
@@ -1706,17 +1729,17 @@ impl ContentBlock {
}
#[cfg(test)]
- fn unsupported_content(&self) -> Option<&acp::ContentBlock> {
+ fn unsupported_content(&self) -> Option<&acp_v2::ContentBlock> {
self.as_view().unsupported_content()
}
pub fn new_output(
- block: acp::ContentBlock,
+ block: acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
) -> Self {
match block {
- acp::ContentBlock::Text(text) => {
+ acp_v2::ContentBlock::Text(text) => {
Self::create_markdown_block(text.text, language_registry, cx)
}
block => {
@@ -1733,19 +1756,19 @@ impl ContentBlock {
}
fn render_from_source(
- block: &acp::ContentBlock,
+ block: &acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
) -> RenderBlock {
match block {
- acp::ContentBlock::Resource(resource) => {
+ acp_v2::ContentBlock::Resource(resource) => {
if let Some((image, dimensions)) = Self::decode_embedded_resource_image(resource) {
return RenderBlock::Image { image, dimensions };
}
if matches!(
&resource.resource,
- acp::EmbeddedResourceResource::TextResourceContents(_)
- | acp::EmbeddedResourceResource::BlobResourceContents(_)
+ acp_v2::EmbeddedResourceResource::TextResourceContents(_)
+ | acp_v2::EmbeddedResourceResource::BlobResourceContents(_)
) {
let markdown =
Self::embedded_resource_markdown(resource, language_registry, cx);
@@ -1754,7 +1777,7 @@ impl ContentBlock {
Self::unsupported(block, language_registry, cx)
}
}
- acp::ContentBlock::Image(image) => {
+ acp_v2::ContentBlock::Image(image) => {
if let Some((image, dimensions)) = Self::decode_image(image) {
RenderBlock::Image { image, dimensions }
} else {
@@ -1767,23 +1790,24 @@ impl ContentBlock {
}
}
}
- acp::ContentBlock::ResourceLink(_) => RenderBlock::ResourceLink,
- acp::ContentBlock::Text(text) => RenderBlock::Markdown {
+ acp_v2::ContentBlock::ResourceLink(_) => RenderBlock::ResourceLink,
+ acp_v2::ContentBlock::Text(text) => RenderBlock::Markdown {
markdown: Self::create_markdown(text.text.clone(), language_registry, cx),
},
+ acp_v2::ContentBlock::Other(_) => Self::unsupported(block, language_registry, cx),
_ => Self::unsupported(block, language_registry, cx),
}
}
fn unsupported(
- content: &acp::ContentBlock,
+ content: &acp_v2::ContentBlock,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
) -> RenderBlock {
- let description = if matches!(content, acp::ContentBlock::Audio(_)) {
- "Audio content is not supported."
- } else {
- "This content is not supported."
+ let description = match content {
+ acp_v2::ContentBlock::Audio(_) => "Audio content is not supported.",
+ acp_v2::ContentBlock::Other(_) => "Unknown content type is not supported.",
+ _ => "This content is not supported.",
};
RenderBlock::Unsupported {
markdown: Self::create_markdown(description.into(), language_registry, cx),
@@ -1798,11 +1822,11 @@ impl ContentBlock {
///
/// Recreating the entity on every streamed snapshot causes the rendered
/// element to tear down and rebuild, which flickers badly.
- pub fn update_text_in_place(&mut self, block: &acp::ContentBlock, cx: &mut App) -> bool {
+ pub fn update_text_in_place(&mut self, block: &acp_v2::ContentBlock, cx: &mut App) -> bool {
let RenderBlock::Markdown { markdown } = &self.render else {
return false;
};
- let acp::ContentBlock::Text(text_content) = block else {
+ let acp_v2::ContentBlock::Text(text_content) = block else {
return false;
};
update_markdown_in_place(markdown, &text_content.text, cx);
@@ -1810,18 +1834,19 @@ impl ContentBlock {
}
fn decode_image(
- image_content: &acp::ImageContent,
+ image_content: &acp_v2::ImageContent,
) -> Option<(Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
- Self::decode_image_data(&image_content.data, &image_content.mime_type)
+ Self::decode_image_data(&image_content.data, image_content.mime_type.as_ref())
}
fn decode_embedded_resource_image(
- resource: &acp::EmbeddedResource,
+ resource: &acp_v2::EmbeddedResource,
) -> Option<(Arc<gpui::Image>, Option<gpui::Size<u32>>)> {
- let acp::EmbeddedResourceResource::BlobResourceContents(blob) = &resource.resource else {
+ let acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) = &resource.resource
+ else {
return None;
};
- let mime_type = blob.mime_type.as_deref()?;
+ let mime_type = blob.mime_type.as_ref()?.as_ref();
Self::decode_image_data(&blob.blob, mime_type)
}
@@ -1892,21 +1917,21 @@ impl ContentBlock {
}
fn embedded_resource_markdown(
- resource: &acp::EmbeddedResource,
+ resource: &acp_v2::EmbeddedResource,
language_registry: &Arc<LanguageRegistry>,
cx: &mut App,
) -> Option<Entity<Markdown>> {
match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => Some(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => Some(
Self::create_markdown(Self::text_resource_markdown(text), language_registry, cx),
),
- acp::EmbeddedResourceResource::BlobResourceContents(_) => None,
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(_) => None,
_ => None,
}
}
- fn text_resource_markdown(resource: &acp::TextResourceContents) -> String {
- match text_resource_render_mode(resource.mime_type.as_deref()) {
+ fn text_resource_markdown(resource: &acp_v2::TextResourceContents) -> String {
+ match text_resource_render_mode(resource.mime_type.as_ref().map(AsRef::as_ref)) {
TextResourceRenderMode::Markdown => resource.text.clone(),
TextResourceRenderMode::CodeBlock(language) => {
Self::fenced_code_block(&resource.text, language)
@@ -1952,7 +1977,7 @@ impl ContentBlock {
impl<'a> ContentBlockView<'a> {
#[cfg(test)]
- fn unsupported_content(&self) -> Option<&'a acp::ContentBlock> {
+ fn unsupported_content(&self) -> Option<&'a acp_v2::ContentBlock> {
match self.render {
RenderBlock::Unsupported { .. } => self.source,
_ => None,
@@ -1967,7 +1992,7 @@ impl<'a> ContentBlockView<'a> {
RenderBlock::EmbeddedResource { .. } => {
self.embedded_resource()
.and_then(|(resource, _)| match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => {
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => {
Some(text.text.as_str())
}
_ => None,
@@ -2005,32 +2030,32 @@ impl ContentBlock {
}
fn embedded_resource_string_contents(
- resource: &acp::EmbeddedResource,
+ resource: &acp_v2::EmbeddedResource,
path_style: PathStyle,
) -> String {
match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => {
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => {
Self::resource_link_md(&text.uri, path_style)
}
- acp::EmbeddedResourceResource::BlobResourceContents(blob) => {
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => {
Self::resource_link_md(&blob.uri, path_style)
}
_ => String::new(),
}
}
- fn embedded_resource_text(resource: &acp::EmbeddedResource) -> &str {
+ fn embedded_resource_text(resource: &acp_v2::EmbeddedResource) -> &str {
match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => &text.text,
- acp::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri,
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => &text.text,
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri,
_ => "",
}
}
- fn embedded_resource_label(resource: &acp::EmbeddedResource) -> &str {
+ fn embedded_resource_label(resource: &acp_v2::EmbeddedResource) -> &str {
match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => &text.uri,
- acp::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri,
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => &text.uri,
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => &blob.uri,
_ => "",
}
}
@@ -2039,10 +2064,12 @@ impl ContentBlock {
impl<'a> ContentBlockView<'a> {
pub fn embedded_resource(
&self,
- ) -> Option<(&'a acp::EmbeddedResource, Option<&'a Entity<Markdown>>)> {
+ ) -> Option<(&'a acp_v2::EmbeddedResource, Option<&'a Entity<Markdown>>)> {
match &self.render {
RenderBlock::EmbeddedResource { markdown } => match self.source {
- Some(acp::ContentBlock::Resource(resource)) => Some((resource, markdown.as_ref())),
+ Some(acp_v2::ContentBlock::Resource(resource)) => {
+ Some((resource, markdown.as_ref()))
+ }
_ => None,
},
_ => None,
@@ -2081,7 +2108,7 @@ impl<'a> ContentBlockView<'a> {
}
}
RenderBlock::ResourceLink => match self.source {
- Some(acp::ContentBlock::ResourceLink(resource_link)) => &resource_link.uri,
+ Some(acp_v2::ContentBlock::ResourceLink(resource_link)) => &resource_link.uri,
_ => "",
},
RenderBlock::Image { .. } => "`Image`",
@@ -2098,10 +2125,10 @@ impl<'a> ContentBlockView<'a> {
}
}
- pub fn resource_link(&self) -> Option<&'a acp::ResourceLink> {
+ pub fn resource_link(&self) -> Option<&'a acp_v2::ResourceLink> {
match &self.render {
RenderBlock::ResourceLink => match self.source {
- Some(acp::ContentBlock::ResourceLink(resource_link)) => Some(resource_link),
+ Some(acp_v2::ContentBlock::ResourceLink(resource_link)) => Some(resource_link),
_ => None,
},
_ => None,
@@ -2180,16 +2207,20 @@ pub enum ToolCallContent {
impl ToolCallContent {
pub fn from_acp(
- content: acp::ToolCallContent,
+ content: acp_v1::ToolCallContent,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
cx: &mut App,
) -> Result<Option<Self>> {
match content {
- acp::ToolCallContent::Content(acp::Content { content, .. }) => Ok(Some(
- Self::ContentBlock(ContentBlock::new_output(content, &language_registry, cx)),
- )),
- acp::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {
+ acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => {
+ Ok(Some(Self::ContentBlock(ContentBlock::new_output(
+ content::from_v1(content)?,
+ &language_registry,
+ cx,
+ ))))
+ }
+ acp_v1::ToolCallContent::Diff(diff) => Ok(Some(Self::Diff(cx.new(|cx| {
Diff::finalized(
diff.path.to_string_lossy().into_owned(),
diff.old_text,
@@ -2198,7 +2229,7 @@ impl ToolCallContent {
cx,
)
})))),
- acp::ToolCallContent::Terminal(acp::Terminal { terminal_id, .. }) => terminals
+ acp_v1::ToolCallContent::Terminal(acp_v1::Terminal { terminal_id, .. }) => terminals
.get(&terminal_id)
.cloned()
.map(|terminal| Some(Self::Terminal(terminal)))
@@ -2209,24 +2240,29 @@ impl ToolCallContent {
pub fn update_from_acp(
&mut self,
- new: acp::ToolCallContent,
+ new: acp_v1::ToolCallContent,
language_registry: Arc<LanguageRegistry>,
- terminals: &HashMap<acp::TerminalId, Entity<Terminal>>,
+ terminals: &HashMap<acp_v1::TerminalId, Entity<Terminal>>,
cx: &mut App,
) -> Result<bool> {
- // Update streaming text in place so the rendered markdown element is
- // reused across snapshots instead of being recreated (which flickers).
- if let (
- Self::ContentBlock(block),
- acp::ToolCallContent::Content(acp::Content { content, .. }),
- ) = (&mut *self, &new)
- && block.update_text_in_place(content, cx)
- {
- return Ok(true);
- }
+ let new = match new {
+ acp_v1::ToolCallContent::Content(acp_v1::Content { content, .. }) => {
+ let content = content::from_v1(content)?;
+ // Keep Markdown identity across text snapshots to avoid flicker.
+ if let Self::ContentBlock(block) = self
+ && block.update_text_in_place(&content, cx)
+ {
+ return Ok(true);
+ }
+ *self =
+ Self::ContentBlock(ContentBlock::new_output(content, &language_registry, cx));
+ return Ok(true);
+ }
+ new => new,
+ };
let needs_update = match (&self, &new) {
- (Self::Diff(old_diff), acp::ToolCallContent::Diff(new_diff)) => {
+ (Self::Diff(old_diff), acp_v1::ToolCallContent::Diff(new_diff)) => {
old_diff.read(cx).needs_update(
new_diff.old_text.as_deref().unwrap_or(""),
&new_diff.new_text,
@@ -2264,13 +2300,13 @@ impl ToolCallContent {
#[derive(Debug, PartialEq)]
pub enum ToolCallUpdate {
- UpdateFields(acp::ToolCallUpdate),
+ UpdateFields(acp_v1::ToolCallUpdate),
UpdateDiff(ToolCallUpdateDiff),
UpdateTerminal(ToolCallUpdateTerminal),
}
impl ToolCallUpdate {
- fn id(&self) -> &acp::ToolCallId {
+ fn id(&self) -> &acp_v1::ToolCallId {
match self {
Self::UpdateFields(update) => &update.tool_call_id,
Self::UpdateDiff(diff) => &diff.id,
@@ -2279,8 +2315,8 @@ impl ToolCallUpdate {
}
}
-impl From<acp::ToolCallUpdate> for ToolCallUpdate {
- fn from(update: acp::ToolCallUpdate) -> Self {
+impl From<acp_v1::ToolCallUpdate> for ToolCallUpdate {
+ fn from(update: acp_v1::ToolCallUpdate) -> Self {
Self::UpdateFields(update)
}
}
@@ -2293,7 +2329,7 @@ impl From<ToolCallUpdateDiff> for ToolCallUpdate {
#[derive(Debug, PartialEq)]
pub struct ToolCallUpdateDiff {
- pub id: acp::ToolCallId,
+ pub id: acp_v1::ToolCallId,
pub diff: Entity<Diff>,
}
@@ -2305,7 +2341,7 @@ impl From<ToolCallUpdateTerminal> for ToolCallUpdate {
#[derive(Debug, PartialEq)]
pub struct ToolCallUpdateTerminal {
- pub id: acp::ToolCallId,
+ pub id: acp_v1::ToolCallId,
pub terminal: Entity<Terminal>,
}
@@ -2335,14 +2371,14 @@ impl Plan {
for entry in &self.entries {
match &entry.status {
- acp::PlanEntryStatus::Pending => {
+ acp_v1::PlanEntryStatus::Pending => {
stats.pending += 1;
}
- acp::PlanEntryStatus::InProgress => {
+ acp_v1::PlanEntryStatus::InProgress => {
stats.in_progress_entry = stats.in_progress_entry.or(Some(entry));
stats.pending += 1;
}
- acp::PlanEntryStatus::Completed => {
+ acp_v1::PlanEntryStatus::Completed => {
stats.completed += 1;
}
_ => {}
@@ -2356,12 +2392,12 @@ impl Plan {
#[derive(Debug)]
pub struct PlanEntry {
pub content: Entity<Markdown>,
- pub priority: acp::PlanEntryPriority,
- pub status: acp::PlanEntryStatus,
+ pub priority: acp_v1::PlanEntryPriority,
+ pub status: acp_v1::PlanEntryStatus,
}
impl PlanEntry {
- pub fn from_acp(entry: acp::PlanEntry, cx: &mut App) -> Self {
+ pub fn from_acp(entry: acp_v1::PlanEntry, cx: &mut App) -> Self {
Self {
content: cx.new(|cx| Markdown::new(entry.content.into(), None, None, cx)),
priority: entry.priority,
@@ -2425,16 +2461,16 @@ pub struct RetryStatus {
pub max_attempts: usize,
pub started_at: Instant,
pub duration: Duration,
- pub meta: Option<acp::Meta>,
+ pub meta: Option<acp_v1::Meta>,
}
pub const REFUSAL_FALLBACK_MODEL_META_KEY: &str = "refusal_fallback_model";
-pub fn meta_with_refusal_fallback(model_name: &str) -> acp::Meta {
- acp::Meta::from_iter([(REFUSAL_FALLBACK_MODEL_META_KEY.into(), model_name.into())])
+pub fn meta_with_refusal_fallback(model_name: &str) -> acp_v1::Meta {
+ acp_v1::Meta::from_iter([(REFUSAL_FALLBACK_MODEL_META_KEY.into(), model_name.into())])
}
-pub fn refusal_fallback_model_from_meta(meta: &Option<acp::Meta>) -> Option<SharedString> {
+pub fn refusal_fallback_model_from_meta(meta: &Option<acp_v1::Meta>) -> Option<SharedString> {
meta.as_ref()
.and_then(|m| m.get(REFUSAL_FALLBACK_MODEL_META_KEY))
.and_then(|v| v.as_str())
@@ -2448,14 +2484,14 @@ struct RunningTurn {
}
pub struct AcpThread {
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
work_dirs: Option<PathList>,
- parent_session_id: Option<acp::SessionId>,
+ parent_session_id: Option<acp_v1::SessionId>,
title: Option<SharedString>,
provisional_title: Option<SharedString>,
entries: Vec<AgentThreadEntry>,
// Notices stay with the live session, but never enter conversation history or exports.
- notices: Vec<(usize, acp::Notice)>,
+ notices: Vec<(usize, acp_v1::Notice)>,
next_notice_id: usize,
elicitations: ElicitationStore,
plan: Plan,
@@ -2469,16 +2505,16 @@ pub struct AcpThread {
connection: Rc<dyn AgentConnection>,
token_usage: Option<TokenUsage>,
cost: Option<SessionCost>,
- prompt_capabilities: acp::PromptCapabilities,
- available_commands: Vec<acp::AvailableCommand>,
+ prompt_capabilities: acp_v1::PromptCapabilities,
+ available_commands: Vec<acp_v1::AvailableCommand>,
_observe_prompt_capabilities: Task<anyhow::Result<()>>,
_idle_sleep_subscriptions: Vec<Subscription>,
- terminals: HashMap<acp::TerminalId, Entity<Terminal>>,
- pending_terminal_output: HashMap<acp::TerminalId, Vec<Vec<u8>>>,
- pending_terminal_exit: HashMap<acp::TerminalId, acp::TerminalExitStatus>,
+ terminals: HashMap<acp_v1::TerminalId, Entity<Terminal>>,
+ pending_terminal_output: HashMap<acp_v1::TerminalId, Vec<Vec<u8>>>,
+ 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::ContentBlock>>,
+ draft_prompt: Option<Vec<acp_v1::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
@@ -2502,11 +2538,11 @@ struct TextCursor {
}
impl TextCursor {
- fn take(&mut self, sources: &[acp::ContentBlock], max_bytes: usize) -> Option<String> {
+ fn take(&mut self, sources: &[acp_v2::ContentBlock], max_bytes: usize) -> Option<String> {
let max_bytes = max_bytes.min(self.pending_bytes);
let mut revealed = String::with_capacity(max_bytes);
while revealed.len() < max_bytes {
- let acp::ContentBlock::Text(text) = sources.get(self.source_index)? else {
+ let acp_v2::ContentBlock::Text(text) = sources.get(self.source_index)? else {
return None;
};
let pending = text.text.get(self.byte_offset..)?;
@@ -2593,21 +2629,21 @@ pub enum AcpThreadEvent {
TokenUsageUpdated,
EntryUpdated(usize),
EntriesRemoved(Range<usize>),
- ToolAuthorizationRequested(acp::ToolCallId),
- ToolAuthorizationReceived(acp::ToolCallId),
+ ToolAuthorizationRequested(acp_v1::ToolCallId),
+ ToolAuthorizationReceived(acp_v1::ToolCallId),
ElicitationRequested(ElicitationEntryId),
/// The request left `Pending`; this does not imply delivery to its response waiter.
ElicitationResponded(ElicitationEntryId),
Retry(RetryStatus),
- SubagentSpawned(acp::SessionId),
- Stopped(acp::StopReason),
+ SubagentSpawned(acp_v1::SessionId),
+ Stopped(acp_v1::StopReason),
Error,
LoadError(LoadError),
PromptCapabilitiesUpdated,
Refusal,
- AvailableCommandsUpdated(Vec<acp::AvailableCommand>),
- ModeUpdated(acp::SessionModeId),
- ConfigOptionsUpdated(Vec<acp::SessionConfigOption>),
+ AvailableCommandsUpdated(Vec<acp_v1::AvailableCommand>),
+ ModeUpdated(acp_v1::SessionModeId),
+ ConfigOptionsUpdated(Vec<acp_v1::SessionConfigOption>),
WorkingDirectoriesUpdated,
}
@@ -2616,39 +2652,39 @@ impl EventEmitter<AcpThreadEvent> for AcpThread {}
#[derive(Debug, Clone)]
pub enum TerminalProviderEvent {
Created {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
label: String,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
terminal: Entity<::terminal::Terminal>,
},
Output {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
data: Vec<u8>,
},
TitleChanged {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
title: String,
},
Exit {
- terminal_id: acp::TerminalId,
- status: acp::TerminalExitStatus,
+ terminal_id: acp_v1::TerminalId,
+ status: acp_v1::TerminalExitStatus,
},
}
#[derive(Debug, Clone)]
pub enum TerminalProviderCommand {
WriteInput {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
bytes: Vec<u8>,
},
Resize {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
cols: u16,
rows: u16,
},
Close {
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
},
}
@@ -2697,14 +2733,14 @@ impl Error for LoadError {}
impl AcpThread {
pub fn new(
- parent_session_id: Option<acp::SessionId>,
+ parent_session_id: Option<acp_v1::SessionId>,
title: Option<SharedString>,
work_dirs: Option<PathList>,
connection: Rc<dyn AgentConnection>,
project: Entity<Project>,
action_log: Entity<ActionLog>,
- session_id: acp::SessionId,
- mut prompt_capabilities_rx: watch::Receiver<acp::PromptCapabilities>,
+ session_id: acp_v1::SessionId,
+ mut prompt_capabilities_rx: watch::Receiver<acp_v1::PromptCapabilities>,
cx: &mut Context<Self>,
) -> Self {
let prompt_capabilities = prompt_capabilities_rx.borrow().clone();
@@ -2801,15 +2837,15 @@ impl AcpThread {
}
}
- pub fn parent_session_id(&self) -> Option<&acp::SessionId> {
+ pub fn parent_session_id(&self) -> Option<&acp_v1::SessionId> {
self.parent_session_id.as_ref()
}
- pub fn prompt_capabilities(&self) -> acp::PromptCapabilities {
+ pub fn prompt_capabilities(&self) -> acp_v1::PromptCapabilities {
self.prompt_capabilities.clone()
}
- pub fn available_commands(&self) -> &[acp::AvailableCommand] {
+ pub fn available_commands(&self) -> &[acp_v1::AvailableCommand] {
&self.available_commands
}
@@ -2817,13 +2853,13 @@ impl AcpThread {
self.entries().is_empty()
}
- pub fn draft_prompt(&self) -> Option<&[acp::ContentBlock]> {
+ pub fn draft_prompt(&self) -> Option<&[acp_v1::ContentBlock]> {
self.draft_prompt.as_deref()
}
pub fn set_draft_prompt(
&mut self,
- prompt: Option<Vec<acp::ContentBlock>>,
+ prompt: Option<Vec<acp_v1::ContentBlock>>,
cx: &mut Context<Self>,
) {
cx.emit(AcpThreadEvent::PromptUpdated);
@@ -2864,7 +2900,7 @@ impl AcpThread {
&self.entries
}
- pub fn notices(&self) -> &[(usize, acp::Notice)] {
+ pub fn notices(&self) -> &[(usize, acp_v1::Notice)] {
&self.notices
}
@@ -2906,7 +2942,7 @@ impl AcpThread {
}
}
- pub fn session_id(&self) -> &acp::SessionId {
+ pub fn session_id(&self) -> &acp_v1::SessionId {
&self.session_id
}
@@ -3027,15 +3063,16 @@ impl AcpThread {
pub fn handle_session_update(
&mut self,
- update: acp::SessionUpdate,
+ update: acp_v1::SessionUpdate,
cx: &mut Context<Self>,
- ) -> Result<(), acp::Error> {
+ ) -> Result<(), acp_v1::Error> {
match update {
- acp::SessionUpdate::UserMessageChunk(acp::ContentChunk {
+ acp_v1::SessionUpdate::UserMessageChunk(acp_v1::ContentChunk {
content,
message_id,
..
}) => {
+ let content = content::from_v1(content).map_err(acp_v1::Error::from)?;
// We optimistically add the full user prompt before calling `prompt`.
// Some ACP servers echo user chunks back over updates. Skip echoed
// chunks only when they match the local optimistic message.
@@ -3062,47 +3099,57 @@ impl AcpThread {
self.push_user_content_block_from_agent(message_id, content, cx);
}
}
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk {
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk {
content,
message_id,
..
}) => {
self.push_assistant_content_block_with_message_id(
- message_id, content, false, false, cx,
+ message_id,
+ content::from_v1(content).map_err(acp_v1::Error::from)?,
+ false,
+ false,
+ cx,
);
}
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk {
+ acp_v1::SessionUpdate::AgentThoughtChunk(acp_v1::ContentChunk {
content,
message_id,
..
}) => {
self.push_assistant_content_block_with_message_id(
- message_id, content, true, false, cx,
+ message_id,
+ content::from_v1(content).map_err(acp_v1::Error::from)?,
+ true,
+ false,
+ cx,
);
}
- acp::SessionUpdate::ToolCall(tool_call) => {
+ acp_v1::SessionUpdate::ToolCall(tool_call) => {
self.upsert_tool_call(tool_call, cx)?;
}
- acp::SessionUpdate::ToolCallUpdate(tool_call_update) => {
+ acp_v1::SessionUpdate::ToolCallUpdate(tool_call_update) => {
self.update_tool_call(tool_call_update, cx)?;
}
- acp::SessionUpdate::CompactionUpdate(compaction_update) => {
- self.upsert_context_compaction_update(compaction_update, cx);
+ acp_v1::SessionUpdate::CompactionUpdate(compaction_update) => {
+ self.upsert_context_compaction_update(compaction_update, cx)
+ .map_err(acp_v1::Error::from)?;
}
- acp::SessionUpdate::CompactionSummaryChunk(summary_chunk) => {
- self.append_context_compaction_summary(summary_chunk, cx);
+ acp_v1::SessionUpdate::CompactionSummaryChunk(summary_chunk) => {
+ self.append_context_compaction_summary(summary_chunk, cx)
+ .map_err(acp_v1::Error::from)?;
}
- acp::SessionUpdate::Plan(plan) => {
+ acp_v1::SessionUpdate::Plan(plan) => {
self.update_plan(plan, cx);
}
- acp::SessionUpdate::Notice(notice) => {
+ acp_v1::SessionUpdate::Notice(notice) => {
let notice_id = self.next_notice_id;
self.next_notice_id += 1;
self.notices.push((notice_id, notice));
cx.emit(AcpThreadEvent::NoticesUpdated);
cx.notify();
}
- acp::SessionUpdate::SessionInfoUpdate(info_update) => {
+ acp_v1::SessionUpdate::SessionInfoUpdate(info_update) => {
if let MaybeUndefined::Value(title) = info_update.title {
let had_provisional = self.provisional_title.take().is_some();
let title: SharedString = title.into();
@@ -3114,22 +3161,22 @@ impl AcpThread {
}
}
}
- acp::SessionUpdate::AvailableCommandsUpdate(acp::AvailableCommandsUpdate {
+ acp_v1::SessionUpdate::AvailableCommandsUpdate(acp_v1::AvailableCommandsUpdate {
available_commands,
..
}) => {
self.available_commands = available_commands.clone();
cx.emit(AcpThreadEvent::AvailableCommandsUpdated(available_commands));
}
- acp::SessionUpdate::CurrentModeUpdate(acp::CurrentModeUpdate {
+ acp_v1::SessionUpdate::CurrentModeUpdate(acp_v1::CurrentModeUpdate {
current_mode_id,
..
}) => cx.emit(AcpThreadEvent::ModeUpdated(current_mode_id)),
- acp::SessionUpdate::ConfigOptionUpdate(acp::ConfigOptionUpdate {
+ acp_v1::SessionUpdate::ConfigOptionUpdate(acp_v1::ConfigOptionUpdate {
config_options,
..
}) => cx.emit(AcpThreadEvent::ConfigOptionsUpdated(config_options)),
- acp::SessionUpdate::UsageUpdate(update) => {
+ acp_v1::SessionUpdate::UsageUpdate(update) => {
let usage = self.token_usage.get_or_insert_with(Default::default);
usage.max_tokens = update.size;
usage.used_tokens = update.used;
@@ -3149,7 +3196,7 @@ impl AcpThread {
pub fn push_user_content_block(
&mut self,
client_id: Option<ClientUserMessageId>,
- chunk: acp::ContentBlock,
+ chunk: acp_v2::ContentBlock,
cx: &mut Context<Self>,
) {
self.push_user_content_block_with_indent(client_id, chunk, false, cx)
@@ -3158,7 +3205,7 @@ impl AcpThread {
pub fn push_user_content_block_with_indent(
&mut self,
client_id: Option<ClientUserMessageId>,
- chunk: acp::ContentBlock,
+ chunk: acp_v2::ContentBlock,
indented: bool,
cx: &mut Context<Self>,
) {
@@ -3174,8 +3221,8 @@ impl AcpThread {
fn push_user_content_block_from_agent(
&mut self,
- id: Option<acp::MessageId>,
- chunk: acp::ContentBlock,
+ id: Option<acp_v1::MessageId>,
+ chunk: acp_v2::ContentBlock,
cx: &mut Context<Self>,
) {
self.push_user_content_block_with_protocol_id(None, false, id, chunk, false, cx)
@@ -3185,8 +3232,8 @@ impl AcpThread {
&mut self,
incoming_client_id: Option<ClientUserMessageId>,
is_optimistic: bool,
- protocol_id: Option<acp::MessageId>,
- chunk: acp::ContentBlock,
+ protocol_id: Option<acp_v1::MessageId>,
+ chunk: acp_v2::ContentBlock,
indented: bool,
cx: &mut Context<Self>,
) {
@@ -3240,7 +3287,7 @@ impl AcpThread {
pub fn push_assistant_content_block(
&mut self,
- chunk: acp::ContentBlock,
+ chunk: acp_v2::ContentBlock,
is_thought: bool,
cx: &mut Context<Self>,
) {
@@ -3249,7 +3296,7 @@ impl AcpThread {
pub fn push_assistant_content_block_with_indent(
&mut self,
- chunk: acp::ContentBlock,
+ chunk: acp_v2::ContentBlock,
is_thought: bool,
indented: bool,
cx: &mut Context<Self>,
@@ -3259,8 +3306,8 @@ impl AcpThread {
fn push_assistant_content_block_with_message_id(
&mut self,
- message_id: Option<acp::MessageId>,
- chunk: acp::ContentBlock,
+ message_id: Option<acp_v1::MessageId>,
+ chunk: acp_v2::ContentBlock,
is_thought: bool,
indented: bool,
cx: &mut Context<Self>,
@@ -3270,7 +3317,7 @@ impl AcpThread {
// For text chunks going to an existing Markdown block, buffer for smooth
// streaming instead of appending all at once which may feel more choppy.
let chunk = match chunk {
- acp::ContentBlock::Text(text) => {
+ acp_v2::ContentBlock::Text(text) => {
if let Some((content, target)) =
self.streaming_content_target(message_id.as_ref(), is_thought, indented)
{
@@ -3280,7 +3327,7 @@ impl AcpThread {
self.buffer_streaming_text(target, source_index, text_len, cx);
return;
}
- acp::ContentBlock::Text(text)
+ acp_v2::ContentBlock::Text(text)
}
chunk => chunk,
};
@@ -3360,7 +3407,7 @@ impl AcpThread {
fn streaming_content_target(
&mut self,
- message_id: Option<&acp::MessageId>,
+ message_id: Option<&acp_v1::MessageId>,
is_thought: bool,
indented: bool,
) -> Option<(&mut MessageContent, StreamingTextTarget)> {
@@ -3528,9 +3575,9 @@ impl AcpThread {
fn upsert_context_compaction_update(
&mut self,
- update: acp::CompactionUpdate,
+ update: acp_v1::CompactionUpdate,
cx: &mut Context<Self>,
- ) {
+ ) -> Result<()> {
let id = ContextCompactionId(update.compaction_id.0.clone());
let language_registry = self.project.read(cx).languages().clone();
@@ -3546,9 +3593,9 @@ impl AcpThread {
_ => None,
})
{
- compaction.apply_update(update, &language_registry, cx);
+ compaction.apply_update(update, &language_registry, cx)?;
cx.emit(AcpThreadEvent::EntryUpdated(entry_index));
- return;
+ return Ok(());
}
let mut compaction = ContextCompaction {
@@ -3557,15 +3604,16 @@ impl AcpThread {
error: None,
summary: Vec::new(),
};
- compaction.apply_update(update, &language_registry, cx);
+ compaction.apply_update(update, &language_registry, cx)?;
self.push_entry(AgentThreadEntry::ContextCompaction(compaction), cx);
+ Ok(())
}
fn append_context_compaction_summary(
&mut self,
- chunk: acp::CompactionSummaryChunk,
+ chunk: acp_v1::CompactionSummaryChunk,
cx: &mut Context<Self>,
- ) {
+ ) -> Result<()> {
let language_registry = self.project.read(cx).languages().clone();
if let Some((entry_index, compaction)) =
self.entries
@@ -3582,9 +3630,10 @@ impl AcpThread {
_ => None,
})
{
- compaction.append_summary(chunk.content, &language_registry, cx);
+ compaction.append_summary(content::from_v1(chunk.content)?, &language_registry, cx);
cx.emit(AcpThreadEvent::EntryUpdated(entry_index));
}
+ Ok(())
}
pub fn update_context_compaction(
@@ -3608,7 +3657,7 @@ impl AcpThread {
if !update.summary_delta.is_empty() {
compaction.append_summary(
- acp::ContentBlock::Text(acp::TextContent::new(update.summary_delta)),
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new(update.summary_delta)),
&language_registry,
cx,
);
@@ -3649,7 +3698,7 @@ impl AcpThread {
cx.emit(AcpThreadEvent::TitleUpdated);
}
- pub fn subagent_spawned(&mut self, session_id: acp::SessionId, cx: &mut Context<Self>) {
+ pub fn subagent_spawned(&mut self, session_id: acp_v1::SessionId, cx: &mut Context<Self>) {
cx.emit(AcpThreadEvent::SubagentSpawned(session_id));
}
@@ -3681,7 +3730,7 @@ impl AcpThread {
id: update.id().clone(),
label: cx.new(|cx| Markdown::new("Tool call not found".into(), None, None, cx)),
title: Some("Tool call not found".into()),
- kind: acp::ToolKind::Fetch,
+ kind: acp_v1::ToolKind::Fetch,
structured_content: vec![ToolCallContent::ContentBlock(
ContentBlock::new_output("Tool call not found".into(), &languages, cx),
)],
@@ -3741,9 +3790,9 @@ impl AcpThread {
/// Updates a tool call if id matches an existing entry, otherwise inserts a new one.
pub fn upsert_tool_call(
&mut self,
- tool_call: acp::ToolCall,
+ tool_call: acp_v1::ToolCall,
cx: &mut Context<Self>,
- ) -> Result<(), acp::Error> {
+ ) -> Result<(), acp_v1::Error> {
let status = tool_call.status.into();
self.upsert_tool_call_inner(tool_call.into(), status, cx)
}
@@ -3751,10 +3800,10 @@ impl AcpThread {
/// Fails if id does not match an existing entry.
pub fn upsert_tool_call_inner(
&mut self,
- update: acp::ToolCallUpdate,
+ update: acp_v1::ToolCallUpdate,
status: ToolCallStatus,
cx: &mut Context<Self>,
- ) -> Result<(), acp::Error> {
+ ) -> Result<(), acp_v1::Error> {
let language_registry = self.project.read(cx).languages().clone();
let id = update.tool_call_id.clone();
@@ -3789,7 +3838,7 @@ impl AcpThread {
cx,
) {
cx.emit(AcpThreadEvent::EntryUpdated(ix));
- return Err(acp::Error::from(error));
+ return Err(acp_v1::Error::from(error));
}
call.update_status(status);
@@ -3809,7 +3858,7 @@ impl AcpThread {
Ok(())
}
- fn index_for_tool_call(&self, id: &acp::ToolCallId) -> Option<usize> {
+ fn index_for_tool_call(&self, id: &acp_v1::ToolCallId) -> Option<usize> {
self.entries
.iter()
.enumerate()
@@ -3825,7 +3874,7 @@ impl AcpThread {
})
}
- fn tool_call_mut(&mut self, id: &acp::ToolCallId) -> Option<(usize, &mut ToolCall)> {
+ fn tool_call_mut(&mut self, id: &acp_v1::ToolCallId) -> Option<(usize, &mut ToolCall)> {
// The tool call we are looking for is typically the last one, or very close to the end.
// At the moment, it doesn't seem like a hashmap would be a good fit for this use case.
self.entries
@@ -3843,7 +3892,7 @@ impl AcpThread {
})
}
- pub fn tool_call(&self, id: &acp::ToolCallId) -> Option<(usize, &ToolCall)> {
+ pub fn tool_call(&self, id: &acp_v1::ToolCallId) -> Option<(usize, &ToolCall)> {
self.entries
.iter()
.enumerate()
@@ -3859,7 +3908,7 @@ impl AcpThread {
})
}
- pub fn tool_call_for_subagent(&self, session_id: &acp::SessionId) -> Option<&ToolCall> {
+ pub fn tool_call_for_subagent(&self, session_id: &acp_v1::SessionId) -> Option<&ToolCall> {
self.entries.iter().find_map(|entry| match entry {
AgentThreadEntry::ToolCall(tool_call) => {
if let Some(subagent_session_info) = &tool_call.subagent_session_info
@@ -3874,7 +3923,7 @@ impl AcpThread {
})
}
- pub fn resolve_locations(&mut self, id: acp::ToolCallId, cx: &mut Context<Self>) {
+ pub fn resolve_locations(&mut self, id: acp_v1::ToolCallId, cx: &mut Context<Self>) {
let project = self.project.clone();
let should_update_agent_location = self.parent_session_id.is_none();
let Some((_, tool_call)) = self.tool_call_mut(&id) else {
@@ -3934,7 +3983,7 @@ impl AcpThread {
pub fn request_tool_call_authorization(
&mut self,
- tool_call: acp::ToolCallUpdate,
+ tool_call: acp_v1::ToolCallUpdate,
options: PermissionOptions,
kind: AuthorizationKind,
cx: &mut Context<Self>,
@@ -3945,7 +3994,7 @@ impl AcpThread {
.tool_call(&tool_call.tool_call_id)
.and_then(|(_, tool_call)| tool_call.status.as_acp_status())
.or(tool_call.fields.status)
- .unwrap_or(acp::ToolCallStatus::Pending);
+ .unwrap_or(acp_v1::ToolCallStatus::Pending);
let status = ToolCallStatus::WaitingForConfirmation {
current_status,
options,
@@ -3969,7 +4018,11 @@ impl AcpThread {
}))
}
- pub fn cancel_tool_call_authorization(&mut self, id: &acp::ToolCallId, cx: &mut Context<Self>) {
+ pub fn cancel_tool_call_authorization(
+ &mut self,
+ id: &acp_v1::ToolCallId,
+ cx: &mut Context<Self>,
+ ) {
let Some((ix, call)) = self.tool_call_mut(id) else {
return;
};
@@ -3984,7 +4037,7 @@ impl AcpThread {
pub fn authorize_tool_call(
&mut self,
- id: acp::ToolCallId,
+ id: acp_v1::ToolCallId,
outcome: SelectedPermissionOutcome,
cx: &mut Context<Self>,
) {
@@ -3992,31 +4045,30 @@ impl AcpThread {
return;
};
- let new_status =
- match &call.status {
- ToolCallStatus::WaitingForConfirmation {
- kind: AuthorizationKind::ActionChoice,
- ..
- } => ToolCallStatus::InProgress,
- ToolCallStatus::WaitingForConfirmation { current_status, .. } => {
- match outcome.option_kind {
- acp::PermissionOptionKind::RejectOnce
- | acp::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
- acp::PermissionOptionKind::AllowOnce
- | acp::PermissionOptionKind::AllowAlways => {
- ToolCallStatus::status_after_permission_grant(*current_status)
- }
- _ => ToolCallStatus::status_after_permission_grant(*current_status),
+ let new_status = match &call.status {
+ ToolCallStatus::WaitingForConfirmation {
+ kind: AuthorizationKind::ActionChoice,
+ ..
+ } => ToolCallStatus::InProgress,
+ ToolCallStatus::WaitingForConfirmation { current_status, .. } => {
+ match outcome.option_kind {
+ acp_v1::PermissionOptionKind::RejectOnce
+ | acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
+ acp_v1::PermissionOptionKind::AllowOnce
+ | acp_v1::PermissionOptionKind::AllowAlways => {
+ ToolCallStatus::status_after_permission_grant(*current_status)
}
+ _ => ToolCallStatus::status_after_permission_grant(*current_status),
}
- _ => match outcome.option_kind {
- acp::PermissionOptionKind::RejectOnce
- | acp::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
- acp::PermissionOptionKind::AllowOnce
- | acp::PermissionOptionKind::AllowAlways => ToolCallStatus::InProgress,
- _ => ToolCallStatus::InProgress,
- },
- };
+ }
+ _ => match outcome.option_kind {
+ acp_v1::PermissionOptionKind::RejectOnce
+ | acp_v1::PermissionOptionKind::RejectAlways => ToolCallStatus::Rejected,
+ acp_v1::PermissionOptionKind::AllowOnce
+ | acp_v1::PermissionOptionKind::AllowAlways => ToolCallStatus::InProgress,
+ _ => ToolCallStatus::InProgress,
+ },
+ };
let curr_status = mem::replace(&mut call.status, new_status);
@@ -4031,18 +4083,18 @@ impl AcpThread {
pub fn request_elicitation(
&mut self,
- request: acp::CreateElicitationRequest,
+ request: acp_v1::CreateElicitationRequest,
cx: &mut Context<Self>,
- ) -> Result<Task<acp::CreateElicitationResponse>, acp::Error> {
+ ) -> Result<Task<acp_v1::CreateElicitationResponse>, acp_v1::Error> {
self.request_elicitation_with_id(request, cx)
.map(|(_, task)| task)
}
pub fn request_elicitation_with_id(
&mut self,
- request: acp::CreateElicitationRequest,
+ request: acp_v1::CreateElicitationRequest,
cx: &mut Context<Self>,
- ) -> Result<(ElicitationEntryId, Task<acp::CreateElicitationResponse>), acp::Error> {
+ ) -> Result<(ElicitationEntryId, Task<acp_v1::CreateElicitationResponse>), acp_v1::Error> {
ElicitationStore::validate_request(&request)?;
let (id, response_rx) = self.elicitations.insert_pending_elicitation(request);
@@ -4068,7 +4120,7 @@ impl AcpThread {
pub fn respond_to_elicitation(
&mut self,
id: &ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
cx: &mut Context<Self>,
) {
let Some(ix) = self.elicitation_entry_ix(id) else {
@@ -4083,7 +4135,7 @@ impl AcpThread {
pub fn complete_url_elicitation(
&mut self,
- elicitation_id: &acp::ElicitationId,
+ elicitation_id: &acp_v1::ElicitationId,
cx: &mut Context<Self>,
) {
let Some(entry_id) = self
@@ -4134,7 +4186,7 @@ impl AcpThread {
&self.plan
}
- pub fn update_plan(&mut self, request: acp::Plan, cx: &mut Context<Self>) {
+ pub fn update_plan(&mut self, request: acp_v1::Plan, cx: &mut Context<Self>) {
let new_entries_len = request.entries.len();
let mut new_entries = request.entries.into_iter();
@@ -4162,7 +4214,7 @@ impl AcpThread {
fn clear_completed_plan_entries(&mut self, cx: &mut Context<Self>) {
self.plan
.entries
- .retain(|entry| !matches!(entry.status, acp::PlanEntryStatus::Completed));
+ .retain(|entry| !matches!(entry.status, acp_v1::PlanEntryStatus::Completed));
cx.notify();
}
@@ -4176,15 +4228,15 @@ impl AcpThread {
&mut self,
message: &str,
cx: &mut Context<Self>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
self.send(vec![message.into()], cx)
}
pub fn send(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
cx: &mut Context<Self>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
self.send_inner(message, true, cx)
}
@@ -4194,25 +4246,29 @@ impl AcpThread {
/// typed command isn't sent to the model as an ordinary user turn.
pub fn send_command(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
cx: &mut Context<Self>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
self.send_inner(message, false, cx)
}
fn send_inner(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
push_user_message: bool,
cx: &mut Context<Self>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
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 {
- block.append_prompt(chunk.clone(), &language_registry, path_style, cx);
+ let chunk = match content::from_v1(chunk.clone()) {
+ Ok(chunk) => chunk,
+ Err(error) => return futures::future::ready(Err(error)).boxed(),
+ };
+ block.append_prompt(chunk, &language_registry, path_style, cx);
}
- let request = acp::PromptRequest::new(self.session_id.clone(), message);
+ 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);
@@ -4271,7 +4327,7 @@ impl AcpThread {
pub fn retry(
&mut self,
cx: &mut Context<Self>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
self.run_turn(cx, async move |this, cx| {
this.update(cx, |this, cx| {
this.connection
@@ -4286,8 +4342,8 @@ impl AcpThread {
fn run_turn(
&mut self,
cx: &mut Context<Self>,
- f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp::PromptResponse>,
- ) -> BoxFuture<'static, Result<Option<acp::PromptResponse>>> {
+ f: impl 'static + AsyncFnOnce(WeakEntity<Self>, &mut AsyncApp) -> Result<acp_v1::PromptResponse>,
+ ) -> BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>> {
self.clear_completed_plan_entries(cx);
self.had_error = false;
@@ -4361,7 +4417,7 @@ impl AcpThread {
Ok(r) => {
this.flush_streaming_text(cx);
- if r.stop_reason == acp::StopReason::MaxTokens {
+ if r.stop_reason == acp_v1::StopReason::MaxTokens {
if is_same_turn {
cx.emit(AcpThreadEvent::StatusChanged);
}
@@ -4389,13 +4445,13 @@ impl AcpThread {
return Err(anyhow!(MaxOutputTokensError));
}
- let canceled = matches!(r.stop_reason, acp::StopReason::Cancelled);
+ let canceled = matches!(r.stop_reason, acp_v1::StopReason::Cancelled);
if canceled && is_same_turn {
this.cancel_pending_turn_entries(cx);
}
// Handle refusal - distinguish between user prompt and tool call refusals
- if let acp::StopReason::Refusal = r.stop_reason {
+ if let acp_v1::StopReason::Refusal = r.stop_reason {
this.had_error = true;
if let Some((user_msg_ix, _)) = this.last_user_message() {
// Check if there's a completed tool call with results after the last user message
@@ -4633,7 +4689,7 @@ impl AcpThread {
this.flush_streaming_text(cx);
if let Some((ix, _)) = this.user_message_mut(&client_id) {
// Collect all terminals from entries that will be removed
- let terminals_to_remove: Vec<acp::TerminalId> = this.entries[ix..]
+ let terminals_to_remove: Vec<acp_v1::TerminalId> = this.entries[ix..]
.iter()
.flat_map(|entry| entry.terminals())
.filter_map(|terminal| terminal.read(cx).id().clone().into())
@@ -4818,7 +4874,7 @@ impl AcpThread {
limit: Option<u32>,
reuse_shared_snapshot: bool,
cx: &mut Context<Self>,
- ) -> Task<Result<String, acp::Error>> {
+ ) -> Task<Result<String, acp_v1::Error>> {
// Args are 1-based, move to 0-based
let line = line.unwrap_or_default().saturating_sub(1);
let limit = limit.unwrap_or(u32::MAX);
@@ -4830,9 +4886,9 @@ impl AcpThread {
let path = project
.project_path_for_absolute_path(&path, cx)
.ok_or_else(|| {
- acp::Error::resource_not_found(Some(path.display().to_string()))
+ acp_v1::Error::resource_not_found(Some(path.display().to_string()))
})?;
- Ok::<_, acp::Error>(project.open_buffer(path, cx))
+ Ok::<_, acp_v1::Error>(project.open_buffer(path, cx))
})?;
let buffer = load.await?;
@@ -4865,7 +4921,7 @@ impl AcpThread {
let start_position = Point::new(line, 0);
if start_position > max_point {
- return Err(acp::Error::invalid_params().data(format!(
+ return Err(acp_v1::Error::invalid_params().data(format!(
"Attempting to read beyond the end of the file, line {}:{}",
max_point.row + 1,
max_point.column
@@ -4990,7 +5046,7 @@ impl AcpThread {
&self,
command: String,
args: Vec<String>,
- extra_env: Vec<acp::EnvVariable>,
+ extra_env: Vec<acp_v1::EnvVariable>,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
sandbox_wrap: Option<SandboxWrap>,
@@ -5023,7 +5079,7 @@ impl AcpThread {
// without a PTY in that case.
let headless = HeadlessTerminal::is_enabled(cx);
- let terminal_id = acp::TerminalId::new(Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(Uuid::new_v4().to_string());
let terminal_task = cx.spawn({
let terminal_id = terminal_id.clone();
async move |_this, cx| {
@@ -5144,7 +5200,7 @@ impl AcpThread {
pub fn kill_terminal(
&mut self,
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
cx: &mut Context<Self>,
) -> Result<()> {
self.terminals
@@ -5159,7 +5215,7 @@ impl AcpThread {
pub fn release_terminal(
&mut self,
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
cx: &mut Context<Self>,
) -> Result<()> {
self.terminals
@@ -5172,7 +5228,7 @@ impl AcpThread {
Ok(())
}
- pub fn terminal(&self, terminal_id: acp::TerminalId) -> Result<Entity<Terminal>> {
+ pub fn terminal(&self, terminal_id: acp_v1::TerminalId) -> Result<Entity<Terminal>> {
self.terminals
.get(&terminal_id)
.context("Terminal not found")
@@ -5201,7 +5257,7 @@ impl AcpThread {
pub fn register_terminal_created(
&mut self,
- terminal_id: acp::TerminalId,
+ terminal_id: acp_v1::TerminalId,
command_label: String,
working_dir: Option<PathBuf>,
output_byte_limit: Option<u64>,
@@ -5391,7 +5447,8 @@ mod tests {
#[test]
fn test_text_cursor_reads_source_on_utf8_boundaries() {
- let sources = ["visible", "", "aé", "", "🦀b", "", "日本語"].map(acp::ContentBlock::from);
+ let sources =
+ ["visible", "", "aé", "", "🦀b", "", "日本語"].map(acp_v2::ContentBlock::from);
let whole = "aé🦀b日本語";
for max_bytes in 1..=whole.len() + 1 {
let mut cursor = TextCursor {
@@ -5511,7 +5568,7 @@ mod tests {
// Absent meta and unknown categories both decode to `None`.
assert_eq!(command_category_from_meta(&None), None);
let unknown =
- acp::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), "future-category".into())]);
+ acp_v1::Meta::from_iter([(COMMAND_CATEGORY_META_KEY.into(), "future-category".into())]);
assert_eq!(command_category_from_meta(&Some(unknown)), None);
}
@@ -5560,8 +5617,8 @@ mod tests {
});
}
- fn message_test_image() -> acp::ContentBlock {
- acp::ContentBlock::Image(acp::ImageContent::new(
+ fn message_test_image() -> acp_v2::ContentBlock {
+ acp_v2::ContentBlock::Image(acp_v2::ImageContent::new(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
"image/png",
))
@@ -5572,35 +5629,38 @@ mod tests {
init_test(cx);
cx.update(|cx| {
let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
- let annotations = acp::Annotations::new().priority(0.5);
+ let annotations = acp_v2::Annotations::new().priority(0.5);
let blocks = vec![
- acp::ContentBlock::Text(
- acp::TextContent::new("")
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("")
.annotations(annotations.clone())
- .meta(acp::Meta::from_iter([("empty".into(), json!(true))])),
+ .meta(acp_v1::Meta::from_iter([("empty".into(), json!(true))])),
),
- acp::ContentBlock::Text(
- acp::TextContent::new("hello ")
- .meta(acp::Meta::from_iter([("part".into(), json!(1))])),
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("hello ")
+ .meta(acp_v1::Meta::from_iter([("part".into(), json!(1))])),
),
- acp::ContentBlock::Text(
- acp::TextContent::new("world")
- .meta(acp::Meta::from_iter([("part".into(), json!(2))])),
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("world")
+ .meta(acp_v1::Meta::from_iter([("part".into(), json!(2))])),
),
match message_test_image() {
- acp::ContentBlock::Image(image) => acp::ContentBlock::Image(
+ acp_v2::ContentBlock::Image(image) => acp_v2::ContentBlock::Image(
image
.uri("file:///original.png".to_string())
.annotations(annotations)
- .meta(acp::Meta::from_iter([("image".into(), json!(42))])),
+ .meta(acp_v1::Meta::from_iter([("image".into(), json!(42))])),
),
_ => unreachable!("fixture is an image"),
},
- acp::ContentBlock::ResourceLink(
- acp::ResourceLink::new("original name", "https://example.com/file")
+ acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("original name", "https://example.com/file")
.description("original description".to_string())
.title("original title".to_string())
- .meta(acp::Meta::from_iter([("link".into(), json!("original"))])),
+ .meta(acp_v1::Meta::from_iter([(
+ "link".into(),
+ json!("original"),
+ )])),
),
];
let mut content = MessageContent::default();
@@ -5683,22 +5743,28 @@ mod tests {
let mut content = MessageContent::default();
for chunk in [
"before".into(),
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("resource text", "tool://preview"),
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new("resource text", "tool://preview"),
),
)),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"link",
"https://example.com/resource",
)),
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::BlobResourceContents(
- acp::BlobResourceContents::new("private-blob-data", "tool://archive.bin"),
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new(
+ "private-blob-data",
+ "tool://archive.bin",
+ ),
),
)),
- acp::ContentBlock::Image(acp::ImageContent::new("not-base64", "image/png")),
- acp::ContentBlock::Audio(acp::AudioContent::new("private-audio-data", "audio/wav")),
+ acp_v2::ContentBlock::Image(acp_v2::ImageContent::new("not-base64", "image/png")),
+ acp_v2::ContentBlock::Audio(acp_v2::AudioContent::new(
+ "private-audio-data",
+ "audio/wav",
+ )),
"after".into(),
] {
content.append(chunk, &language_registry, PathStyle::local(), cx);
@@ -5760,6 +5826,54 @@ mod tests {
});
}
+ #[gpui::test]
+ fn test_v2_other_content_preserves_raw_source_and_renders_fallback(cx: &mut TestAppContext) {
+ init_test(cx);
+ cx.update(|cx| {
+ let language_registry =
+ Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
+ let raw_fields = std::collections::BTreeMap::from([
+ (
+ "payload".to_string(),
+ json!({"nested": [1, {"value": "original"}]}),
+ ),
+ ("_meta".to_string(), json!({"source": "future-agent"})),
+ ]);
+ let source = acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
+ "_custom_payload",
+ raw_fields.clone(),
+ ));
+
+ let content =
+ MessageContent::new(source.clone(), &language_registry, PathStyle::local(), cx);
+ let rendered_blocks = content.blocks().collect::<Vec<_>>();
+ let [rendered] = rendered_blocks.as_slice() else {
+ panic!("expected one fallback block");
+ };
+ assert_eq!(content.source_blocks(), std::slice::from_ref(&source));
+ assert!(std::ptr::eq(
+ rendered.source.expect("fallback source"),
+ &content.source_blocks()[0],
+ ));
+ assert_eq!(rendered.unsupported_content(), Some(&source));
+ assert_eq!(
+ rendered.to_markdown(cx),
+ "Unknown content type is not supported."
+ );
+
+ let output = ContentBlock::new_output(source, &language_registry, cx);
+ let Some(acp_v2::ContentBlock::Other(other)) = output.unsupported_content() else {
+ panic!("expected original unknown source");
+ };
+ assert_eq!(other.type_, "_custom_payload");
+ assert_eq!(other.fields, raw_fields);
+ assert_eq!(
+ output.to_markdown(cx),
+ "Unknown content type is not supported."
+ );
+ });
+ }
+
#[gpui::test]
async fn test_message_content_preserves_streaming_entities(cx: &mut TestAppContext) {
init_test(cx);
@@ -5774,15 +5888,15 @@ mod tests {
let source_blocks = [
"before".into(),
- acp::ContentBlock::Text(
- acp::TextContent::new(" image")
- .meta(acp::Meta::from_iter([("sequence".into(), json!(2))])),
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new(" image")
+ .meta(acp_v1::Meta::from_iter([("sequence".into(), json!(2))])),
),
message_test_image(),
"after".into(),
- acp::ContentBlock::Text(
- acp::TextContent::new(" image")
- .meta(acp::Meta::from_iter([("sequence".into(), json!(5))])),
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new(" image")
+ .meta(acp_v1::Meta::from_iter([("sequence".into(), json!(5))])),
),
];
let (before, after, image) = thread.update(cx, |thread, cx| {
@@ -5885,16 +5999,19 @@ mod tests {
for (content, preview) in [
(
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("Resource preview", "tool://preview")
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new("Resource preview", "tool://preview")
.mime_type("text/markdown".to_string()),
),
)),
"Resource preview",
),
(
- acp::ContentBlock::Audio(acp::AudioContent::new("private-audio-data", "audio/wav")),
+ acp_v2::ContentBlock::Audio(acp_v2::AudioContent::new(
+ "private-audio-data",
+ "audio/wav",
+ )),
"Audio content is not supported.",
),
] {
@@ -5936,7 +6053,7 @@ mod tests {
let path_style = thread.project.read(cx).path_style(cx);
let languages = thread.project.read(cx).languages().clone();
let uri = "file:///project/report.md";
- let link = acp::ContentBlock::ResourceLink(acp::ResourceLink::new("report", uri));
+ let link = acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new("report", uri));
let expected = format!(
"{}\n## Details\n",
ContentBlock::resource_link_md(uri, path_style),
@@ -5985,16 +6102,16 @@ mod tests {
.expect("session should be created");
let chunks = vec![
"read ".into(),
- 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(
"attached file contents",
"https://example.com/file",
),
),
)),
" and ".into(),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v2::ContentBlock::ResourceLink(acp_v2::ResourceLink::new(
"link",
"https://example.com/link",
)),
@@ -6035,35 +6152,37 @@ mod tests {
#[test]
fn text_resource_markdown_uses_mime_type_for_code_blocks() {
- let shell = acp::TextResourceContents::new("echo 'hello from exec test'", "tool://preview")
- .mime_type("text/x-shellscript".to_string());
+ let shell =
+ acp_v2::TextResourceContents::new("echo 'hello from exec test'", "tool://preview")
+ .mime_type("text/x-shellscript".to_string());
assert_eq!(
ContentBlock::text_resource_markdown(&shell),
"```sh\necho 'hello from exec test'\n```"
);
- let markdown = acp::TextResourceContents::new("**approval** requested", "tool://preview")
- .mime_type("text/markdown".to_string());
+ let markdown =
+ acp_v2::TextResourceContents::new("**approval** requested", "tool://preview")
+ .mime_type("text/markdown".to_string());
assert_eq!(
ContentBlock::text_resource_markdown(&markdown),
"**approval** requested"
);
- let plain = acp::TextResourceContents::new("plain preview", "tool://preview")
+ let plain = acp_v2::TextResourceContents::new("plain preview", "tool://preview")
.mime_type("text/plain".to_string());
assert_eq!(
ContentBlock::text_resource_markdown(&plain),
"```\nplain preview\n```"
);
- let cpp = acp::TextResourceContents::new("int main() {}", "tool://preview")
+ let cpp = acp_v2::TextResourceContents::new("int main() {}", "tool://preview")
.mime_type("text/x-c++; charset=utf-8".to_string());
assert_eq!(
ContentBlock::text_resource_markdown(&cpp),
"```cpp\nint main() {}\n```"
);
- let untyped = acp::TextResourceContents::new("# plain preview", "tool://preview");
+ let untyped = acp_v2::TextResourceContents::new("# plain preview", "tool://preview");
assert_eq!(
ContentBlock::text_resource_markdown(&untyped),
"```\n# plain preview\n```"
@@ -6079,10 +6198,13 @@ mod tests {
cx.update(|cx| {
let language_registry =
Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
- let content = acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("echo 'hello from exec test'", "tool://preview")
- .mime_type("text/x-shellscript".to_string()),
+ let content = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new(
+ "echo 'hello from exec test'",
+ "tool://preview",
+ )
+ .mime_type("text/x-shellscript".to_string()),
),
));
@@ -6092,10 +6214,13 @@ mod tests {
panic!("expected embedded resource block, got {block:?}");
};
match &resource.resource {
- acp::EmbeddedResourceResource::TextResourceContents(text) => {
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => {
assert_eq!(text.text, "echo 'hello from exec test'");
assert_eq!(text.uri, "tool://preview");
- assert_eq!(text.mime_type.as_deref(), Some("text/x-shellscript"));
+ assert_eq!(
+ text.mime_type.as_ref().map(AsRef::as_ref),
+ Some("text/x-shellscript")
+ );
}
other => panic!("expected text resource contents, got {other:?}"),
}
@@ -6114,9 +6239,9 @@ mod tests {
assert_eq!(block.text_content(cx), Some("echo 'hello from exec test'"));
let untyped = ContentBlock::new_output(
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("# plain preview", "tool://preview"),
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new("# plain preview", "tool://preview"),
),
)),
&language_registry,
@@ -6136,9 +6261,9 @@ mod tests {
cx.update(|cx| {
let language_registry =
Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
- let image_blob = acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::BlobResourceContents(
- acp::BlobResourceContents::new(
+ let image_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
"tool://preview.png",
)
@@ -6174,9 +6299,9 @@ mod tests {
cx.update(|cx| {
let language_registry =
Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
- let archive_blob = acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::BlobResourceContents(
- acp::BlobResourceContents::new("not an image", "tool://archive.bin")
+ let archive_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new("not an image", "tool://archive.bin")
.mime_type("application/octet-stream".to_string()),
),
));
@@ -6188,18 +6313,21 @@ mod tests {
};
assert!(markdown.is_none());
match &resource.resource {
- acp::EmbeddedResourceResource::BlobResourceContents(blob) => {
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => {
assert_eq!(blob.uri, "tool://archive.bin");
- assert_eq!(blob.mime_type.as_deref(), Some("application/octet-stream"));
+ assert_eq!(
+ blob.mime_type.as_ref().map(AsRef::as_ref),
+ Some("application/octet-stream")
+ );
}
other => panic!("expected blob resource contents, got {other:?}"),
}
assert_eq!(block.to_markdown(cx), "tool://archive.bin");
assert_eq!(block.text_content(cx), None);
- let invalid_image_blob = acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::BlobResourceContents(
- acp::BlobResourceContents::new("not-base64", "tool://preview.png")
+ let invalid_image_blob = acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new("not-base64", "tool://preview.png")
.mime_type("image/png".to_string()),
),
));
@@ -6249,7 +6377,7 @@ mod tests {
.await
.unwrap();
- let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
// Send Output BEFORE Created - should be buffered by acp_thread
thread.update(cx, |thread, cx| {
@@ -6318,7 +6446,7 @@ mod tests {
.await
.unwrap();
- let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
let lower = cx.new(|cx| {
let builder = ::terminal::TerminalBuilder::new_display_only(
::terminal::terminal_settings::CursorShape::default(),
@@ -6388,7 +6516,7 @@ mod tests {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
- status: acp::TerminalExitStatus::new().exit_code(7),
+ status: acp_v1::TerminalExitStatus::new().exit_code(7),
},
cx,
);
@@ -6440,7 +6568,7 @@ mod tests {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
- status: acp::TerminalExitStatus::new().signal("SIGTERM"),
+ status: acp_v1::TerminalExitStatus::new().signal("SIGTERM"),
},
cx,
);
@@ -6492,7 +6620,7 @@ mod tests {
.await
.unwrap();
- let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
// Send Output BEFORE Created
thread.update(cx, |thread, cx| {
@@ -6510,14 +6638,14 @@ mod tests {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
- status: acp::TerminalExitStatus::new().signal("SIGTERM"),
+ status: acp_v1::TerminalExitStatus::new().signal("SIGTERM"),
},
cx,
);
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id.clone(),
- status: acp::TerminalExitStatus::new().exit_code(0),
+ status: acp_v1::TerminalExitStatus::new().exit_code(0),
},
cx,
);
@@ -6617,7 +6745,7 @@ mod tests {
.await
.unwrap();
- let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
// We use printf instead of echo and chain with && sleep to ensure proper execution
let (program, args) = ShellBuilder::new(&Shell::System, false).build(
@@ -6846,40 +6974,40 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("First ".into()).message_id("msg_user_1"),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("First ".into()).message_id("msg_user_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("message".into()).message_id("msg_user_1"),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("message".into()).message_id("msg_user_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("Second message".into()).message_id("msg_user_2"),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("Second message".into()).message_id("msg_user_2"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("Echo".into()).message_id("msg_user_3"),
),
cx,
)
@@ -6957,8 +7085,8 @@ mod tests {
);
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(
- acp::ContentChunk::new("Agent user chunk".into())
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new("Agent user chunk".into())
.message_id("agent_user_chunk"),
),
cx,
@@ -7012,24 +7140,24 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AgentThoughtChunk(
- acp::ContentChunk::new("Thinking ".into()).message_id("msg_thought_1"),
+ acp_v1::SessionUpdate::AgentThoughtChunk(
+ acp_v1::ContentChunk::new("Thinking ".into()).message_id("msg_thought_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentThoughtChunk(
- acp::ContentChunk::new("hard".into()).message_id("msg_thought_1"),
+ acp_v1::SessionUpdate::AgentThoughtChunk(
+ acp_v1::ContentChunk::new("hard".into()).message_id("msg_thought_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentThoughtChunk(
- acp::ContentChunk::new("A separate thought".into())
+ acp_v1::SessionUpdate::AgentThoughtChunk(
+ acp_v1::ContentChunk::new("A separate thought".into())
.message_id("msg_thought_2"),
),
cx,
@@ -7037,24 +7165,24 @@ mod tests {
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Answer ".into()).message_id("msg_agent_1"),
+ acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Answer ".into()).message_id("msg_agent_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("done".into()).message_id("msg_agent_1"),
+ acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("done".into()).message_id("msg_agent_1"),
),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Follow-up".into()).message_id("msg_agent_2"),
+ acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Follow-up".into()).message_id("msg_agent_2"),
),
cx,
)
@@ -7118,22 +7246,22 @@ mod tests {
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
- "Thinking ".into(),
- )),
+ acp_v1::SessionUpdate::AgentThoughtChunk(
+ acp_v1::ContentChunk::new("Thinking ".into()),
+ ),
cx,
)
.unwrap();
thread
.handle_session_update(
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
- "hard!".into(),
- )),
+ acp_v1::SessionUpdate::AgentThoughtChunk(
+ acp_v1::ContentChunk::new("hard!".into()),
+ ),
cx,
)
.unwrap();
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
},
@@ -7185,7 +7313,7 @@ mod tests {
move |request, thread, mut cx| {
let received_prompt = received_prompt.clone();
async move {
- if let Some(acp::ContentBlock::Text(text)) = request.prompt.first() {
+ if let Some(acp_v1::ContentBlock::Text(text)) = request.prompt.first() {
*received_prompt.borrow_mut() = Some(text.text.clone());
}
// Simulate a native command producing its own thread entry
@@ -7201,7 +7329,7 @@ mod tests {
cx,
);
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -7262,15 +7390,15 @@ mod tests {
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UserMessageChunk(acp::ContentChunk::new(
- prompt,
- )),
+ acp_v1::SessionUpdate::UserMessageChunk(
+ acp_v1::ContentChunk::new(prompt),
+ ),
cx,
)
.unwrap();
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}),
@@ -7334,7 +7462,7 @@ mod tests {
.unwrap()
.await
.unwrap();
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
},
@@ -7564,7 +7692,7 @@ mod tests {
.await
.unwrap_err();
- assert_eq!(err.code, acp::ErrorCode::ResourceNotFound);
+ assert_eq!(err.code, acp_v1::ErrorCode::ResourceNotFound);
}
#[gpui::test]
@@ -7573,7 +7701,7 @@ mod tests {
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
- let id = acp::ToolCallId::new("test");
+ let id = acp_v1::ToolCallId::new("test");
let connection = Rc::new(FakeAgentConnection::new().on_user_message({
let id = id.clone();
@@ -7583,17 +7711,17 @@ mod tests {
thread
.update(&mut cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(id.clone(), "Label")
- .kind(acp::ToolKind::Fetch)
- .status(acp::ToolCallStatus::InProgress),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(id.clone(), "Label")
+ .kind(acp_v1::ToolKind::Fetch)
+ .status(acp_v1::ToolCallStatus::InProgress),
),
cx,
)
})
.unwrap()
.unwrap();
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -7637,9 +7765,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
id,
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::Completed),
)),
cx,
)
@@ -7677,13 +7806,13 @@ mod tests {
for summary in ["retained context", "replacement summary"] {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(
- acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(
+ acp_v1::CompactionUpdate::new(
"compaction",
- acp::CompactionStatus::Completed,
+ acp_v1::CompactionStatus::Completed,
)
- .summary(vec![acp::ContentBlock::Text(
- acp::TextContent::new(summary),
+ .summary(vec![acp_v1::ContentBlock::Text(
+ acp_v1::TextContent::new(summary),
)]),
),
cx,
@@ -7710,10 +7839,13 @@ mod tests {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(
- acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Failed)
- .summary(None::<Vec<acp::ContentBlock>>)
- .error("model unavailable"),
+ acp_v1::SessionUpdate::CompactionUpdate(
+ acp_v1::CompactionUpdate::new(
+ "compaction",
+ acp_v1::CompactionStatus::Failed,
+ )
+ .summary(None::<Vec<acp_v1::ContentBlock>>)
+ .error("model unavailable"),
),
cx,
)
@@ -7748,9 +7880,12 @@ mod tests {
};
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(
- acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Failed)
- .error(error),
+ acp_v1::SessionUpdate::CompactionUpdate(
+ acp_v1::CompactionUpdate::new(
+ "compaction",
+ acp_v1::CompactionStatus::Failed,
+ )
+ .error(error),
),
cx,
)
@@ -7776,16 +7911,16 @@ mod tests {
}
for summary in [
- vec![acp::ContentBlock::Text(acp::TextContent::new(""))],
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(""))],
Vec::new(),
] {
let expected_length = summary.len();
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(
- acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(
+ acp_v1::CompactionUpdate::new(
"compaction",
- acp::CompactionStatus::Completed,
+ acp_v1::CompactionStatus::Completed,
)
.summary(summary),
),
@@ -7814,35 +7949,53 @@ mod tests {
.expect("failed to create ACP thread");
let image_data = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==";
let text_resource =
- acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("Retained resource text", "summary://context")
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new("Retained resource text", "summary://context")
.mime_type("text/markdown".to_string()),
));
let blob_resource =
- acp::EmbeddedResource::new(acp::EmbeddedResourceResource::BlobResourceContents(
- acp::BlobResourceContents::new("c3VtbWFyeQ==", "summary://attachment")
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents(
+ acp_v1::BlobResourceContents::new("c3VtbWFyeQ==", "summary://attachment")
.mime_type("application/octet-stream".to_string()),
));
- let audio = acp::ContentBlock::Audio(acp::AudioContent::new("YXVkaW8=", "audio/wav"));
+ let audio = acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new("YXVkaW8=", "audio/wav"));
let blocks = vec![
- acp::ContentBlock::Text(acp::TextContent::new("retained ")),
- acp::ContentBlock::Text(acp::TextContent::new("context")),
- acp::ContentBlock::Resource(text_resource.clone()),
- acp::ContentBlock::Image(acp::ImageContent::new(image_data, "image/png")),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("retained ")),
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("context")),
+ acp_v1::ContentBlock::Resource(text_resource),
+ acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(image_data, "image/png")),
+ acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
"Reference",
"https://example.com/context",
)),
audio.clone(),
- acp::ContentBlock::Resource(blob_resource.clone()),
+ acp_v1::ContentBlock::Resource(blob_resource),
];
+ let source_blocks = blocks
+ .iter()
+ .cloned()
+ .map(content::from_v1)
+ .collect::<Result<Vec<_>>>()
+ .expect("convert retained content");
+ let [
+ _,
+ _,
+ acp_v2::ContentBlock::Resource(text_resource),
+ _,
+ _,
+ stored_audio,
+ acp_v2::ContentBlock::Resource(blob_resource),
+ ] = source_blocks.as_slice()
+ else {
+ panic!("expected retained summary content");
+ };
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(
"compaction",
- acp::CompactionStatus::InProgress,
+ acp_v1::CompactionStatus::InProgress,
)),
cx,
)
@@ -7850,8 +8003,8 @@ mod tests {
for block in &blocks {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionSummaryChunk(
- acp::CompactionSummaryChunk::new("compaction", block.clone()),
+ acp_v1::SessionUpdate::CompactionSummaryChunk(
+ acp_v1::CompactionSummaryChunk::new("compaction", block.clone()),
),
cx,
)
@@ -7861,13 +8014,15 @@ mod tests {
for replace_summary in [false, true] {
thread.update(cx, |thread, cx| {
- let mut update =
- acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Completed);
+ let mut update = acp_v1::CompactionUpdate::new(
+ "compaction",
+ acp_v1::CompactionStatus::Completed,
+ );
if replace_summary {
update = update.summary(blocks.clone());
}
thread
- .handle_session_update(acp::SessionUpdate::CompactionUpdate(update), cx)
+ .handle_session_update(acp_v1::SessionUpdate::CompactionUpdate(update), cx)
.expect("failed to complete compaction");
});
thread.read_with(cx, |thread, cx| {
@@ -7886,7 +8041,7 @@ mod tests {
.as_view()
.embedded_resource()
.map(|(resource, _)| resource),
- Some(&text_resource)
+ Some(text_resource)
);
assert_eq!(resource.to_markdown(cx), "Retained resource text");
assert_eq!(
@@ -7903,13 +8058,13 @@ mod tests {
let Some(content) = unsupported.unsupported_content() else {
panic!("expected preserved audio with a visible fallback");
};
- assert_eq!(content, &audio);
+ assert_eq!(content, stored_audio);
assert!(unsupported.visible_content(cx));
assert_eq!(
blob.as_view()
.embedded_resource()
.map(|(resource, _)| resource),
- Some(&blob_resource)
+ Some(blob_resource)
);
assert!(blob.visible_content(cx));
assert_eq!(
@@ -7930,9 +8085,12 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(
- acp::CompactionUpdate::new("compaction", acp::CompactionStatus::Completed)
- .summary(vec![audio.clone()]),
+ acp_v1::SessionUpdate::CompactionUpdate(
+ acp_v1::CompactionUpdate::new(
+ "compaction",
+ acp_v1::CompactionStatus::Completed,
+ )
+ .summary(vec![audio.clone()]),
),
cx,
)
@@ -7945,7 +8103,7 @@ mod tests {
};
assert!(matches!(
compaction.summary.as_slice(),
- [block] if block.unsupported_content() == Some(&audio)
+ [block] if block.unsupported_content() == Some(stored_audio)
));
assert!(
thread
@@ -7980,22 +8138,22 @@ mod tests {
thread.update(cx, |thread, cx| {
for update in [
- acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(
"first",
- acp::CompactionStatus::InProgress,
+ acp_v1::CompactionStatus::InProgress,
)),
- acp::SessionUpdate::ToolCall(acp::ToolCall::new("tool", "Unrelated tool")),
- acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::ToolCall(acp_v1::ToolCall::new("tool", "Unrelated tool")),
+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(
"second",
- acp::CompactionStatus::InProgress,
+ acp_v1::CompactionStatus::InProgress,
)),
- acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(
"second",
- acp::CompactionStatus::Completed,
+ acp_v1::CompactionStatus::Completed,
)),
- acp::SessionUpdate::CompactionSummaryChunk(acp::CompactionSummaryChunk::new(
+ acp_v1::SessionUpdate::CompactionSummaryChunk(acp_v1::CompactionSummaryChunk::new(
"first",
- acp::ContentBlock::Text(acp::TextContent::new("partial summary")),
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("partial summary")),
)),
] {
thread
@@ -8009,9 +8167,9 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::CompactionUpdate(acp::CompactionUpdate::new(
+ acp_v1::SessionUpdate::CompactionUpdate(acp_v1::CompactionUpdate::new(
"first",
- acp::CompactionStatus::Cancelled,
+ acp_v1::CompactionStatus::Cancelled,
)),
cx,
)
@@ -8052,37 +8210,37 @@ mod tests {
cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));
for (call, expected, has_strong_text) in [
(
- acp::ToolCall::new("tool", "Reading **file**").name("read_file"),
+ acp_v1::ToolCall::new("tool", "Reading **file**").name("read_file"),
"Reading **file**",
true,
),
- (acp::ToolCall::new("tool", ""), "Tool call", false),
+ (acp_v1::ToolCall::new("tool", ""), "Tool call", false),
(
- acp::ToolCall::new("tool", "\n\t ").name(" \t"),
+ acp_v1::ToolCall::new("tool", "\n\t ").name(" \t"),
"Tool call",
false,
),
(
- acp::ToolCall::new("tool", "").name("**mcp__tool**"),
+ acp_v1::ToolCall::new("tool", "").name("**mcp__tool**"),
"**mcp__tool**",
false,
),
(
- acp::ToolCall::new("tool", "\n\t ")
+ acp_v1::ToolCall::new("tool", "\n\t ")
.name("**mcp__tool**")
- .kind(acp::ToolKind::Edit),
+ .kind(acp_v1::ToolKind::Edit),
"**mcp__tool**",
false,
),
(
- acp::ToolCall::new("tool", "")
+ acp_v1::ToolCall::new("tool", "")
.name("**mcp__tool**")
- .kind(acp::ToolKind::Execute),
+ .kind(acp_v1::ToolKind::Execute),
"**mcp__tool**",
false,
),
(
- acp::ToolCall::new("tool", "").meta(meta_with_tool_name("legacy_tool")),
+ acp_v1::ToolCall::new("tool", "").meta(meta_with_tool_name("legacy_tool")),
"legacy_tool",
false,
),
@@ -8129,7 +8287,7 @@ mod tests {
cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));
let mut call = cx.update(|cx| {
ToolCall::from_acp(
- acp::ToolCall::new("tool", ""),
+ acp_v1::ToolCall::new("tool", ""),
ToolCallStatus::Pending,
languages.clone(),
&HashMap::default(),
@@ -8139,49 +8297,49 @@ mod tests {
});
for (update, expected, has_strong_text) in [
(
- acp::ToolCallUpdateFields::new().name("**tool_name**"),
+ acp_v1::ToolCallUpdateFields::new().name("**tool_name**"),
"**tool_name**",
false,
),
(
- acp::ToolCallUpdateFields::new().title("**Readable title**"),
+ acp_v1::ToolCallUpdateFields::new().title("**Readable title**"),
"**Readable title**",
true,
),
(
- acp::ToolCallUpdateFields::new().name("renamed_tool"),
+ acp_v1::ToolCallUpdateFields::new().name("renamed_tool"),
"**Readable title**",
true,
),
(
- acp::ToolCallUpdateFields::new().kind(acp::ToolKind::Execute),
+ acp_v1::ToolCallUpdateFields::new().kind(acp_v1::ToolKind::Execute),
"**Readable title**",
false,
),
(
- acp::ToolCallUpdateFields::new().kind(acp::ToolKind::Read),
+ acp_v1::ToolCallUpdateFields::new().kind(acp_v1::ToolKind::Read),
"**Readable title**",
true,
),
(
- acp::ToolCallUpdateFields::new().title("\n\t "),
+ acp_v1::ToolCallUpdateFields::new().title("\n\t "),
"renamed_tool",
false,
),
(
- acp::ToolCallUpdateFields::new().name(" \t"),
+ acp_v1::ToolCallUpdateFields::new().name(" \t"),
"Tool call",
false,
),
(
- acp::ToolCallUpdateFields::new()
+ acp_v1::ToolCallUpdateFields::new()
.title("**same_name**")
.name("**same_name**"),
"**same_name**",
true,
),
(
- acp::ToolCallUpdateFields::new().name("different_name"),
+ acp_v1::ToolCallUpdateFields::new().name("different_name"),
"**same_name**",
true,
),
@@ -8213,7 +8371,7 @@ mod tests {
cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));
let mut created_with_raw_output = cx.update(|cx| {
ToolCall::from_acp(
- acp::ToolCall::new("created", "Tool").raw_output(serde_json::json!("first")),
+ acp_v1::ToolCall::new("created", "Tool").raw_output(serde_json::json!("first")),
ToolCallStatus::Pending,
languages.clone(),
&HashMap::default(),
@@ -8223,7 +8381,7 @@ mod tests {
});
let mut updated_with_raw_output = cx.update(|cx| {
ToolCall::from_acp(
- acp::ToolCall::new("updated", "Tool"),
+ acp_v1::ToolCall::new("updated", "Tool"),
ToolCallStatus::Pending,
languages.clone(),
&HashMap::default(),
@@ -8236,7 +8394,7 @@ mod tests {
cx.update(|cx| {
updated_with_raw_output
.update_fields(
- acp::ToolCallUpdateFields::new().raw_output(serde_json::json!("first")),
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("first")),
None,
languages.clone(),
&HashMap::default(),
@@ -8256,7 +8414,7 @@ mod tests {
cx.update(|cx| {
created_with_raw_output
.update_fields(
- acp::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
None,
languages.clone(),
&HashMap::default(),
@@ -8265,7 +8423,7 @@ mod tests {
.expect("second raw output update should apply");
updated_with_raw_output
.update_fields(
- acp::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("second")),
None,
languages.clone(),
&HashMap::default(),
@@ -8302,7 +8460,7 @@ mod tests {
cx.update(|cx| Arc::new(LanguageRegistry::test(cx.background_executor().clone())));
let mut call = cx.update(|cx| {
ToolCall::from_acp(
- acp::ToolCall::new("tool", "Tool")
+ acp_v1::ToolCall::new("tool", "Tool")
.content(vec!["structured".into()])
.raw_output(serde_json::json!("raw")),
ToolCallStatus::Pending,
@@ -8320,7 +8478,7 @@ mod tests {
});
cx.update(|cx| {
call.update_fields(
- acp::ToolCallUpdateFields::new().raw_output(serde_json::json!("new raw")),
+ acp_v1::ToolCallUpdateFields::new().raw_output(serde_json::json!("new raw")),
None,
languages.clone(),
&HashMap::default(),
@@ -8334,7 +8492,7 @@ mod tests {
});
cx.update(|cx| {
call.update_fields(
- acp::ToolCallUpdateFields::new().content(vec![]),
+ acp_v1::ToolCallUpdateFields::new().content(vec![]),
None,
languages.clone(),
&HashMap::default(),
@@ -8351,7 +8509,7 @@ mod tests {
});
cx.update(|cx| {
call.update_fields(
- acp::ToolCallUpdateFields::new().content(vec!["replacement".into()]),
+ acp_v1::ToolCallUpdateFields::new().content(vec!["replacement".into()]),
None,
languages,
&HashMap::default(),
@@ -8382,8 +8540,8 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("tool-call", "Tool call")
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("tool-call", "Tool call")
.name("first_class")
.meta(meta_with_tool_name("legacy")),
),
@@ -8402,8 +8560,8 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("legacy-tool-call", "Legacy tool call")
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("legacy-tool-call", "Legacy tool call")
.meta(meta_with_tool_name("legacy")),
),
cx,
@@ -8421,9 +8579,12 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(
- acp::ToolCallUpdate::new("tool-call", acp::ToolCallUpdateFields::new())
- .meta(meta_with_tool_name("legacy_update")),
+ acp_v1::SessionUpdate::ToolCallUpdate(
+ acp_v1::ToolCallUpdate::new(
+ "tool-call",
+ acp_v1::ToolCallUpdateFields::new(),
+ )
+ .meta(meta_with_tool_name("legacy_update")),
),
cx,
)
@@ -8433,7 +8594,7 @@ mod tests {
thread.read_with(cx, |thread, _| {
let Some(tool_call) = thread.entries.iter().find_map(|entry| match entry {
AgentThreadEntry::ToolCall(tool_call)
- if tool_call.id == acp::ToolCallId::new("tool-call") =>
+ if tool_call.id == acp_v1::ToolCallId::new("tool-call") =>
{
Some(tool_call)
}
@@ -8447,10 +8608,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(
- acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(
+ acp_v1::ToolCallUpdate::new(
"legacy-tool-call",
- acp::ToolCallUpdateFields::new().name("first_class_update"),
+ acp_v1::ToolCallUpdateFields::new().name("first_class_update"),
)
.meta(meta_with_tool_name("ignored_legacy_update")),
),
@@ -8462,7 +8623,7 @@ mod tests {
thread.read_with(cx, |thread, _| {
let Some(tool_call) = thread.entries.iter().find_map(|entry| match entry {
AgentThreadEntry::ToolCall(tool_call)
- if tool_call.id == acp::ToolCallId::new("legacy-tool-call") =>
+ if tool_call.id == acp_v1::ToolCallId::new("legacy-tool-call") =>
{
Some(tool_call)
}
@@ -8476,7 +8637,7 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(acp::ToolCall::new(
+ acp_v1::SessionUpdate::ToolCall(acp_v1::ToolCall::new(
"late-legacy-tool-call",
"Late legacy tool call",
)),
@@ -8487,10 +8648,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(
- acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(
+ acp_v1::ToolCallUpdate::new(
"late-legacy-tool-call",
- acp::ToolCallUpdateFields::new(),
+ acp_v1::ToolCallUpdateFields::new(),
)
.meta(meta_with_tool_name("late_legacy")),
),
@@ -8510,12 +8671,12 @@ mod tests {
#[gpui::test]
fn test_context_compaction_exports_status(cx: &mut App) {
for (status, expected_label) in [
- (acp::CompactionStatus::InProgress, "In Progress"),
- (acp::CompactionStatus::Completed, "Completed"),
- (acp::CompactionStatus::Failed, "Failed"),
- (acp::CompactionStatus::Cancelled, "Canceled"),
+ (acp_v1::CompactionStatus::InProgress, "In Progress"),
+ (acp_v1::CompactionStatus::Completed, "Completed"),
+ (acp_v1::CompactionStatus::Failed, "Failed"),
+ (acp_v1::CompactionStatus::Cancelled, "Canceled"),
(
- acp::CompactionStatus::Other("interrupted".into()),
+ acp_v1::CompactionStatus::Other("interrupted".into()),
"interrupted",
),
] {
@@ -8555,11 +8716,11 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("write_file", "Write SKILL.md")
- .kind(acp::ToolKind::Edit)
- .status(acp::ToolCallStatus::Completed)
- .locations(vec![acp::ToolCallLocation::new(skill_path.clone())]),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("write_file", "Write SKILL.md")
+ .kind(acp_v1::ToolKind::Edit)
+ .status(acp_v1::ToolCallStatus::Completed)
+ .locations(vec![acp_v1::ToolCallLocation::new(skill_path.clone())]),
),
cx,
)
@@ -8598,20 +8759,20 @@ mod tests {
.await
.unwrap();
- let tool_call_id = acp::ToolCallId::new("toolu_01duplicate");
- let allow_option_id = acp::PermissionOptionId::new("allow");
+ let tool_call_id = acp_v1::ToolCallId::new("toolu_01duplicate");
+ let allow_option_id = acp_v1::PermissionOptionId::new("allow");
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id.clone(), "Original title")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Original title")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.content(vec!["original content".into()])
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
allow_option_id.clone(),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -8622,10 +8783,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(tool_call_id.clone(), "Updated title")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Updated title")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.content(vec!["updated content".into()]),
),
cx,
@@ -8649,10 +8810,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_call_id.clone(),
- acp::ToolCallUpdateFields::new()
- .status(acp::ToolCallStatus::InProgress)
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::InProgress)
.title("Updated again")
.content(vec!["updated again".into()]),
)),
@@ -8676,7 +8837,7 @@ mod tests {
let selected_outcome = SelectedPermissionOutcome::new(
allow_option_id.clone(),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
);
thread.update(cx, |thread, cx| {
thread.authorize_tool_call(tool_call_id.clone(), selected_outcome, cx);
@@ -8692,7 +8853,7 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
assert_eq!(outcome.option_id, allow_option_id);
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -8703,10 +8864,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_call_id.clone(),
- acp::ToolCallUpdateFields::new()
- .status(acp::ToolCallStatus::Completed)
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::Completed)
.title("Completed")
.content(vec!["done".into()]),
)),
@@ -8740,18 +8901,18 @@ mod tests {
.await
.unwrap();
- let tool_call_id = acp::ToolCallId::new("toolu_01auto_resolve");
+ let tool_call_id = acp_v1::ToolCallId::new("toolu_01auto_resolve");
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id.clone(), "Original title")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Original title")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -8762,9 +8923,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_call_id.clone(),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::InProgress),
)),
cx,
)
@@ -8778,7 +8940,7 @@ mod tests {
assert!(matches!(
tool_call.status,
ToolCallStatus::WaitingForConfirmation {
- current_status: acp::ToolCallStatus::InProgress,
+ current_status: acp_v1::ToolCallStatus::InProgress,
..
}
));
@@ -8788,8 +8950,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id.clone(),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -8804,8 +8966,8 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
- assert_eq!(outcome.option_id, acp::PermissionOptionId::new("allow"));
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_id, acp_v1::PermissionOptionId::new("allow"));
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -8830,14 +8992,14 @@ mod tests {
.await
.unwrap();
- let tool_call_id = acp::ToolCallId::new("toolu_01existing_permission");
+ let tool_call_id = acp_v1::ToolCallId::new("toolu_01existing_permission");
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(tool_call_id.clone(), "Running title")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::InProgress),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Running title")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::InProgress),
),
cx,
)
@@ -8847,14 +9009,14 @@ mod tests {
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id.clone(), "Needs permission")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Needs permission")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -8870,7 +9032,7 @@ mod tests {
assert!(matches!(
tool_call.status,
ToolCallStatus::WaitingForConfirmation {
- current_status: acp::ToolCallStatus::InProgress,
+ current_status: acp_v1::ToolCallStatus::InProgress,
..
}
));
@@ -8880,8 +9042,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id.clone(),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -8889,8 +9051,8 @@ mod tests {
match permission_task.await {
RequestPermissionOutcome::Selected(outcome) => {
- assert_eq!(outcome.option_id, acp::PermissionOptionId::new("allow"));
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_id, acp_v1::PermissionOptionId::new("allow"));
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
RequestPermissionOutcome::Cancelled
| RequestPermissionOutcome::InterruptedByFollowUp => {
@@ -8915,18 +9077,18 @@ mod tests {
.await
.unwrap();
- let tool_call_id = acp::ToolCallId::new("toolu_01cancelled_permission");
+ let tool_call_id = acp_v1::ToolCallId::new("toolu_01cancelled_permission");
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id.clone(), "Needs permission")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Needs permission")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -8970,18 +9132,18 @@ mod tests {
.await
.unwrap();
- let tool_call_id = acp::ToolCallId::new("toolu_01completed_while_waiting");
+ let tool_call_id = acp_v1::ToolCallId::new("toolu_01completed_while_waiting");
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id.clone(), "Needs permission")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::Pending)
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Needs permission")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::Pending)
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
AuthorizationKind::PermissionGrant,
cx,
@@ -8992,9 +9154,10 @@ mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_call_id.clone(),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::Completed),
)),
cx,
)
@@ -9030,21 +9193,20 @@ mod tests {
thread
.update(&mut cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("test", "Label")
- .kind(acp::ToolKind::Edit)
- .status(acp::ToolCallStatus::Completed)
- .content(vec![acp::ToolCallContent::Diff(acp::Diff::new(
- "/test/test.txt",
- "foo",
- ))]),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("test", "Label")
+ .kind(acp_v1::ToolKind::Edit)
+ .status(acp_v1::ToolCallStatus::Completed)
+ .content(vec![acp_v1::ToolCallContent::Diff(
+ acp_v1::Diff::new("/test/test.txt", "foo"),
+ )]),
),
cx,
)
})
.unwrap()
.unwrap();
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -9093,20 +9255,20 @@ mod tests {
fs.write(Path::new(&filename), b"").await?;
}
- let acp::ContentBlock::Text(content) = &request.prompt[0] else {
+ let acp_v1::ContentBlock::Text(content) = &request.prompt[0] else {
panic!("expected text content block");
};
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
- content.text.to_uppercase().into(),
- )),
+ acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(content.text.to_uppercase().into()),
+ ),
cx,
)
.unwrap();
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -9303,7 +9465,7 @@ mod tests {
finish_response_rx.await.ok();
}
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -9377,10 +9539,10 @@ mod tests {
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("tool1", "Test Tool")
- .kind(acp::ToolKind::Fetch)
- .status(acp::ToolCallStatus::Completed)
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("tool1", "Test Tool")
+ .kind(acp_v1::ToolKind::Fetch)
+ .status(acp_v1::ToolCallStatus::Completed)
.raw_input(serde_json::json!({"query": "test"}))
.raw_output(serde_json::json!({"result": "inappropriate content"})),
),
@@ -9390,9 +9552,9 @@ mod tests {
})?;
// Now return refusal because of the tool result
- Ok(acp::PromptResponse::new(acp::StopReason::Refusal))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal))
} else {
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
}
.boxed_local()
@@ -9468,10 +9630,10 @@ mod tests {
let refuse_next = refuse_next.clone();
move |_request, _thread, _cx| {
if refuse_next.load(SeqCst) {
- async move { Ok(acp::PromptResponse::new(acp::StopReason::Refusal)) }
+ async move { Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal)) }
.boxed_local()
} else {
- async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }
+ async move { Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) }
.boxed_local()
}
}
@@ -9531,23 +9693,23 @@ mod tests {
let refuse_next = refuse_next.clone();
async move {
if refuse_next.load(SeqCst) {
- return Ok(acp::PromptResponse::new(acp::StopReason::Refusal));
+ return Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal));
}
- let acp::ContentBlock::Text(content) = &request.prompt[0] else {
+ let acp_v1::ContentBlock::Text(content) = &request.prompt[0] else {
panic!("expected text content block");
};
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
- content.text.to_uppercase().into(),
- )),
+ acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(content.text.to_uppercase().into()),
+ ),
cx,
)
.unwrap();
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -9647,10 +9809,10 @@ mod tests {
let result = thread.update(cx, |thread, cx| {
thread.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -9673,16 +9835,16 @@ mod tests {
enable_acp_beta(cx);
let thread = new_test_thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
- let tool_call_id = acp::ToolCallId::new("tool-1");
+ let tool_call_id = acp_v1::ToolCallId::new("tool-1");
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id.clone())
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id.clone())
.tool_call_id(tool_call_id.clone()),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -9693,7 +9855,7 @@ mod tests {
let elicitation_id = thread.read_with(cx, |thread, _| {
let (elicitation_id, elicitation) = only_thread_elicitation(thread);
- let acp::ElicitationScope::Session(scope) = elicitation.request.scope() else {
+ let acp_v1::ElicitationScope::Session(scope) = elicitation.request.scope() else {
panic!("expected session-scoped elicitation");
};
assert_eq!(scope.tool_call_id.as_ref(), Some(&tool_call_id));
@@ -9702,13 +9864,13 @@ mod tests {
let expected_content = std::collections::BTreeMap::from([(
"name".to_string(),
- acp::ElicitationContentValue::from("Ada"),
+ acp_v1::ElicitationContentValue::from("Ada"),
)]);
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(expected_content.clone()),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new().content(expected_content.clone()),
)),
cx,
);
@@ -9717,8 +9879,8 @@ mod tests {
let response = response_task.await;
assert_eq!(
response.action,
- acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(expected_content)
+ acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new().content(expected_content)
)
);
thread.read_with(cx, |thread, _| {
@@ -9735,14 +9897,14 @@ mod tests {
enable_acp_beta(cx);
let thread = new_test_thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(session_id),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -9773,15 +9935,15 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
thread.update(cx, |thread, cx| {
thread.complete_url_elicitation(&url_elicitation_id, cx);
@@ -9800,14 +9962,14 @@ mod tests {
enable_acp_beta(cx);
let thread = new_test_thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(session_id),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -9826,15 +9988,15 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
thread.update(cx, |thread, cx| {
@@ -9864,14 +10026,14 @@ mod tests {
enable_acp_beta(cx);
let thread = new_test_thread(cx).await;
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(session_id),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -9890,15 +10052,15 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
@@ -9943,15 +10105,15 @@ mod tests {
let stop_reason = {
let mut prompt_count = prompt_count.borrow_mut();
let stop_reason = if *prompt_count == 0 {
- acp::StopReason::EndTurn
+ acp_v1::StopReason::EndTurn
} else {
- acp::StopReason::Cancelled
+ acp_v1::StopReason::Cancelled
};
*prompt_count += 1;
stop_reason
};
- async move { Ok(acp::PromptResponse::new(stop_reason)) }.boxed_local()
+ async move { Ok(acp_v1::PromptResponse::new(stop_reason)) }.boxed_local()
}
}));
let thread = cx
@@ -9966,16 +10128,16 @@ mod tests {
.await
.expect("first turn should succeed")
.expect("first turn should return a response");
- assert_eq!(response.stop_reason, acp::StopReason::EndTurn);
+ assert_eq!(response.stop_reason, acp_v1::StopReason::EndTurn);
let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(session_id),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -9994,15 +10156,15 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
let response = thread
@@ -10010,7 +10172,7 @@ mod tests {
.await
.expect("second turn should succeed")
.expect("second turn should return a response");
- assert_eq!(response.stop_reason, acp::StopReason::Cancelled);
+ assert_eq!(response.stop_reason, acp_v1::StopReason::Cancelled);
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&entry_id) else {
panic!("missing elicitation entry");
@@ -10038,10 +10200,10 @@ mod tests {
let response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10057,22 +10219,25 @@ mod tests {
store.elicitations()
);
};
- let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ let acp_v1::ElicitationScope::Request(scope) = elicitation.request.scope() else {
panic!("expected request-scoped elicitation");
};
- assert_eq!(scope.request_id, acp::RequestId::Number(1));
+ assert_eq!(scope.request_id, acp_v1::RequestId::Number(1));
elicitation.id.clone()
});
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Decline
+ );
store.read_with(cx, |store, _| {
let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10099,10 +10264,10 @@ mod tests {
let response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10124,19 +10289,22 @@ mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
store.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Decline
+ );
assert_eq!(
responded_ids.borrow().as_slice(),
std::slice::from_ref(&elicitation_id)
@@ -10159,10 +10327,10 @@ mod tests {
let (elicitation_id, response_task) = thread.update(cx, |thread, cx| {
thread
.request_elicitation_with_id(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10175,7 +10343,10 @@ mod tests {
thread.cancel_elicitation(&elicitation_id, cx);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Cancel
+ );
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10194,10 +10365,10 @@ mod tests {
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10215,7 +10386,10 @@ mod tests {
thread.cancel(cx).detach();
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Cancel
+ );
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10226,16 +10400,16 @@ mod tests {
fn request_test_session_elicitation(
thread: WeakEntity<AcpThread>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut AsyncApp,
- ) -> Result<Task<acp::CreateElicitationResponse>> {
+ ) -> Result<Task<acp_v1::CreateElicitationResponse>> {
thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10285,7 +10459,7 @@ mod tests {
cx.run_until_parked();
assert_eq!(
*elicitation_action.borrow(),
- Some(acp::ElicitationAction::Cancel)
+ Some(acp_v1::ElicitationAction::Cancel)
);
thread.read_with(cx, |thread, _| {
let Some(elicitation) = thread.entries().iter().find_map(|entry| match entry {
@@ -10320,7 +10494,7 @@ mod tests {
})
.detach();
- Ok(acp::PromptResponse::new(acp::StopReason::MaxTokens))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::MaxTokens))
}
.boxed_local()
}
@@ -10340,7 +10514,7 @@ mod tests {
cx.run_until_parked();
assert_eq!(
*elicitation_action.borrow(),
- Some(acp::ElicitationAction::Cancel)
+ Some(acp_v1::ElicitationAction::Cancel)
);
thread.read_with(cx, |thread, _| {
let Some(elicitation) = thread.entries().iter().find_map(|entry| match entry {
@@ -10364,10 +10538,10 @@ mod tests {
let (elicitation_id, response_task) = store.update(cx, |store, cx| {
store
.request_elicitation_with_id(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10380,7 +10554,10 @@ mod tests {
store.cancel_elicitation(&elicitation_id, cx);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Cancel
+ );
store.read_with(cx, |store, _| {
let Some((_, elicitation)) = store.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10405,14 +10582,14 @@ mod tests {
})
});
- let request_id = acp::RequestId::Number(1);
+ let request_id = acp_v1::RequestId::Number(1);
let (elicitation_id, response_task) = store.update(cx, |store, cx| {
store
.request_elicitation_with_id(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(request_id.clone()),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(request_id.clone()),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10445,10 +10622,10 @@ mod tests {
let response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10461,7 +10638,10 @@ mod tests {
store.cancel_all(cx);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Cancel);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Cancel
+ );
}
#[gpui::test]
@@ -10475,10 +10655,10 @@ mod tests {
let first_response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10489,10 +10669,10 @@ mod tests {
let second_response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
- acp::ElicitationSchema::new().string("account", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(2)),
+ acp_v1::ElicitationSchema::new().string("account", true),
),
"Provide an account",
),
@@ -10511,7 +10691,7 @@ mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&first_elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
store.clear(cx);
@@ -10519,11 +10699,11 @@ mod tests {
assert_eq!(
first_response_task.await.action,
- acp::ElicitationAction::Decline
+ acp_v1::ElicitationAction::Decline
);
assert_eq!(
second_response_task.await.action,
- acp::ElicitationAction::Cancel
+ acp_v1::ElicitationAction::Cancel
);
store.read_with(cx, |store, _| assert!(store.elicitations().is_empty()));
}
@@ -10535,15 +10715,15 @@ mod tests {
init_test(cx);
enable_acp_beta(cx);
let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let accepted_response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10554,10 +10734,10 @@ mod tests {
let pending_response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
- acp::ElicitationSchema::new().string("account", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(2)),
+ acp_v1::ElicitationSchema::new().string("account", true),
),
"Provide an account",
),
@@ -10568,9 +10748,9 @@ mod tests {
let accepted_url_response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(3)),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(3)),
url_elicitation_id,
"https://example.com/complete",
),
@@ -10598,26 +10778,26 @@ mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&accepted_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
store.respond_to_elicitation(
&accepted_url_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
accepted_response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
assert!(matches!(
accepted_url_response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
let cleared_ids = store.update(cx, |store, cx| store.clear_resolved(cx));
@@ -10638,7 +10818,7 @@ mod tests {
store.update(cx, |store, cx| store.clear(cx));
assert_eq!(
pending_response_task.await.action,
- acp::ElicitationAction::Cancel
+ acp_v1::ElicitationAction::Cancel
);
}
@@ -10647,14 +10827,14 @@ mod tests {
init_test(cx);
enable_acp_beta(cx);
let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -10690,15 +10870,15 @@ mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
store.update(cx, |store, cx| {
store.complete_url_elicitation(&url_elicitation_id, cx);
@@ -10718,7 +10898,7 @@ mod tests {
init_test(cx);
enable_acp_beta(cx);
let store = cx.update(|cx| cx.new(|_| ElicitationStore::default()));
- let url_elicitation_id = acp::ElicitationId::new("url-1");
+ let url_elicitation_id = acp_v1::ElicitationId::new("url-1");
let responded_ids = Rc::new(RefCell::new(Vec::new()));
let _subscription = cx.update(|cx| {
let responded_ids = responded_ids.clone();
@@ -10732,9 +10912,9 @@ mod tests {
let response_task = store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
url_elicitation_id.clone(),
"https://example.com/complete",
),
@@ -10758,15 +10938,15 @@ mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
assert!(matches!(
response_task.await.action,
- acp::ElicitationAction::Accept(_)
+ acp_v1::ElicitationAction::Accept(_)
));
assert_eq!(
responded_ids.borrow().as_slice(),
@@ -10809,10 +10989,10 @@ mod tests {
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10829,13 +11009,16 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
thread.cancel(cx).detach();
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Decline
+ );
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10854,10 +11037,10 @@ mod tests {
let response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -10874,19 +11057,22 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
});
- assert_eq!(response_task.await.action, acp::ElicitationAction::Decline);
+ assert_eq!(
+ response_task.await.action,
+ acp_v1::ElicitationAction::Decline
+ );
thread.read_with(cx, |thread, _| {
let Some((_, elicitation)) = thread.elicitation(&elicitation_id) else {
panic!("missing elicitation entry");
@@ -10911,9 +11097,9 @@ mod tests {
] {
let result = thread.update(cx, |thread, cx| {
thread.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(session_id.clone()),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id.clone()),
"url-1",
invalid_url,
),
@@ -10926,7 +11112,7 @@ mod tests {
let Err(error) = result else {
panic!("{invalid_url} should not be accepted for URL elicitation");
};
- assert_eq!(error.code, acp::ErrorCode::InvalidParams);
+ assert_eq!(error.code, acp_v1::ErrorCode::InvalidParams);
}
thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
}
@@ -10939,10 +11125,10 @@ mod tests {
let result = thread.update(cx, |thread, cx| {
thread.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::OtherElicitationMode::new(
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::OtherElicitationMode::new(
"future",
- acp::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSessionScope::new(session_id),
std::collections::BTreeMap::new(),
),
"Use a future input mode",
@@ -10954,7 +11140,7 @@ mod tests {
let Err(error) = result else {
panic!("unadvertised elicitation mode should be rejected");
};
- assert_eq!(error.code, acp::ErrorCode::InvalidParams);
+ assert_eq!(error.code, acp_v1::ErrorCode::InvalidParams);
thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
}
@@ -10965,10 +11151,10 @@ mod tests {
let result = store.update(cx, |store, cx| {
store.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::OtherElicitationMode::new(
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::OtherElicitationMode::new(
"future",
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
std::collections::BTreeMap::new(),
),
"Use a future input mode",
@@ -10980,7 +11166,7 @@ mod tests {
let Err(error) = result else {
panic!("unadvertised elicitation mode should be rejected");
};
- assert_eq!(error.code, acp::ErrorCode::InvalidParams);
+ assert_eq!(error.code, acp_v1::ErrorCode::InvalidParams);
store.read_with(cx, |store, _| assert!(store.elicitations().is_empty()));
}
@@ -11013,17 +11199,18 @@ mod tests {
#[derive(Clone, Default)]
struct FakeAgentConnection {
- auth_methods: Vec<acp::AuthMethod>,
+ auth_methods: Vec<acp_v1::AuthMethod>,
supports_truncate: bool,
- sessions: Arc<parking_lot::Mutex<HashMap<acp::SessionId, WeakEntity<AcpThread>>>>,
+ sessions: Arc<parking_lot::Mutex<HashMap<acp_v1::SessionId, WeakEntity<AcpThread>>>>,
set_title_calls: Rc<RefCell<Vec<SharedString>>>,
on_user_message: Option<
Rc<
dyn Fn(
- acp::PromptRequest,
+ acp_v1::PromptRequest,
WeakEntity<AcpThread>,
AsyncApp,
- ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
+ )
+ -> LocalBoxFuture<'static, Result<acp_v1::PromptResponse>>
+ 'static,
>,
>,
@@ -11046,7 +11233,7 @@ mod tests {
}
#[expect(unused)]
- fn with_auth_methods(mut self, auth_methods: Vec<acp::AuthMethod>) -> Self {
+ fn with_auth_methods(mut self, auth_methods: Vec<acp_v1::AuthMethod>) -> Self {
self.auth_methods = auth_methods;
self
}
@@ -11054,10 +11241,10 @@ mod tests {
fn on_user_message(
mut self,
handler: impl Fn(
- acp::PromptRequest,
+ acp_v1::PromptRequest,
WeakEntity<AcpThread>,
AsyncApp,
- ) -> LocalBoxFuture<'static, Result<acp::PromptResponse>>
+ ) -> LocalBoxFuture<'static, Result<acp_v1::PromptResponse>>
+ 'static,
) -> Self {
self.on_user_message.replace(Rc::new(handler));
@@ -11074,7 +11261,7 @@ mod tests {
"fake".into()
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&self.auth_methods
}
@@ -11084,7 +11271,7 @@ mod tests {
work_dirs: PathList,
cx: &mut App,
) -> Task<gpui::Result<Entity<AcpThread>>> {
- let session_id = acp::SessionId::new(
+ let session_id = acp_v1::SessionId::new(
rand::rng()
.sample_iter(&distr::Alphanumeric)
.take(7)
@@ -11102,7 +11289,7 @@ mod tests {
action_log,
session_id.clone(),
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -11114,7 +11301,11 @@ mod tests {
Task::ready(Ok(thread))
}
- fn authenticate(&self, method: acp::AuthMethodId, _cx: &mut App) -> Task<gpui::Result<()>> {
+ fn authenticate(
+ &self,
+ method: acp_v1::AuthMethodId,
+ _cx: &mut App,
+ ) -> Task<gpui::Result<()>> {
if self.auth_methods().iter().any(|m| m.id() == &method) {
Task::ready(Ok(()))
} else {
@@ -11124,9 +11315,9 @@ mod tests {
fn prompt(
&self,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
let sessions = self.sessions.lock();
let thread = sessions.get(&params.session_id).unwrap();
if let Some(handler) = &self.on_user_message {
@@ -11134,7 +11325,7 @@ mod tests {
let thread = thread.clone();
cx.spawn(async move |cx| handler(params, thread, cx.clone()).await)
} else {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
}
@@ -11149,11 +11340,11 @@ mod tests {
})
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn truncate(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionTruncate>> {
self.supports_truncate.then(|| {
@@ -11165,7 +11356,7 @@ mod tests {
fn set_title(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionSetTitle>> {
Some(Rc::new(FakeAgentSessionSetTitle {
@@ -11190,7 +11381,7 @@ mod tests {
}
struct FakeAgentSessionEditor {
- _session_id: acp::SessionId,
+ _session_id: acp_v1::SessionId,
}
impl AgentSessionTruncate for FakeAgentSessionEditor {
@@ -11211,9 +11402,9 @@ mod tests {
fn prompt(
&self,
_client_user_message_id: ClientUserMessageId,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
self.connection.prompt(params, cx)
}
}
@@ -11233,12 +11424,12 @@ mod tests {
.unwrap();
// Try to update a tool call that doesn't exist
- let nonexistent_id = acp::ToolCallId::new("nonexistent-tool-call");
+ let nonexistent_id = acp_v1::ToolCallId::new("nonexistent-tool-call");
thread.update(cx, |thread, cx| {
let result = thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
nonexistent_id.clone(),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+ acp_v1::ToolCallUpdateFields::new().status(acp_v1::ToolCallStatus::Completed),
)),
cx,
);
@@ -11253,7 +11444,7 @@ mod tests {
if let AgentThreadEntry::ToolCall(tool_call) = &thread.entries[0] {
assert_eq!(tool_call.id, nonexistent_id);
assert!(matches!(tool_call.status, ToolCallStatus::Failed));
- assert_eq!(tool_call.kind, acp::ToolKind::Fetch);
+ assert_eq!(tool_call.kind, acp_v1::ToolKind::Fetch);
// Check that the content contains the error message
assert_eq!(tool_call.content().len(), 1);
@@ -11308,7 +11499,7 @@ mod tests {
.unwrap();
// Create 2 terminals BEFORE the checkpoint that have completed running
- let terminal_id_1 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id_1 = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
let mock_terminal_1 = cx.new(|cx| {
let builder = ::terminal::TerminalBuilder::new_display_only(
::terminal::terminal_settings::CursorShape::default(),
@@ -11348,13 +11539,13 @@ mod tests {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id_1.clone(),
- status: acp::TerminalExitStatus::new().exit_code(0),
+ status: acp_v1::TerminalExitStatus::new().exit_code(0),
},
cx,
);
});
- let terminal_id_2 = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id_2 = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
let mock_terminal_2 = cx.new(|cx| {
let builder = ::terminal::TerminalBuilder::new_display_only(
::terminal::terminal_settings::CursorShape::default(),
@@ -11394,7 +11585,7 @@ mod tests {
thread.on_terminal_provider_event(
TerminalProviderEvent::Exit {
terminal_id: terminal_id_2.clone(),
- status: acp::TerminalExitStatus::new().exit_code(0),
+ status: acp_v1::TerminalExitStatus::new().exit_code(0),
},
cx,
);
@@ -11414,7 +11605,7 @@ mod tests {
// Create a terminal AFTER the checkpoint we'll restore to.
// This simulates the AI agent starting a long-running terminal command.
- let terminal_id = acp::TerminalId::new(uuid::Uuid::new_v4().to_string());
+ let terminal_id = acp_v1::TerminalId::new(uuid::Uuid::new_v4().to_string());
let mock_terminal = cx.new(|cx| {
let builder = ::terminal::TerminalBuilder::new_display_only(
::terminal::terminal_settings::CursorShape::default(),
@@ -11457,13 +11648,13 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("terminal-tool-1", "Running command")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::InProgress)
- .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
- terminal_id.clone(),
- ))])
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("terminal-tool-1", "Running command")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::InProgress)
+ .content(vec![acp_v1::ToolCallContent::Terminal(
+ acp_v1::Terminal::new(terminal_id.clone()),
+ )])
.raw_input(serde_json::json!({"command": "sleep 1000", "cd": "/test"})),
),
cx,
@@ -11590,7 +11781,8 @@ mod tests {
let connection = Rc::new(FakeAgentConnection::new().on_user_message(
move |_, _thread, _cx| {
handler_done_clone.store(true, SeqCst);
- async move { Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)) }.boxed_local()
+ async move { Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)) }
+ .boxed_local()
},
));
@@ -11669,7 +11861,7 @@ mod tests {
if let Some(rx) = complete_rx {
rx.await.ok();
}
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
},
@@ -11741,10 +11933,9 @@ mod tests {
let connection = Rc::new(FakeAgentConnection::new().on_user_message({
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::ContentBlock::Text(t) if t.text.contains("first")));
+ let is_first = params.prompt.iter().any(
+ |c| matches!(c, acp_v1::ContentBlock::Text(t) if t.text.contains("first")),
+ );
let second_complete_rx = if is_first {
None
} else {
@@ -11762,7 +11953,7 @@ mod tests {
.expect("second completion receiver should be available")
.await?;
}
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
}
@@ -11783,7 +11974,7 @@ mod tests {
let permission_task = thread
.update(cx, |thread, cx| {
thread.request_tool_call_authorization(
- acp::ToolCall::new("permission", "Needs permission").into(),
+ acp_v1::ToolCall::new("permission", "Needs permission").into(),
PermissionOptions::Flat(Vec::new()),
AuthorizationKind::PermissionGrant,
cx,
@@ -11863,7 +12054,7 @@ mod tests {
}
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -11892,7 +12083,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::ContentBlock::Text(text) if text.text.contains("first"))
+ matches!(content, acp_v1::ContentBlock::Text(text) if text.text.contains("first"))
});
let compaction_id = compaction_id.clone();
@@ -11915,9 +12106,9 @@ mod tests {
);
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Cancelled))
} else {
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
}
.boxed_local()
@@ -11945,7 +12136,7 @@ mod tests {
.await
.expect("first request should complete")
.expect("first request should have response");
- assert_eq!(response.stop_reason, acp::StopReason::Cancelled);
+ assert_eq!(response.stop_reason, acp_v1::StopReason::Cancelled);
thread.read_with(cx, |thread, _| {
let compaction = thread
@@ -12018,13 +12209,13 @@ mod tests {
thread
.update(&mut cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(
- acp::ToolCallId::new("test-tool"),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(
+ acp_v1::ToolCallId::new("test-tool"),
"Test Tool",
)
- .kind(acp::ToolKind::Fetch)
- .status(acp::ToolCallStatus::InProgress),
+ .kind(acp_v1::ToolKind::Fetch)
+ .status(acp_v1::ToolCallStatus::InProgress),
),
cx,
)
@@ -12032,7 +12223,7 @@ mod tests {
.unwrap()
.unwrap();
- Ok(acp::PromptResponse::new(acp::StopReason::Cancelled))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Cancelled))
}
.boxed_local()
},
@@ -12054,7 +12245,7 @@ mod tests {
.expect("should have response");
assert_eq!(
response.stop_reason,
- acp::StopReason::Cancelled,
+ acp_v1::StopReason::Cancelled,
"response should have Cancelled stop_reason"
);
@@ -12183,8 +12374,8 @@ mod tests {
let result = thread.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::SessionInfoUpdate(
- acp::SessionInfoUpdate::new().title("Helping with Rust question"),
+ acp_v1::SessionUpdate::SessionInfoUpdate(
+ acp_v1::SessionInfoUpdate::new().title("Helping with Rust question"),
),
cx,
)
@@ -12238,28 +12429,29 @@ mod tests {
})
});
- let warning = acp::Notice::new(acp::NoticeSeverity::Warning, "MCP server unavailable")
- .description("Continuing without it.");
+ let warning =
+ acp_v1::Notice::new(acp_v1::NoticeSeverity::Warning, "MCP server unavailable")
+ .description("Continuing without it.");
let notices = vec![
- acp::Notice::new(acp::NoticeSeverity::Info, "Using default configuration"),
+ acp_v1::Notice::new(acp_v1::NoticeSeverity::Info, "Using default configuration"),
warning.clone(),
warning.clone(),
- acp::Notice::new(acp::NoticeSeverity::Error, "Optional integration failed"),
- acp::Notice::new(
- acp::NoticeSeverity::Other("critical".into()),
+ acp_v1::Notice::new(acp_v1::NoticeSeverity::Error, "Optional integration failed"),
+ acp_v1::Notice::new(
+ acp_v1::NoticeSeverity::Other("critical".into()),
"Future severity",
),
- acp::Notice::new(
- acp::NoticeSeverity::Other("_custom".into()),
+ acp_v1::Notice::new(
+ acp_v1::NoticeSeverity::Other("_custom".into()),
"**Plain text**, not Markdown",
)
- .meta(acp::Meta::from_iter([("source".into(), "test".into())])),
+ .meta(acp_v1::Meta::from_iter([("source".into(), "test".into())])),
];
thread.update(cx, |thread, cx| {
for notice in &notices {
thread
- .handle_session_update(acp::SessionUpdate::Notice(notice.clone()), cx)
+ .handle_session_update(acp_v1::SessionUpdate::Notice(notice.clone()), cx)
.expect("notice should be accepted");
}
assert_eq!(
@@ -12299,7 +12491,7 @@ mod tests {
}
assert!(thread.notices().is_empty());
thread
- .handle_session_update(acp::SessionUpdate::Notice(warning.clone()), cx)
+ .handle_session_update(acp_v1::SessionUpdate::Notice(warning.clone()), cx)
.expect("a repeated notice is a new live event");
thread.dismiss_notice(1, cx);
assert_eq!(thread.notices(), &[(notices.len(), warning)]);
@@ -12323,9 +12515,9 @@ mod tests {
let history_before_notice = thread.to_markdown(cx);
let entry_count = thread.entries().len();
thread.handle_session_update(
- acp::SessionUpdate::Notice(
- acp::Notice::new(
- acp::NoticeSeverity::Error,
+ acp_v1::SessionUpdate::Notice(
+ acp_v1::Notice::new(
+ acp_v1::NoticeSeverity::Error,
"Optional integration failed",
)
.description("Work will continue without the integration."),
@@ -12337,13 +12529,13 @@ mod tests {
assert_eq!(thread.entries().len(), entry_count);
assert_eq!(thread.to_markdown(cx), history_before_notice);
thread.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"The response continues.".into(),
)),
cx,
)
})??;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
.boxed_local()
},
@@ -12391,8 +12583,8 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(
- acp::UsageUpdate::new(5000, 10000).cost(acp::Cost::new(0.42, "USD")),
+ acp_v1::SessionUpdate::UsageUpdate(
+ acp_v1::UsageUpdate::new(5000, 10000).cost(acp_v1::Cost::new(0.42, "USD")),
),
cx,
)
@@ -12427,8 +12619,8 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(
- acp::UsageUpdate::new(5000, 10000).cost(acp::Cost::new(0.42, "USD")),
+ acp_v1::SessionUpdate::UsageUpdate(
+ acp_v1::UsageUpdate::new(5000, 10000).cost(acp_v1::Cost::new(0.42, "USD")),
),
cx,
)
@@ -12461,7 +12653,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(acp::UsageUpdate::new(1000, 10000)),
+ acp_v1::SessionUpdate::UsageUpdate(acp_v1::UsageUpdate::new(1000, 10000)),
cx,
)
.unwrap();
@@ -12493,8 +12685,8 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(
- acp::UsageUpdate::new(1000, 10000).cost(acp::Cost::new(0.10, "USD")),
+ acp_v1::SessionUpdate::UsageUpdate(
+ acp_v1::UsageUpdate::new(1000, 10000).cost(acp_v1::Cost::new(0.10, "USD")),
),
cx,
)
@@ -12502,7 +12694,7 @@ mod tests {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(acp::UsageUpdate::new(2000, 10000)),
+ acp_v1::SessionUpdate::UsageUpdate(acp_v1::UsageUpdate::new(2000, 10000)),
cx,
)
.unwrap();
@@ -12529,16 +12721,16 @@ mod tests {
thread.update(&mut cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(
- acp::UsageUpdate::new(3000, 10000)
- .cost(acp::Cost::new(0.05, "EUR")),
+ acp_v1::SessionUpdate::UsageUpdate(
+ acp_v1::UsageUpdate::new(3000, 10000)
+ .cost(acp_v1::Cost::new(0.05, "EUR")),
),
cx,
)
.unwrap();
})?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)
- .usage(acp::Usage::new(500, 200, 300)))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)
+ .usage(acp_v1::Usage::new(500, 200, 300)))
}
.boxed_local()
},
@@ -12589,8 +12781,8 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::UsageUpdate(
- acp::UsageUpdate::new(1000, 10000).cost(acp::Cost::new(0.25, "USD")),
+ acp_v1::SessionUpdate::UsageUpdate(
+ acp_v1::UsageUpdate::new(1000, 10000).cost(acp_v1::Cost::new(0.25, "USD")),
),
cx,
)
@@ -12626,7 +12818,7 @@ mod tests {
// `f(this, cx).await` with `tx` still alive but unsent.
let connection = Rc::new(FakeAgentConnection::new().on_user_message(
|_params, _thread, _cx| {
- async move { futures::future::pending::<Result<acp::PromptResponse>>().await }
+ async move { futures::future::pending::<Result<acp_v1::PromptResponse>>().await }
.boxed_local()
},
));
@@ -12693,7 +12885,7 @@ mod tests {
async move |_, _| {
completion.await?;
backend_finished.store(true, SeqCst);
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
}
})
});
@@ -12735,22 +12927,22 @@ mod tests {
cx.set_idle_sleep_prevention_delay(delay);
for (backend_result, expected_result, expected_had_error) in [
(
- Ok(acp::StopReason::EndTurn),
- Ok(acp::StopReason::EndTurn),
+ Ok(acp_v1::StopReason::EndTurn),
+ Ok(acp_v1::StopReason::EndTurn),
false,
),
(
- Ok(acp::StopReason::Cancelled),
- Ok(acp::StopReason::Cancelled),
+ Ok(acp_v1::StopReason::Cancelled),
+ Ok(acp_v1::StopReason::Cancelled),
false,
),
(
- Ok(acp::StopReason::Refusal),
- Ok(acp::StopReason::Refusal),
+ Ok(acp_v1::StopReason::Refusal),
+ Ok(acp_v1::StopReason::Refusal),
true,
),
(
- Ok(acp::StopReason::MaxTokens),
+ Ok(acp_v1::StopReason::MaxTokens),
Err("output token limit reached"),
true,
),
@@ -12766,7 +12958,7 @@ mod tests {
assert!(!thread.read_with(cx, |thread, _| thread.had_error()));
complete
- .send(backend_result.map(acp::PromptResponse::new))
+ .send(backend_result.map(acp_v1::PromptResponse::new))
.expect("turn should still be running");
let result = request
.await
@@ -12810,8 +13002,8 @@ mod tests {
connection,
project,
action_log,
- acp::SessionId::new("subagent"),
- watch::Receiver::constant(acp::PromptCapabilities::new()),
+ acp_v1::SessionId::new("subagent"),
+ watch::Receiver::constant(acp_v1::PromptCapabilities::new()),
cx,
)
})
@@ -12833,14 +13025,16 @@ mod tests {
let parent_cancel = parent.update(cx, |thread, cx| thread.cancel(cx));
assert_eq!(cx.active_idle_sleep_preventions(), 2);
parent_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .send(Ok(acp_v1::PromptResponse::new(
+ acp_v1::StopReason::Cancelled,
+ )))
.expect("parent backend should still be running");
parent_cancel.await;
parent_request.await.expect("parent turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 2);
independent_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("independent turn should still be running");
independent_request
.await
@@ -12852,7 +13046,7 @@ mod tests {
);
subagent_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("subagent should still be running");
subagent_request
.await
@@ -12894,7 +13088,7 @@ mod tests {
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("backend should still be running");
cancel.await;
request.await.expect("turn should complete");
@@ -12940,7 +13134,7 @@ mod tests {
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -12975,7 +13169,9 @@ mod tests {
});
first_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .send(Ok(acp_v1::PromptResponse::new(
+ acp_v1::StopReason::Cancelled,
+ )))
.expect("first backend should still be running");
first_request.await.expect("first turn should complete");
cx.run_until_parked();
@@ -12989,7 +13185,7 @@ mod tests {
});
second_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("second backend should still be running");
second_request.await.expect("second turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13071,7 +13267,7 @@ mod tests {
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13105,7 +13301,7 @@ mod tests {
None
};
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("backend should still be running");
if let Some(cancel) = cancel {
cancel.await;
@@ -13125,7 +13321,7 @@ mod tests {
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 1);
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("next turn should still be running");
request.await.expect("next turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13140,8 +13336,8 @@ mod tests {
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 1);
- let first_id = acp::ToolCallId::new("first-permission");
- let second_id = acp::ToolCallId::new("second-permission");
+ let first_id = acp_v1::ToolCallId::new("first-permission");
+ let second_id = acp_v1::ToolCallId::new("second-permission");
let first_permission = request_test_permission(&thread, first_id.clone(), cx);
assert_eq!(cx.active_idle_sleep_preventions(), 0);
let second_permission = request_test_permission(&thread, second_id.clone(), cx);
@@ -13157,9 +13353,10 @@ mod tests {
thread.update(cx, |thread, cx| {
thread
.update_tool_call(
- acp::ToolCallUpdate::new(
+ acp_v1::ToolCallUpdate::new(
first_id.clone(),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::InProgress),
),
cx,
)
@@ -13167,8 +13364,8 @@ mod tests {
thread.authorize_tool_call(
second_id,
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("reject"),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v1::PermissionOptionId::new("reject"),
+ acp_v1::PermissionOptionKind::RejectOnce,
),
cx,
);
@@ -13176,7 +13373,7 @@ mod tests {
assert!(matches!(
second_permission.await,
RequestPermissionOutcome::Selected(outcome)
- if outcome.option_kind == acp::PermissionOptionKind::RejectOnce
+ if outcome.option_kind == acp_v1::PermissionOptionKind::RejectOnce
));
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13184,13 +13381,13 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
});
assert_eq!(
elicitation_response.await.action,
- acp::ElicitationAction::Decline
+ acp_v1::ElicitationAction::Decline
);
cx.run_until_parked();
assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
@@ -13200,8 +13397,8 @@ mod tests {
thread.authorize_tool_call(
first_id,
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -13209,14 +13406,14 @@ mod tests {
assert!(matches!(
first_permission.await,
RequestPermissionOutcome::Selected(outcome)
- if outcome.option_kind == acp::PermissionOptionKind::AllowOnce
+ if outcome.option_kind == acp_v1::PermissionOptionKind::AllowOnce
));
cx.run_until_parked();
assert!(!thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
assert_eq!(cx.active_idle_sleep_preventions(), 1);
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13229,14 +13426,14 @@ mod tests {
init_test(cx);
for status in [
None,
- Some(acp::ToolCallStatus::Completed),
- Some(acp::ToolCallStatus::Failed),
+ Some(acp_v1::ToolCallStatus::Completed),
+ Some(acp_v1::ToolCallStatus::Failed),
] {
let thread = new_test_thread(cx).await;
let (complete, request) = start_test_turn(&thread, cx);
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 1);
- let tool_call_id = acp::ToolCallId::new("permission");
+ let tool_call_id = acp_v1::ToolCallId::new("permission");
let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13245,9 +13442,9 @@ mod tests {
if let Some(status) = status {
thread
.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_call_id,
- acp::ToolCallUpdateFields::new().status(status),
+ acp_v1::ToolCallUpdateFields::new().status(status),
)),
cx,
)
@@ -13265,7 +13462,7 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 1, "status: {status:?}");
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13280,7 +13477,7 @@ mod tests {
let (complete, request) = start_test_turn(&thread, cx);
cx.run_until_parked();
cx.executor().advance_clock(Duration::from_secs(1));
- let tool_call_id = acp::ToolCallId::new("permission");
+ let tool_call_id = acp_v1::ToolCallId::new("permission");
let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
cx.run_until_parked();
cx.executor().advance_clock(Duration::from_secs(1));
@@ -13298,8 +13495,8 @@ mod tests {
thread.authorize_tool_call(
tool_call_id,
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -13317,7 +13514,7 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 1);
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13356,7 +13553,7 @@ mod tests {
);
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13371,9 +13568,9 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 1);
for action in [
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new()),
- acp::ElicitationAction::Decline,
- acp::ElicitationAction::Cancel,
+ acp_v1::ElicitationAction::Accept(acp_v1::ElicitationAcceptAction::new()),
+ acp_v1::ElicitationAction::Decline,
+ acp_v1::ElicitationAction::Cancel,
] {
let (elicitation_id, response) = request_test_form_elicitation(&thread, cx);
cx.run_until_parked();
@@ -13386,7 +13583,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(action.clone()),
+ acp_v1::CreateElicitationResponse::new(action.clone()),
cx,
);
});
@@ -13398,7 +13595,7 @@ mod tests {
thread.update(cx, |thread, cx| {
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Cancel),
cx,
);
});
@@ -13407,7 +13604,7 @@ mod tests {
}
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13422,13 +13619,13 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 1);
for (url_id, accept) in [("accepted", true), ("canceled", false)] {
- let url_id = acp::ElicitationId::new(url_id);
+ let url_id = acp_v1::ElicitationId::new(url_id);
let (entry_id, response) = thread.update(cx, |thread, cx| {
thread
.request_elicitation_with_id(
- acp::CreateElicitationRequest::new(
- acp::ElicitationUrlMode::new(
- acp::ElicitationSessionScope::new(thread.session_id().clone()),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationUrlMode::new(
+ acp_v1::ElicitationSessionScope::new(thread.session_id().clone()),
url_id.clone(),
"https://example.com/complete",
),
@@ -13447,15 +13644,15 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 0);
let expected_action = if accept {
- acp::ElicitationAction::Accept(acp::ElicitationAcceptAction::new())
+ acp_v1::ElicitationAction::Accept(acp_v1::ElicitationAcceptAction::new())
} else {
- acp::ElicitationAction::Cancel
+ acp_v1::ElicitationAction::Cancel
};
thread.update(cx, |thread, cx| {
if accept {
thread.respond_to_elicitation(
&entry_id,
- acp::CreateElicitationResponse::new(expected_action.clone()),
+ acp_v1::CreateElicitationResponse::new(expected_action.clone()),
cx,
);
} else {
@@ -13475,7 +13672,7 @@ mod tests {
}
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13490,7 +13687,7 @@ mod tests {
let (complete, request) = start_test_turn(&thread, cx);
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 1);
- let tool_call_id = acp::ToolCallId::new("permission");
+ let tool_call_id = acp_v1::ToolCallId::new("permission");
let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
let (elicitation_id, elicitation_response) = request_test_form_elicitation(&thread, cx);
cx.run_until_parked();
@@ -13503,21 +13700,21 @@ mod tests {
));
assert_eq!(
elicitation_response.await.action,
- acp::ElicitationAction::Cancel
+ acp_v1::ElicitationAction::Cancel
);
thread.update(cx, |thread, cx| {
thread.authorize_tool_call(
tool_call_id,
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
thread.respond_to_elicitation(
&elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
@@ -13530,7 +13727,9 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 0);
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .send(Ok(acp_v1::PromptResponse::new(
+ acp_v1::StopReason::Cancelled,
+ )))
.expect("backend should still be running");
cancel.await;
request.await.expect("turn should complete");
@@ -13539,7 +13738,7 @@ mod tests {
#[gpui::test]
async fn test_stale_refusal_does_not_affect_follow_up_turn(cx: &mut TestAppContext) {
- assert_stale_completion_does_not_affect_follow_up_turn(Ok(acp::StopReason::Refusal), cx)
+ assert_stale_completion_does_not_affect_follow_up_turn(Ok(acp_v1::StopReason::Refusal), cx)
.await;
}
@@ -13554,9 +13753,9 @@ mod tests {
) {
init_test(cx);
let thread = new_test_thread(cx).await;
- let text = acp::ContentBlock::Text(
- acp::TextContent::new("before")
- .meta(acp::Meta::from_iter([("sequence".into(), json!(1))])),
+ let text = acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("before")
+ .meta(acp_v2::Meta::from_iter([("sequence".into(), json!(1))])),
);
let image = message_test_image();
@@ -13600,7 +13799,7 @@ mod tests {
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("turn should still be running");
request.await.expect("turn should complete");
thread.read_with(cx, |thread, cx| {
@@ -13701,7 +13900,9 @@ mod tests {
);
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::Cancelled)))
+ .send(Ok(acp_v1::PromptResponse::new(
+ acp_v1::StopReason::Cancelled,
+ )))
.expect("backend should still be running");
cancel.await;
request.await.expect("turn should complete");
@@ -13749,10 +13950,10 @@ mod tests {
thread: &Entity<AcpThread>,
cx: &mut TestAppContext,
) -> (
- oneshot::Sender<Result<acp::PromptResponse>>,
- BoxFuture<'static, Result<Option<acp::PromptResponse>>>,
+ oneshot::Sender<Result<acp_v1::PromptResponse>>,
+ BoxFuture<'static, Result<Option<acp_v1::PromptResponse>>>,
) {
- let (complete, completion) = oneshot::channel::<Result<acp::PromptResponse>>();
+ let (complete, completion) = oneshot::channel::<Result<acp_v1::PromptResponse>>();
let request = thread.update(cx, |thread, cx| {
thread.run_turn(cx, async move |_, _| completion.await?)
});
@@ -13761,23 +13962,23 @@ mod tests {
fn request_test_permission(
thread: &Entity<AcpThread>,
- tool_call_id: acp::ToolCallId,
+ tool_call_id: acp_v1::ToolCallId,
cx: &mut TestAppContext,
) -> Task<RequestPermissionOutcome> {
thread.update(cx, |thread, cx| {
thread
.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id, "Needs permission").into(),
+ acp_v1::ToolCall::new(tool_call_id, "Needs permission").into(),
PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("reject"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("reject"),
"Reject",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v1::PermissionOptionKind::RejectOnce,
),
]),
AuthorizationKind::PermissionGrant,
@@ -13790,14 +13991,14 @@ mod tests {
fn request_test_form_elicitation(
thread: &Entity<AcpThread>,
cx: &mut TestAppContext,
- ) -> (ElicitationEntryId, Task<acp::CreateElicitationResponse>) {
+ ) -> (ElicitationEntryId, Task<acp_v1::CreateElicitationResponse>) {
thread.update(cx, |thread, cx| {
thread
.request_elicitation_with_id(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(thread.session_id().clone()),
- acp::ElicitationSchema::new().string("name", false),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(thread.session_id().clone()),
+ acp_v1::ElicitationSchema::new().string("name", false),
),
"Provide a name",
),
@@ -13818,7 +14019,7 @@ mod tests {
}
async fn assert_stale_completion_does_not_affect_follow_up_turn(
- backend_result: Result<acp::StopReason, &'static str>,
+ backend_result: Result<acp_v1::StopReason, &'static str>,
cx: &mut TestAppContext,
) {
init_test(cx);
@@ -13841,7 +14042,7 @@ mod tests {
first_complete
.send(
backend_result
- .map(acp::PromptResponse::new)
+ .map(acp_v1::PromptResponse::new)
.map_err(|message| anyhow!(message)),
)
.expect("first backend should still be running");
@@ -13915,7 +14116,7 @@ mod tests {
assert_eq!(cx.active_idle_sleep_preventions(), 1);
second_complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("second backend should still be running");
second_request.await.expect("second turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
@@ -13931,20 +14132,20 @@ mod tests {
let (complete, request) = start_test_turn(&thread, cx);
cx.run_until_parked();
assert_eq!(cx.active_idle_sleep_preventions(), 1);
- let tool_call_id = acp::ToolCallId::new("permission");
+ let tool_call_id = acp_v1::ToolCallId::new("permission");
let permission = request_test_permission(&thread, tool_call_id.clone(), cx);
cx.run_until_parked();
assert!(thread.read_with(cx, |thread, _| thread.is_waiting_for_confirmation()));
assert_eq!(cx.active_idle_sleep_preventions(), 0);
thread.update(cx, |thread, cx| {
- let update = acp::ToolCallUpdate::new(
+ let update = acp_v1::ToolCallUpdate::new(
tool_call_id.clone(),
- acp::ToolCallUpdateFields::new()
- .status(acp::ToolCallStatus::Completed)
- .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
- acp::TerminalId::new("unknown-terminal"),
- ))]),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::Completed)
+ .content(vec![acp_v1::ToolCallContent::Terminal(
+ acp_v1::Terminal::new(acp_v1::TerminalId::new("unknown-terminal")),
+ )]),
);
if upsert {
assert!(
@@ -13969,7 +14170,7 @@ mod tests {
.1
.status
.as_acp_status(),
- Some(acp::ToolCallStatus::Completed)
+ Some(acp_v1::ToolCallStatus::Completed)
);
assert!(!thread.is_waiting_for_confirmation());
});
@@ -13990,7 +14191,7 @@ mod tests {
});
complete
- .send(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ .send(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
.expect("backend should still be running");
request.await.expect("turn should complete");
assert_eq!(cx.active_idle_sleep_preventions(), 0);
diff --git a/crates/acp_thread/src/connection.rs b/crates/acp_thread/src/connection.rs
index 5f0cf69890d..11d3edf436c 100644
--- a/crates/acp_thread/src/connection.rs
+++ b/crates/acp_thread/src/connection.rs
@@ -1,5 +1,5 @@
use crate::{AcpThread, ElicitationStore};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v1 as acp_v1;
use anyhow::Result;
use chrono::{DateTime, Utc};
use collections::{HashMap, HashSet, IndexMap};
@@ -112,7 +112,7 @@ pub trait AgentConnection {
/// Load an existing session by ID.
fn load_session(
self: Rc<Self>,
- _session_id: acp::SessionId,
+ _session_id: acp_v1::SessionId,
_project: Entity<Project>,
_work_dirs: PathList,
_title: Option<SharedString>,
@@ -129,7 +129,7 @@ pub trait AgentConnection {
/// Close an existing session. Allows the agent to free the session from memory.
fn close_session(
self: Rc<Self>,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &mut App,
) -> Task<Result<()>> {
Task::ready(Err(anyhow::Error::msg("Closing sessions is not supported")))
@@ -143,7 +143,7 @@ pub trait AgentConnection {
/// Resume an existing session by ID without replaying previous messages.
fn resume_session(
self: Rc<Self>,
- _session_id: acp::SessionId,
+ _session_id: acp_v1::SessionId,
_project: Entity<Project>,
_work_dirs: PathList,
_title: Option<SharedString>,
@@ -164,17 +164,17 @@ pub trait AgentConnection {
false
}
- fn auth_methods(&self) -> &[acp::AuthMethod];
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod];
fn terminal_auth_task(
&self,
- _method: &acp::AuthMethodId,
+ _method: &acp_v1::AuthMethodId,
_cx: &App,
) -> Option<Task<Result<SpawnInTerminal>>> {
None
}
- fn authenticate(&self, method: acp::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
+ fn authenticate(&self, method: acp_v1::AuthMethodId, cx: &mut App) -> Task<Result<()>>;
fn supports_logout(&self) -> bool {
false
@@ -192,14 +192,21 @@ pub trait AgentConnection {
None
}
- fn prompt(&self, params: acp::PromptRequest, cx: &mut App)
- -> Task<Result<acp::PromptResponse>>;
+ fn prompt(
+ &self,
+ params: acp_v1::PromptRequest,
+ cx: &mut App,
+ ) -> Task<Result<acp_v1::PromptResponse>>;
- fn retry(&self, _session_id: &acp::SessionId, _cx: &App) -> Option<Rc<dyn AgentSessionRetry>> {
+ fn retry(
+ &self,
+ _session_id: &acp_v1::SessionId,
+ _cx: &App,
+ ) -> Option<Rc<dyn AgentSessionRetry>> {
None
}
- fn cancel(&self, session_id: &acp::SessionId, cx: &mut App);
+ fn cancel(&self, session_id: &acp_v1::SessionId, cx: &mut App);
/// Request-scoped elicitations are connection-level because they can arrive before a session
/// thread exists. Session-scoped elicitations stay in the thread timeline, but use
@@ -210,7 +217,7 @@ pub trait AgentConnection {
fn truncate(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionTruncate>> {
None
@@ -218,7 +225,7 @@ pub trait AgentConnection {
fn set_title(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionSetTitle>> {
None
@@ -228,7 +235,10 @@ pub trait AgentConnection {
///
/// If the agent does not support model selection, returns [None].
/// This allows sharing the selector in UI components.
- fn model_selector(&self, _session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
+ fn model_selector(
+ &self,
+ _session_id: &acp_v1::SessionId,
+ ) -> Option<Rc<dyn AgentModelSelector>> {
None
}
@@ -238,7 +248,7 @@ pub trait AgentConnection {
fn session_modes(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionModes>> {
None
@@ -246,7 +256,7 @@ pub trait AgentConnection {
fn session_config_options(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionConfigOptions>> {
None
@@ -277,13 +287,13 @@ pub trait AgentSessionClientUserMessageIds {
fn prompt(
&self,
client_user_message_id: ClientUserMessageId,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>>;
+ ) -> Task<Result<acp_v1::PromptResponse>>;
}
pub trait AgentSessionRetry {
- fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>>;
+ fn run(&self, cx: &mut App) -> Task<Result<acp_v1::PromptResponse>>;
}
pub trait AgentSessionSetTitle {
@@ -295,31 +305,31 @@ pub trait AgentTelemetry {
/// storage with telemetry events.
fn thread_data(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &mut App,
) -> Task<Result<serde_json::Value>>;
}
pub trait AgentSessionModes {
- fn current_mode(&self) -> acp::SessionModeId;
+ fn current_mode(&self) -> acp_v1::SessionModeId;
- fn all_modes(&self) -> Vec<acp::SessionMode>;
+ fn all_modes(&self) -> Vec<acp_v1::SessionMode>;
- fn set_mode(&self, mode: acp::SessionModeId, cx: &mut App) -> Task<Result<()>>;
+ fn set_mode(&self, mode: acp_v1::SessionModeId, cx: &mut App) -> Task<Result<()>>;
}
pub trait AgentSessionConfigOptions {
/// Get all current config options with their state
- fn config_options(&self) -> Vec<acp::SessionConfigOption>;
+ fn config_options(&self) -> Vec<acp_v1::SessionConfigOption>;
/// Set a config option value
/// Returns the full updated list of config options
fn set_config_option(
&self,
- config_id: acp::SessionConfigId,
- value: acp::SessionConfigOptionValue,
+ config_id: acp_v1::SessionConfigId,
+ value: acp_v1::SessionConfigOptionValue,
cx: &mut App,
- ) -> Task<Result<Vec<acp::SessionConfigOption>>>;
+ ) -> Task<Result<Vec<acp_v1::SessionConfigOption>>>;
/// Whenever the config options are updated the receiver will be notified.
/// Optional for agents that don't update their config options dynamically.
@@ -332,14 +342,14 @@ pub trait AgentSessionConfigOptions {
pub struct AgentSessionListRequest {
pub cwd: Option<PathBuf>,
pub cursor: Option<String>,
- pub meta: Option<acp::Meta>,
+ pub meta: Option<acp_v1::Meta>,
}
#[derive(Debug, Clone)]
pub struct AgentSessionListResponse {
pub sessions: Vec<AgentSessionInfo>,
pub next_cursor: Option<String>,
- pub meta: Option<acp::Meta>,
+ pub meta: Option<acp_v1::Meta>,
}
impl AgentSessionListResponse {
@@ -354,16 +364,16 @@ impl AgentSessionListResponse {
#[derive(Debug, Clone, PartialEq)]
pub struct AgentSessionInfo {
- pub session_id: acp::SessionId,
+ pub session_id: acp_v1::SessionId,
pub work_dirs: Option<PathList>,
pub title: Option<SharedString>,
pub updated_at: Option<DateTime<Utc>>,
pub created_at: Option<DateTime<Utc>>,
- pub meta: Option<acp::Meta>,
+ pub meta: Option<acp_v1::Meta>,
}
impl AgentSessionInfo {
- pub fn new(session_id: impl Into<acp::SessionId>) -> Self {
+ pub fn new(session_id: impl Into<acp_v1::SessionId>) -> Self {
Self {
session_id: session_id.into(),
work_dirs: None,
@@ -379,8 +389,8 @@ impl AgentSessionInfo {
pub enum SessionListUpdate {
Refresh,
SessionInfo {
- session_id: acp::SessionId,
- update: acp::SessionInfoUpdate,
+ session_id: acp_v1::SessionId,
+ update: acp_v1::SessionInfoUpdate,
},
}
@@ -395,7 +405,7 @@ pub trait AgentSessionList {
false
}
- fn delete_session(&self, _session_id: &acp::SessionId, _cx: &mut App) -> Task<Result<()>> {
+ fn delete_session(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) -> Task<Result<()>> {
Task::ready(Err(anyhow::anyhow!("delete_session not supported")))
}
@@ -536,8 +546,8 @@ impl AgentModelList {
#[derive(Debug, Clone)]
pub struct PermissionOptionChoice {
- pub allow: acp::PermissionOption,
- pub deny: acp::PermissionOption,
+ pub allow: acp_v1::PermissionOption,
+ pub deny: acp_v1::PermissionOption,
pub sub_patterns: Vec<String>,
}
@@ -578,7 +588,7 @@ pub struct PermissionPattern {
#[derive(Debug, Clone)]
pub enum PermissionOptions {
- Flat(Vec<acp::PermissionOption>),
+ Flat(Vec<acp_v1::PermissionOption>),
Dropdown(Vec<PermissionOptionChoice>),
DropdownWithPatterns {
choices: Vec<PermissionOptionChoice>,
@@ -598,8 +608,8 @@ impl PermissionOptions {
pub fn first_option_of_kind(
&self,
- kind: acp::PermissionOptionKind,
- ) -> Option<&acp::PermissionOption> {
+ kind: acp_v1::PermissionOptionKind,
+ ) -> Option<&acp_v1::PermissionOption> {
match self {
PermissionOptions::Flat(options) => options.iter().find(|option| option.kind == kind),
PermissionOptions::Dropdown(options) => options.iter().find_map(|choice| {
@@ -625,13 +635,13 @@ impl PermissionOptions {
}
}
- pub fn allow_once_option_id(&self) -> Option<acp::PermissionOptionId> {
- self.first_option_of_kind(acp::PermissionOptionKind::AllowOnce)
+ pub fn allow_once_option_id(&self) -> Option<acp_v1::PermissionOptionId> {
+ self.first_option_of_kind(acp_v1::PermissionOptionKind::AllowOnce)
.map(|option| option.option_id.clone())
}
- pub fn deny_once_option_id(&self) -> Option<acp::PermissionOptionId> {
- self.first_option_of_kind(acp::PermissionOptionKind::RejectOnce)
+ pub fn deny_once_option_id(&self) -> Option<acp_v1::PermissionOptionId> {
+ self.first_option_of_kind(acp_v1::PermissionOptionKind::RejectOnce)
.map(|option| option.option_id.clone())
}
@@ -754,9 +764,10 @@ mod test_support {
#[derive(Clone)]
pub struct StubAgentConnection {
- sessions: Arc<Mutex<HashMap<acp::SessionId, Session>>>,
- permission_requests: HashMap<acp::ToolCallId, PermissionOptions>,
- next_prompt_updates: Arc<Mutex<Vec<acp::SessionUpdate>>>,
+ sessions: Arc<Mutex<HashMap<acp_v1::SessionId, Session>>>,
+ permission_requests: HashMap<acp_v1::ToolCallId, PermissionOptions>,
+ next_prompt_updates: Arc<Mutex<Vec<acp_v1::SessionUpdate>>>,
+ next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
supports_load_session: bool,
supports_session_additional_directories: bool,
agent_id: AgentId,
@@ -765,7 +776,7 @@ mod test_support {
struct Session {
thread: WeakEntity<AcpThread>,
- response_tx: Option<oneshot::Sender<acp::StopReason>>,
+ response_tx: Option<oneshot::Sender<acp_v1::StopReason>>,
}
impl Default for StubAgentConnection {
@@ -778,6 +789,7 @@ mod test_support {
pub fn new() -> Self {
Self {
next_prompt_updates: Default::default(),
+ next_truncate: Default::default(),
permission_requests: HashMap::default(),
sessions: Arc::default(),
supports_load_session: false,
@@ -787,13 +799,19 @@ mod test_support {
}
}
- pub fn set_next_prompt_updates(&self, updates: Vec<acp::SessionUpdate>) {
+ pub fn set_next_prompt_updates(&self, updates: Vec<acp_v1::SessionUpdate>) {
*self.next_prompt_updates.lock() = updates;
}
+ pub fn defer_next_truncate(&self) -> oneshot::Sender<()> {
+ let (sender, receiver) = oneshot::channel();
+ assert!(self.next_truncate.lock().replace(receiver).is_none());
+ sender
+ }
+
pub fn with_permission_requests(
mut self,
- permission_requests: HashMap<acp::ToolCallId, PermissionOptions>,
+ permission_requests: HashMap<acp_v1::ToolCallId, PermissionOptions>,
) -> Self {
self.permission_requests = permission_requests;
self
@@ -824,7 +842,7 @@ mod test_support {
fn create_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
work_dirs: PathList,
title: Option<SharedString>,
@@ -841,7 +859,7 @@ mod test_support {
action_log,
session_id.clone(),
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -861,8 +879,8 @@ mod test_support {
pub fn send_update(
&self,
- session_id: acp::SessionId,
- update: acp::SessionUpdate,
+ session_id: acp_v1::SessionId,
+ update: acp_v1::SessionUpdate,
cx: &mut App,
) {
assert!(
@@ -881,7 +899,7 @@ mod test_support {
.unwrap();
}
- pub fn end_turn(&self, session_id: acp::SessionId, stop_reason: acp::StopReason) {
+ pub fn end_turn(&self, session_id: acp_v1::SessionId, stop_reason: acp_v1::StopReason) {
self.sessions
.lock()
.get_mut(&session_id)
@@ -903,13 +921,13 @@ mod test_support {
self.telemetry_id.clone()
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn model_selector(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
) -> Option<Rc<dyn AgentModelSelector>> {
Some(self.model_selector_impl())
}
@@ -920,7 +938,7 @@ mod test_support {
work_dirs: PathList,
cx: &mut gpui::App,
) -> Task<gpui::Result<Entity<AcpThread>>> {
- let session_id = acp::SessionId::new(StubSessionCounter::next(cx).to_string());
+ let session_id = acp_v1::SessionId::new(StubSessionCounter::next(cx).to_string());
let thread = self.create_session(session_id, project, work_dirs, None, cx);
Task::ready(Ok(thread))
}
@@ -935,7 +953,7 @@ mod test_support {
fn load_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
work_dirs: PathList,
title: Option<SharedString>,
@@ -951,7 +969,7 @@ mod test_support {
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
unimplemented!()
@@ -959,9 +977,9 @@ mod test_support {
fn prompt(
&self,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
let mut sessions = self.sessions.lock();
let Session {
thread,
@@ -973,13 +991,13 @@ mod test_support {
response_tx.replace(tx);
cx.spawn(async move |_| {
let stop_reason = rx.await?;
- Ok(acp::PromptResponse::new(stop_reason))
+ Ok(acp_v1::PromptResponse::new(stop_reason))
})
} else {
for update in self.next_prompt_updates.lock().drain(..) {
let thread = thread.clone();
let update = update.clone();
- let permission_request = if let acp::SessionUpdate::ToolCall(tool_call) =
+ let permission_request = if let acp_v1::SessionUpdate::ToolCall(tool_call) =
&update
&& let Some(options) = self.permission_requests.get(&tool_call.tool_call_id)
{
@@ -1010,7 +1028,7 @@ mod test_support {
cx.spawn(async move |_| {
try_join_all(tasks).await?;
- Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
})
}
}
@@ -1024,7 +1042,7 @@ mod test_support {
}))
}
- fn cancel(&self, session_id: &acp::SessionId, _cx: &mut App) {
+ fn cancel(&self, session_id: &acp_v1::SessionId, _cx: &mut App) {
if let Some(end_turn_tx) = self
.sessions
.lock()
@@ -1033,13 +1051,13 @@ mod test_support {
.response_tx
.take()
{
- end_turn_tx.send(acp::StopReason::Cancelled).unwrap();
+ end_turn_tx.send(acp_v1::StopReason::Cancelled).unwrap();
}
}
fn set_title(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionSetTitle>> {
Some(Rc::new(StubAgentSessionSetTitle))
@@ -1047,10 +1065,13 @@ mod test_support {
fn truncate(
&self,
- _session_id: &acp::SessionId,
+ _session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn AgentSessionTruncate>> {
- Some(Rc::new(StubAgentSessionEditor))
+ // Capability checks also call this; only run may consume the gate.
+ Some(Rc::new(StubAgentSessionEditor {
+ next_truncate: self.next_truncate.clone(),
+ }))
}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
@@ -1074,18 +1095,27 @@ mod test_support {
fn prompt(
&self,
_client_user_message_id: ClientUserMessageId,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
self.connection.prompt(params, cx)
}
}
- struct StubAgentSessionEditor;
+ struct StubAgentSessionEditor {
+ next_truncate: Arc<Mutex<Option<oneshot::Receiver<()>>>>,
+ }
impl AgentSessionTruncate for StubAgentSessionEditor {
- fn run(&self, _: ClientUserMessageId, _: &mut App) -> Task<Result<()>> {
- Task::ready(Ok(()))
+ fn run(&self, _: ClientUserMessageId, cx: &mut App) -> Task<Result<()>> {
+ if let Some(receiver) = self.next_truncate.lock().take() {
+ cx.foreground_executor().spawn(async move {
+ receiver.await?;
+ Ok(())
+ })
+ } else {
+ Task::ready(Ok(()))
+ }
}
}
diff --git a/crates/acp_thread/src/content.rs b/crates/acp_thread/src/content.rs
new file mode 100644
index 00000000000..93a85d5263b
--- /dev/null
+++ b/crates/acp_thread/src/content.rs
@@ -0,0 +1,578 @@
+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
+use anyhow::{Result, bail};
+
+pub fn from_v1(block: acp_v1::ContentBlock) -> Result<acp_v2::ContentBlock> {
+ Ok(match block {
+ acp_v1::ContentBlock::Text(content) => acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new(content.text)
+ .annotations(annotations_from_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v1::ContentBlock::Image(content) => acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new(content.data, content.mime_type)
+ .uri(content.uri)
+ .annotations(annotations_from_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v1::ContentBlock::Audio(content) => acp_v2::ContentBlock::Audio(
+ acp_v2::AudioContent::new(content.data, content.mime_type)
+ .annotations(annotations_from_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v1::ContentBlock::ResourceLink(content) => acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new(content.name, content.uri)
+ .title(content.title)
+ .description(content.description)
+ .mime_type(content.mime_type.map(acp_v2::MediaType::new))
+ .size(content.size)
+ .annotations(annotations_from_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v1::ContentBlock::Resource(content) => {
+ let resource = match content.resource {
+ acp_v1::EmbeddedResourceResource::TextResourceContents(resource) => {
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new(resource.text, resource.uri)
+ .mime_type(resource.mime_type.map(acp_v2::MediaType::new))
+ .meta(resource.meta),
+ )
+ }
+ acp_v1::EmbeddedResourceResource::BlobResourceContents(resource) => {
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new(resource.blob, resource.uri)
+ .mime_type(resource.mime_type.map(acp_v2::MediaType::new))
+ .meta(resource.meta),
+ )
+ }
+ _ => bail!("unsupported v1 embedded resource variant"),
+ };
+ acp_v2::ContentBlock::Resource(
+ acp_v2::EmbeddedResource::new(resource)
+ .annotations(annotations_from_v1(content.annotations)?)
+ .meta(content.meta),
+ )
+ }
+ _ => bail!("unsupported v1 content block variant"),
+ })
+}
+
+/// An empty icon list normalizes to absence; other unrepresentable fields are rejected.
+pub fn to_v1(block: acp_v2::ContentBlock) -> Result<acp_v1::ContentBlock> {
+ Ok(match block {
+ acp_v2::ContentBlock::Text(content) => acp_v1::ContentBlock::Text(
+ acp_v1::TextContent::new(content.text)
+ .annotations(annotations_to_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v2::ContentBlock::Image(content) => acp_v1::ContentBlock::Image(
+ acp_v1::ImageContent::new(content.data, content.mime_type.0.to_string())
+ .uri(content.uri)
+ .annotations(annotations_to_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v2::ContentBlock::Audio(content) => acp_v1::ContentBlock::Audio(
+ acp_v1::AudioContent::new(content.data, content.mime_type.0.to_string())
+ .annotations(annotations_to_v1(content.annotations)?)
+ .meta(content.meta),
+ ),
+ acp_v2::ContentBlock::ResourceLink(content) => {
+ if content
+ .icons
+ .as_ref()
+ .is_some_and(|icons| !icons.is_empty())
+ {
+ bail!("v2 resource link icons cannot be represented in v1");
+ }
+ acp_v1::ContentBlock::ResourceLink(
+ acp_v1::ResourceLink::new(content.name, content.uri)
+ .title(content.title)
+ .description(content.description)
+ .mime_type(content.mime_type.map(|mime_type| mime_type.0.to_string()))
+ .size(content.size)
+ .annotations(annotations_to_v1(content.annotations)?)
+ .meta(content.meta),
+ )
+ }
+ acp_v2::ContentBlock::Resource(content) => {
+ let resource = match content.resource {
+ acp_v2::EmbeddedResourceResource::TextResourceContents(resource) => {
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(resource.text, resource.uri)
+ .mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string()))
+ .meta(resource.meta),
+ )
+ }
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(resource) => {
+ acp_v1::EmbeddedResourceResource::BlobResourceContents(
+ acp_v1::BlobResourceContents::new(resource.blob, resource.uri)
+ .mime_type(resource.mime_type.map(|mime_type| mime_type.0.to_string()))
+ .meta(resource.meta),
+ )
+ }
+ _ => bail!("unsupported v2 embedded resource variant"),
+ };
+ acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(resource)
+ .annotations(annotations_to_v1(content.annotations)?)
+ .meta(content.meta),
+ )
+ }
+ acp_v2::ContentBlock::Other(_) => {
+ bail!("v2 custom content block cannot be represented in v1")
+ }
+ _ => bail!("unsupported v2 content block variant"),
+ })
+}
+
+pub fn can_convert_to_v1(block: &acp_v2::ContentBlock) -> bool {
+ let annotations = match block {
+ acp_v2::ContentBlock::Text(content) => &content.annotations,
+ acp_v2::ContentBlock::Image(content) => &content.annotations,
+ acp_v2::ContentBlock::Audio(content) => &content.annotations,
+ acp_v2::ContentBlock::ResourceLink(content)
+ if content.icons.as_ref().is_none_or(Vec::is_empty) =>
+ {
+ &content.annotations
+ }
+ acp_v2::ContentBlock::Resource(content)
+ if matches!(
+ content.resource,
+ acp_v2::EmbeddedResourceResource::TextResourceContents(_)
+ | acp_v2::EmbeddedResourceResource::BlobResourceContents(_)
+ ) =>
+ {
+ &content.annotations
+ }
+ _ => return false,
+ };
+ annotations
+ .as_ref()
+ .and_then(|annotations| annotations.audience.as_ref())
+ .is_none_or(|audience| {
+ audience
+ .iter()
+ .all(|role| matches!(role, acp_v2::Role::Assistant | acp_v2::Role::User))
+ })
+}
+
+fn annotations_from_v1(
+ annotations: Option<acp_v1::Annotations>,
+) -> Result<Option<acp_v2::Annotations>> {
+ annotations
+ .map(|annotations| {
+ let audience = annotations
+ .audience
+ .map(|audience| {
+ audience
+ .into_iter()
+ .map(|role| match role {
+ acp_v1::Role::Assistant => Ok(acp_v2::Role::Assistant),
+ acp_v1::Role::User => Ok(acp_v2::Role::User),
+ _ => bail!("unsupported v1 annotation role"),
+ })
+ .collect::<Result<Vec<_>>>()
+ })
+ .transpose()?;
+ Ok(acp_v2::Annotations::new()
+ .audience(audience)
+ .last_modified(annotations.last_modified)
+ .priority(annotations.priority)
+ .meta(annotations.meta))
+ })
+ .transpose()
+}
+
+fn annotations_to_v1(
+ annotations: Option<acp_v2::Annotations>,
+) -> Result<Option<acp_v1::Annotations>> {
+ annotations
+ .map(|annotations| {
+ let audience = annotations
+ .audience
+ .map(|audience| {
+ audience
+ .into_iter()
+ .map(|role| match role {
+ acp_v2::Role::Assistant => Ok(acp_v1::Role::Assistant),
+ acp_v2::Role::User => Ok(acp_v1::Role::User),
+ acp_v2::Role::Other(_) => {
+ bail!("v2 annotation role cannot be represented in v1")
+ }
+ _ => bail!("unsupported v2 annotation role"),
+ })
+ .collect::<Result<Vec<_>>>()
+ })
+ .transpose()?;
+ Ok(acp_v1::Annotations::new()
+ .audience(audience)
+ .last_modified(annotations.last_modified)
+ .priority(annotations.priority)
+ .meta(annotations.meta))
+ })
+ .transpose()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::{Value, json};
+ use std::collections::BTreeMap;
+
+ fn meta() -> serde_json::Map<String, Value> {
+ serde_json::Map::from_iter([("origin".to_owned(), json!({"nested": [0, null, "value"]}))])
+ }
+
+ fn annotations() -> acp_v1::Annotations {
+ acp_v1::Annotations::new()
+ .audience(vec![acp_v1::Role::User, acp_v1::Role::Assistant])
+ .last_modified("2025-01-02T03:04:05Z")
+ .priority(0.75)
+ .meta(meta())
+ }
+
+ fn round_trip(block: acp_v1::ContentBlock) {
+ let original = block.clone();
+ let upgraded = from_v1(block).expect("v1 block should convert to v2");
+ assert!(can_convert_to_v1(&upgraded));
+ assert_eq!(
+ serde_json::to_value(&upgraded).expect("serialize v2 block"),
+ serde_json::to_value(&original).expect("serialize original block")
+ );
+ let restored = to_v1(upgraded).expect("converted block should convert back to v1");
+ assert_eq!(restored, original);
+ }
+
+ fn rejects(block: acp_v2::ContentBlock) {
+ assert!(!can_convert_to_v1(&block));
+ assert!(to_v1(block).is_err());
+ }
+
+ #[test]
+ fn preserves_all_v1_content_variants_and_metadata() {
+ round_trip(acp_v1::ContentBlock::Text(
+ acp_v1::TextContent::new("Hello \0 世界")
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ round_trip(acp_v1::ContentBlock::Image(
+ acp_v1::ImageContent::new("AAECA/8=", "not/a valid mime ; 😀")
+ .uri("")
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ round_trip(acp_v1::ContentBlock::Audio(
+ acp_v1::AudioContent::new("///+", "")
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ round_trip(acp_v1::ContentBlock::ResourceLink(
+ acp_v1::ResourceLink::new("name", "file:///some/resource")
+ .title("")
+ .description("description")
+ .mime_type("??")
+ .size(0)
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ round_trip(acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new("source text", "file:///text")
+ .mime_type("")
+ .meta(meta()),
+ ))
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ round_trip(acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents(
+ acp_v1::BlobResourceContents::new("AAECA/8=", "file:///blob")
+ .mime_type("bad mime")
+ .meta(meta()),
+ ))
+ .annotations(annotations())
+ .meta(meta()),
+ ));
+ }
+
+ #[test]
+ fn preserves_absent_and_empty_optional_fields() {
+ round_trip(acp_v1::ContentBlock::Text(acp_v1::TextContent::new("")));
+ round_trip(acp_v1::ContentBlock::Text(
+ acp_v1::TextContent::new("")
+ .annotations(acp_v1::Annotations::new().audience(Vec::new())),
+ ));
+ round_trip(acp_v1::ContentBlock::Text(
+ acp_v1::TextContent::new("")
+ .annotations(acp_v1::Annotations::new())
+ .meta(acp_v1::Meta::new()),
+ ));
+ round_trip(acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new("", "").meta(acp_v1::Meta::new()),
+ ))
+ .annotations(acp_v1::Annotations::new().meta(acp_v1::Meta::new()))
+ .meta(acp_v1::Meta::new()),
+ ));
+ round_trip(acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(
+ "", "",
+ )));
+ round_trip(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new(
+ "", "",
+ )));
+ round_trip(acp_v1::ContentBlock::ResourceLink(
+ acp_v1::ResourceLink::new("", ""),
+ ));
+ round_trip(acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new("", ""),
+ )),
+ ));
+ round_trip(acp_v1::ContentBlock::Resource(
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::BlobResourceContents(
+ acp_v1::BlobResourceContents::new("", ""),
+ )),
+ ));
+ }
+
+ #[test]
+ fn accepts_empty_icons_without_discarding_resource_data() {
+ let link = acp_v2::ResourceLink::new("Reference", "https://example.com/resource")
+ .title("Resource title")
+ .description("Resource description")
+ .mime_type("custom/type")
+ .size(0)
+ .annotations(
+ acp_v2::Annotations::new()
+ .audience(vec![acp_v2::Role::User])
+ .meta(meta()),
+ )
+ .meta(meta());
+ let original = acp_v2::ContentBlock::ResourceLink(link.clone().icons(Vec::new()));
+ let expected = acp_v2::ContentBlock::ResourceLink(link);
+
+ assert!(can_convert_to_v1(&original));
+ assert_eq!(
+ serde_json::to_value(&original).expect("serialize original")["icons"],
+ json!([])
+ );
+ let downgraded = to_v1(original).expect("empty icon list should not prevent conversion");
+ assert_eq!(
+ serde_json::to_value(&downgraded).expect("serialize v1"),
+ serde_json::to_value(&expected).expect("serialize normalized v2"),
+ );
+ assert_eq!(from_v1(downgraded).expect("restore v2"), expected);
+ }
+
+ #[test]
+ fn rejects_v2_only_content_and_annotations() {
+ rejects(acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
+ "_custom",
+ BTreeMap::from([("payload".to_owned(), json!({"opaque": [1, 2]}))]),
+ )));
+ rejects(acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new("AAE=", "image/png").annotations(
+ acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_custom".into())]),
+ ),
+ ));
+ rejects(acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("name", "uri")
+ .icons(Vec::new())
+ .annotations(
+ acp_v2::Annotations::new()
+ .audience(vec![acp_v2::Role::Other("_custom".into())]),
+ ),
+ ));
+ rejects(acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("name", "uri").icons(vec![acp_v2::Icon::new("file:///icon")]),
+ ));
+ }
+
+ fn round_trip_from_v2(block: acp_v2::ContentBlock) {
+ assert!(can_convert_to_v1(&block), "{block:?}");
+ let original_wire = serde_json::to_value(&block).expect("serialize original v2 block");
+ let downgraded = to_v1(block.clone()).expect("representable v2 block converts to v1");
+ assert_eq!(
+ serde_json::to_value(&downgraded).expect("serialize intermediate v1 block"),
+ original_wire
+ );
+ assert_eq!(
+ from_v1(downgraded).expect("v1 block converts back to v2"),
+ block
+ );
+ }
+
+ #[test]
+ fn preserves_independently_constructed_v2_content() {
+ for (annotations, outer_meta, resource_meta) in [
+ (None, None, None),
+ (
+ Some(
+ acp_v2::Annotations::new()
+ .audience(Vec::new())
+ .meta(serde_json::Map::new()),
+ ),
+ Some(serde_json::Map::new()),
+ Some(serde_json::Map::new()),
+ ),
+ (
+ Some(
+ acp_v2::Annotations::new()
+ .audience(vec![
+ acp_v2::Role::User,
+ acp_v2::Role::Assistant,
+ acp_v2::Role::User,
+ ])
+ .last_modified("not a date \0 雪")
+ .priority(-0.25)
+ .meta(serde_json::Map::from_iter([(
+ "hint".to_owned(),
+ json!({"items": [false, null, "é"]}),
+ )])),
+ ),
+ Some(serde_json::Map::from_iter([(
+ "outer".to_owned(),
+ json!({"key": [1, "\n"]}),
+ )])),
+ Some(serde_json::Map::from_iter([(
+ "resource".to_owned(),
+ json!({"nested": {"value": 2}}),
+ )])),
+ ),
+ ] {
+ let blocks = [
+ acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("Hello \0 世界\n")
+ .annotations(annotations.clone())
+ .meta(outer_meta.clone()),
+ ),
+ acp_v2::ContentBlock::Image(
+ acp_v2::ImageContent::new("AAECA/8=", "not/a valid mime ; 😀")
+ .uri("")
+ .annotations(annotations.clone())
+ .meta(outer_meta.clone()),
+ ),
+ acp_v2::ContentBlock::Audio(
+ acp_v2::AudioContent::new("///+", "")
+ .annotations(annotations.clone())
+ .meta(outer_meta.clone()),
+ ),
+ acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("名\n", "file:///a")
+ .title("")
+ .description("description \0")
+ .mime_type("??")
+ .size(0)
+ .annotations(annotations.clone())
+ .meta(outer_meta.clone()),
+ ),
+ acp_v2::ContentBlock::Resource(
+ acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new("source \0 text", "file:///text")
+ .mime_type("")
+ .meta(resource_meta.clone()),
+ ),
+ )
+ .annotations(annotations.clone())
+ .meta(outer_meta.clone()),
+ ),
+ acp_v2::ContentBlock::Resource(
+ acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new("AAECA/8=", "file:///blob")
+ .mime_type("bad mime")
+ .meta(resource_meta),
+ ),
+ )
+ .annotations(annotations)
+ .meta(outer_meta),
+ ),
+ ];
+ for block in blocks {
+ round_trip_from_v2(block);
+ }
+ }
+
+ for block in [
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new("")),
+ acp_v2::ContentBlock::Image(acp_v2::ImageContent::new("", "")),
+ acp_v2::ContentBlock::Audio(acp_v2::AudioContent::new("", "")),
+ acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("", "")
+ .size(i64::MAX)
+ .annotations(acp_v2::Annotations::new().priority(0.125)),
+ ),
+ acp_v2::ContentBlock::ResourceLink(
+ acp_v2::ResourceLink::new("negative size", "file:///negative").size(-1),
+ ),
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::TextResourceContents(
+ acp_v2::TextResourceContents::new("", ""),
+ ),
+ )),
+ acp_v2::ContentBlock::Resource(acp_v2::EmbeddedResource::new(
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(
+ acp_v2::BlobResourceContents::new("", ""),
+ ),
+ )),
+ ] {
+ round_trip_from_v2(block);
+ }
+ }
+
+ #[test]
+ fn v1_sdk_wire_values_round_trip_after_sdk_normalization() {
+ for wire in [
+ json!({
+ "type": "text",
+ "text": "wire \0 世界",
+ "annotations": {
+ "audience": ["user", 42, "_future", "assistant", "user"],
+ "lastModified": false,
+ "priority": "invalid",
+ "_meta": {"valid": [null, 1]}
+ },
+ "_meta": {"outer": {"nested": true}}
+ }),
+ json!({
+ "type": "image",
+ "data": "",
+ "mimeType": "not/a valid mime ; 😀",
+ "uri": 123,
+ "annotations": {"audience": [], "priority": 0.25},
+ "_meta": false
+ }),
+ json!({
+ "type": "resource_link",
+ "name": "link",
+ "uri": "file:///link",
+ "title": 7,
+ "description": "",
+ "mimeType": "??",
+ "size": "large",
+ "annotations": {"audience": ["assistant"]},
+ "_meta": {}
+ }),
+ ] {
+ let decoded: acp_v1::ContentBlock =
+ serde_json::from_value(wire.clone()).expect("v1 SDK accepts wire fixture");
+ let normalized = serde_json::to_value(&decoded).expect("serialize normalized v1");
+ assert_ne!(
+ normalized, wire,
+ "v1 SDK normalizes malformed optional hints"
+ );
+ let upgraded = from_v1(decoded.clone()).expect("adapter accepts decoded v1 value");
+ assert!(can_convert_to_v1(&upgraded));
+ assert_eq!(
+ serde_json::to_value(&upgraded).expect("serialize upgraded v2"),
+ normalized
+ );
+ let restored = to_v1(upgraded).expect("adapter restores decoded v1 value");
+ assert_eq!(restored, decoded);
+ assert_eq!(
+ serde_json::to_value(restored).expect("serialize restored v1"),
+ normalized
+ );
+ }
+ }
+}
diff --git a/crates/agent/src/agent.rs b/crates/agent/src/agent.rs
index ebede3a87d9..f94d36aa4e3 100644
--- a/crates/agent/src/agent.rs
+++ b/crates/agent/src/agent.rs
@@ -33,7 +33,7 @@ use acp_thread::{
AcpThread, AgentModelId, AgentModelSelector, AgentSessionInfo, AgentSessionList,
AgentSessionListRequest, AgentSessionListResponse, ClientUserMessageId, TokenUsageRatio,
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v1 as acp_v1;
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 +240,7 @@ struct Session {
}
impl Session {
- fn draft_prompt(&self, cx: &App) -> Option<Vec<acp::ContentBlock>> {
+ fn draft_prompt(&self, cx: &App) -> Option<Vec<acp_v1::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),
@@ -439,8 +439,8 @@ pub trait SiblingThreadHost {
pub struct NativeAgent {
/// Session ID -> Session mapping
- sessions: HashMap<acp::SessionId, Session>,
- pending_sessions: HashMap<acp::SessionId, PendingSession>,
+ sessions: HashMap<acp_v1::SessionId, Session>,
+ pending_sessions: HashMap<acp_v1::SessionId, PendingSession>,
thread_store: Entity<ThreadStore>,
/// Project-specific state keyed by project EntityId
projects: HashMap<EntityId, ProjectState>,
@@ -991,7 +991,7 @@ impl NativeAgent {
);
}
- fn session_project_state(&self, session_id: &acp::SessionId) -> Option<&ProjectState> {
+ fn session_project_state(&self, session_id: &acp_v1::SessionId) -> Option<&ProjectState> {
self.sessions
.get(session_id)
.and_then(|session| self.projects.get(&session.project_id))
@@ -1562,8 +1562,8 @@ impl NativeAgent {
.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AvailableCommandsUpdate(
- acp::AvailableCommandsUpdate::new(available_commands.clone()),
+ acp_v1::SessionUpdate::AvailableCommandsUpdate(
+ acp_v1::AvailableCommandsUpdate::new(available_commands.clone()),
),
cx,
)
@@ -1576,11 +1576,11 @@ impl NativeAgent {
fn build_available_commands_for_project(
project_state: Option<&ProjectState>,
cx: &App,
- ) -> Vec<acp::AvailableCommand> {
+ ) -> Vec<acp_v1::AvailableCommand> {
let Some(state) = project_state else {
return Vec::new();
};
- let compact_command = acp::AvailableCommand::new(
+ let compact_command = acp_v1::AvailableCommand::new(
COMPACT_COMMAND_NAME,
"Summarize the conversation so far to free up context",
)
@@ -1610,7 +1610,7 @@ impl NativeAgent {
};
let mut command =
- acp::AvailableCommand::new(name, prompt.description.clone().unwrap_or_default())
+ acp_v1::AvailableCommand::new(name, prompt.description.clone().unwrap_or_default())
.meta(acp_thread::meta_with_command_category(
acp_thread::CommandCategory::Mcp,
));
@@ -1619,8 +1619,8 @@ impl NativeAgent {
Some([arg]) => {
let hint = format!("<{}>", arg.name);
- command = command.input(acp::AvailableCommandInput::Unstructured(
- acp::UnstructuredCommandInput::new(hint),
+ command = command.input(acp_v1::AvailableCommandInput::Unstructured(
+ acp_v1::UnstructuredCommandInput::new(hint),
));
}
Some([]) | None => {}
@@ -1640,7 +1640,7 @@ impl NativeAgent {
pub fn load_thread(
&mut self,
- id: acp::SessionId,
+ id: acp_v1::SessionId,
project: Entity<Project>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<Thread>>> {
@@ -1680,7 +1680,7 @@ impl NativeAgent {
pub fn open_thread(
&mut self,
- id: acp::SessionId,
+ id: acp_v1::SessionId,
project: Entity<Project>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<AcpThread>>> {
@@ -1747,7 +1747,7 @@ impl NativeAgent {
pub fn thread_summary(
&mut self,
- id: acp::SessionId,
+ id: acp_v1::SessionId,
project: Entity<Project>,
cx: &mut Context<Self>,
) -> Task<Result<SharedString>> {
@@ -1772,9 +1772,9 @@ impl NativeAgent {
fn release_session(
&mut self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
acp_thread_id: EntityId,
- draft_prompt: Option<Vec<acp::ContentBlock>>,
+ draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
cx: &mut Context<Self>,
) {
let Some(session) = self.sessions.get(session_id) else {
@@ -1809,8 +1809,8 @@ impl NativeAgent {
fn enqueue_save(
&mut self,
- id: &acp::SessionId,
- draft_prompt: Option<Vec<acp::ContentBlock>>,
+ id: &acp_v1::SessionId,
+ draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
cx: &mut Context<Self>,
) {
let Some(session) = self.sessions.get(id) else {
@@ -1833,7 +1833,7 @@ impl NativeAgent {
}
async fn run_save_worker(
- id: acp::SessionId,
+ id: acp_v1::SessionId,
mut wake: watch::Receiver<()>,
pending_save: Arc<Mutex<Option<PendingThreadSave>>>,
database_future: Shared<Task<Result<Arc<ThreadsDatabase>, Arc<anyhow::Error>>>>,
@@ -1873,9 +1873,9 @@ impl NativeAgent {
fn thread_save_payload(
&self,
session: &Session,
- draft_prompt: Option<Vec<acp::ContentBlock>>,
+ draft_prompt: Option<Vec<acp_v1::ContentBlock>>,
cx: &mut App,
- ) -> Option<(acp::SessionId, PathList, Task<DbThread>)> {
+ ) -> Option<(acp_v1::SessionId, PathList, Task<DbThread>)> {
if session.thread.read(cx).is_empty() {
return None;
}
@@ -1933,13 +1933,13 @@ impl NativeAgent {
fn send_mcp_prompt(
&self,
client_user_message_id: ClientUserMessageId,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
prompt_name: String,
server_id: ContextServerId,
arguments: HashMap<String, String>,
- original_content: Vec<acp::ContentBlock>,
+ original_content: Vec<acp_v1::ContentBlock>,
cx: &mut Context<Self>,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
let Some(state) = self.session_project_state(&session_id) else {
return Task::ready(Err(anyhow!("Project state not found for session")));
};
@@ -1980,6 +1980,7 @@ impl NativeAgent {
for message in prompt.messages {
let context_server::types::PromptMessage { role, content } = message;
let block = mcp_message_content_to_acp_content_block(content);
+ let display_block = acp_thread::content::from_v1(block.clone())?;
match role {
context_server::types::Role::User => {
@@ -1988,7 +1989,7 @@ impl NativeAgent {
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
Some(id.clone()),
- block.clone(),
+ display_block,
true,
cx,
);
@@ -2001,7 +2002,7 @@ impl NativeAgent {
context_server::types::Role::Assistant => {
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_assistant_content_block_with_indent(
- block.clone(),
+ display_block,
false,
true,
cx,
@@ -2044,9 +2045,9 @@ impl NativeAgent {
fn send_compact_command(
&self,
client_user_message_id: ClientUserMessageId,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut Context<Self>,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
cx.spawn(async move |this, cx| {
let (acp_thread, thread) = this.update(cx, |this, _cx| {
let session = this
@@ -2090,11 +2091,11 @@ impl NativeAgent {
fn send_skill_invocation(
&self,
client_user_message_id: ClientUserMessageId,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
skill: Skill,
- original_content: Vec<acp::ContentBlock>,
+ original_content: Vec<acp_v1::ContentBlock>,
cx: &mut Context<Self>,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
let Some(state) = self.session_project_state(&session_id) else {
return Task::ready(Err(anyhow!("Project state not found for session")));
};
@@ -2136,10 +2137,10 @@ impl NativeAgent {
})?
};
let envelope = crate::tools::render_skill_envelope(&skill, &body);
- let envelope_block = acp::ContentBlock::Text(acp::TextContent::new(envelope));
+ let envelope_block = acp_v1::ContentBlock::Text(acp_v1::TextContent::new(envelope));
let mut user_blocks = original_content;
- if let Some(acp::ContentBlock::Text(text_content)) = user_blocks.first_mut() {
+ if let Some(acp_v1::ContentBlock::Text(text_content)) = user_blocks.first_mut() {
let stripped = strip_slash_command_prefix(&text_content.text);
if stripped.trim().is_empty() {
user_blocks.remove(0);
@@ -2153,10 +2154,11 @@ impl NativeAgent {
// user's own typed message is already rendered by the normal
// prompt flow, so we don't push it to the UI again here.
let injected_id = acp_thread::ClientUserMessageId::new();
+ let display_block = acp_thread::content::from_v1(envelope_block.clone())?;
acp_thread.update(cx, |acp_thread, cx| {
acp_thread.push_user_content_block_with_indent(
Some(injected_id),
- envelope_block.clone(),
+ display_block,
true,
cx,
);
@@ -2193,7 +2195,7 @@ impl NativeAgent {
pub struct NativeAgentConnection(pub Entity<NativeAgent>);
impl NativeAgentConnection {
- pub fn thread(&self, session_id: &acp::SessionId, cx: &App) -> Option<Entity<Thread>> {
+ pub fn thread(&self, session_id: &acp_v1::SessionId, cx: &App) -> Option<Entity<Thread>> {
self.0
.read(cx)
.sessions
@@ -2223,7 +2225,7 @@ impl NativeAgentConnection {
pub fn available_skills(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
) -> Vec<NativeAvailableSkill> {
self.0
@@ -2241,7 +2243,7 @@ impl NativeAgentConnection {
pub fn load_thread(
&self,
- id: acp::SessionId,
+ id: acp_v1::SessionId,
project: Entity<Project>,
cx: &mut App,
) -> Task<Result<Entity<Thread>>> {
@@ -2251,11 +2253,11 @@ impl NativeAgentConnection {
fn run_turn(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut App,
f: impl 'static
+ FnOnce(Entity<Thread>, &mut App) -> Result<mpsc::UnboundedReceiver<Result<ThreadEvent>>>,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
let Some((thread, acp_thread)) = self.0.update(cx, |agent, _cx| {
let session = agent.sessions.get(&session_id)?;
Some((session.thread.clone(), session.acp_thread.clone()))
@@ -2277,7 +2279,7 @@ impl NativeAgentConnection {
acp_thread: WeakEntity<AcpThread>,
connection: Option<NativeAgentConnection>,
cx: &App,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
cx.spawn(async move |cx| {
// Handle response stream and forward to session.acp_thread
while let Some(result) = events.next().await {
@@ -2287,11 +2289,14 @@ impl NativeAgentConnection {
match event {
ThreadEvent::UserMessage(message) => {
+ let content = message.content.iter().cloned()
+ .map(|content| acp_thread::content::from_v1(content.into()))
+ .collect::<Result<Vec<_>>>()?;
acp_thread.update(cx, |thread, cx| {
- for content in &*message.content {
+ for content in content {
thread.push_user_content_block(
Some(message.id.clone()),
- content.clone().into(),
+ content,
cx,
);
}
@@ -2324,10 +2329,10 @@ impl NativeAgentConnection {
acp_thread::RequestPermissionOutcome::Selected(outcome) => outcome,
acp_thread::RequestPermissionOutcome::InterruptedByFollowUp => {
acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new(
+ acp_v1::PermissionOptionId::new(
FOLLOW_UP_PERMISSION_DENIED_OPTION_ID,
),
- acp::PermissionOptionKind::RejectOnce,
+ acp_v1::PermissionOptionKind::RejectOnce,
)
}
acp_thread::RequestPermissionOutcome::Cancelled => return,
@@ -2354,12 +2359,12 @@ impl NativeAgentConnection {
response,
}) => {
let request_result = acp_thread.update(cx, |thread, cx| {
- let scope = acp::ElicitationSessionScope::new(
+ let scope = acp_v1::ElicitationSessionScope::new(
thread.session_id().clone(),
)
.tool_call_id(tool_call_id);
- let request = acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(scope, schema),
+ let request = acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(scope, schema),
message,
);
thread.request_elicitation(request, cx)
@@ -2383,8 +2388,8 @@ impl NativeAgentConnection {
// doesn't hang waiting on a form that will
// never render.
response
- .send(acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Cancel,
+ .send(acp_v1::CreateElicitationResponse::new(
+ acp_v1::ElicitationAction::Cancel,
))
.ok();
}
@@ -2433,7 +2438,7 @@ impl NativeAgentConnection {
}
ThreadEvent::Stop(stop_reason) => {
log::debug!("Assistant message complete: {:?}", stop_reason);
- return Ok(acp::PromptResponse::new(stop_reason));
+ return Ok(acp_v1::PromptResponse::new(stop_reason));
}
}
}
@@ -2445,7 +2450,7 @@ impl NativeAgentConnection {
}
log::debug!("Response stream completed");
- anyhow::Ok(acp::PromptResponse::new(acp::StopReason::EndTurn))
+ anyhow::Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn))
})
}
}
@@ -2473,8 +2478,8 @@ impl<'a> Command<'a> {
&& self.skill_scope.is_none()
}
- fn parse(prompt: &'a [acp::ContentBlock]) -> Option<Self> {
- let acp::ContentBlock::Text(text_content) = prompt.first()? else {
+ fn parse(prompt: &'a [acp_v1::ContentBlock]) -> Option<Self> {
+ let acp_v1::ContentBlock::Text(text_content) = prompt.first()? else {
return None;
};
let text = text_content.text.trim();
@@ -2544,7 +2549,7 @@ fn strip_slash_command_prefix(text: &str) -> String {
}
struct NativeAgentModelSelector {
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
connection: NativeAgentConnection,
}
@@ -2793,7 +2798,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
fn load_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
_work_dirs: PathList,
_title: Option<SharedString>,
@@ -2803,15 +2808,15 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
.update(cx, |agent, cx| agent.open_thread(session_id, project, cx))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[] // No auth for in-process
}
- fn authenticate(&self, _method: acp::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
+ fn authenticate(&self, _method: acp_v1::AuthMethodId, _cx: &mut App) -> Task<Result<()>> {
Task::ready(Ok(()))
}
- fn model_selector(&self, session_id: &acp::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
+ fn model_selector(&self, session_id: &acp_v1::SessionId) -> Option<Rc<dyn AgentModelSelector>> {
Some(Rc::new(NativeAgentModelSelector {
session_id: session_id.clone(),
connection: self.clone(),
@@ -2828,9 +2833,9 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
fn prompt(
&self,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
acp_thread::AgentSessionClientUserMessageIds::prompt(
self,
acp_thread::AgentSessionClientUserMessageIds::new_id(self),
@@ -2841,7 +2846,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
fn retry(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
_cx: &App,
) -> Option<Rc<dyn acp_thread::AgentSessionRetry>> {
Some(Rc::new(NativeAgentSessionRetry {
@@ -2850,7 +2855,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
}) as _)
}
- fn cancel(&self, session_id: &acp::SessionId, cx: &mut App) {
+ fn cancel(&self, session_id: &acp_v1::SessionId, cx: &mut App) {
log::info!("Cancelling on session: {}", session_id);
self.0.update(cx, |agent, cx| {
if let Some(session) = agent.sessions.get(session_id) {
@@ -2864,7 +2869,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
fn truncate(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
) -> Option<Rc<dyn acp_thread::AgentSessionTruncate>> {
self.0.read_with(cx, |agent, _cx| {
@@ -2879,7 +2884,7 @@ impl acp_thread::AgentConnection for NativeAgentConnection {
fn set_title(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
) -> Option<Rc<dyn acp_thread::AgentSessionSetTitle>> {
self.0.read_with(cx, |agent, _cx| {
@@ -2913,9 +2918,9 @@ impl acp_thread::AgentSessionClientUserMessageIds for NativeAgentConnection {
fn prompt(
&self,
client_user_message_id: acp_thread::ClientUserMessageId,
- params: acp::PromptRequest,
+ params: acp_v1::PromptRequest,
cx: &mut App,
- ) -> Task<Result<acp::PromptResponse>> {
+ ) -> Task<Result<acp_v1::PromptResponse>> {
let session_id = params.session_id.clone();
log::info!("Received prompt request for session: {}", session_id);
log::debug!("Prompt blocks count: {}", params.prompt.len());
@@ -3073,7 +3078,7 @@ impl acp_thread::AgentSessionClientUserMessageIds for NativeAgentConnection {
impl acp_thread::AgentTelemetry for NativeAgentConnection {
fn thread_data(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &mut App,
) -> Task<Result<serde_json::Value>> {
let Some(session) = self.0.read(cx).sessions.get(session_id) else {
@@ -3135,7 +3140,7 @@ impl AgentSessionList for NativeAgentSessionList {
true
}
- fn delete_session(&self, session_id: &acp::SessionId, cx: &mut App) -> Task<Result<()>> {
+ fn delete_session(&self, session_id: &acp_v1::SessionId, cx: &mut App) -> Task<Result<()>> {
self.thread_store
.update(cx, |store, cx| store.delete_thread(session_id.clone(), cx))
}
@@ -3193,11 +3198,11 @@ impl acp_thread::AgentSessionTruncate for NativeAgentSessionTruncate {
struct NativeAgentSessionRetry {
connection: NativeAgentConnection,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
}
impl acp_thread::AgentSessionRetry for NativeAgentSessionRetry {
- fn run(&self, cx: &mut App) -> Task<Result<acp::PromptResponse>> {
+ fn run(&self, cx: &mut App) -> Task<Result<acp_v1::PromptResponse>> {
self.connection
.run_turn(self.session_id.clone(), cx, |thread, cx| {
thread.update(cx, |thread, cx| thread.resume(cx))
@@ -3297,7 +3302,7 @@ impl NativeThreadEnvironment {
pub(crate) fn resume_subagent_thread(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut App,
) -> Result<Rc<dyn SubagentHandle>> {
let (subagent_thread, acp_thread) = self.agent.update(cx, |agent, _cx| {
@@ -3329,7 +3334,7 @@ impl NativeThreadEnvironment {
fn prompt_subagent(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
subagent_thread: Entity<Thread>,
acp_thread: Entity<acp_thread::AcpThread>,
) -> Result<Rc<dyn SubagentHandle>> {
@@ -3349,7 +3354,7 @@ impl ThreadEnvironment for NativeThreadEnvironment {
fn create_terminal(
&self,
command: String,
- extra_env: Vec<acp::EnvVariable>,
+ extra_env: Vec<acp_v1::EnvVariable>,
cwd: Option<PathBuf>,
output_byte_limit: Option<u64>,
sandbox_wrap: Option<acp_thread::SandboxWrap>,
@@ -3398,9 +3403,9 @@ impl ThreadEnvironment for NativeThreadEnvironment {
let temp_dir = temp_dir.canonicalize().unwrap_or(temp_dir);
let temp_dir_string = temp_dir.to_string_lossy().into_owned();
extra_env.extend([
- acp::EnvVariable::new("TMPDIR", &temp_dir_string),
- acp::EnvVariable::new("TMP", &temp_dir_string),
- acp::EnvVariable::new("TEMP", &temp_dir_string),
+ acp_v1::EnvVariable::new("TMPDIR", &temp_dir_string),
+ acp_v1::EnvVariable::new("TMP", &temp_dir_string),
+ acp_v1::EnvVariable::new("TEMP", &temp_dir_string),
]);
// The command's `$TMPDIR` must live inside the sandbox's
// writable scope. The per-thread temp directory is owned
@@ -3461,7 +3466,7 @@ impl ThreadEnvironment for NativeThreadEnvironment {
fn resume_subagent(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut App,
) -> Result<Rc<dyn SubagentHandle>> {
self.resume_subagent_thread(session_id, cx)
@@ -3503,7 +3508,7 @@ impl ThreadEnvironment for NativeThreadEnvironment {
}
pub struct NativeSubagentHandle {
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
parent_thread: WeakEntity<Thread>,
subagent_thread: Entity<Thread>,
acp_thread: Entity<acp_thread::AcpThread>,
@@ -3511,7 +3516,7 @@ pub struct NativeSubagentHandle {
impl NativeSubagentHandle {
fn new(
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
subagent_thread: Entity<Thread>,
acp_thread: Entity<acp_thread::AcpThread>,
parent_thread_entity: Entity<Thread>,
@@ -3526,7 +3531,7 @@ impl NativeSubagentHandle {
}
impl SubagentHandle for NativeSubagentHandle {
- fn id(&self) -> acp::SessionId {
+ fn id(&self) -> acp_v1::SessionId {
self.session_id.clone()
}
@@ -3589,15 +3594,15 @@ impl SubagentHandle for NativeSubagentHandle {
};
let discard_partial_output = matches!(
&response,
- Ok(Some(response)) if response.stop_reason == acp::StopReason::Cancelled
- || response.stop_reason == acp::StopReason::Refusal
+ Ok(Some(response)) if response.stop_reason == acp_v1::StopReason::Cancelled
+ || response.stop_reason == acp_v1::StopReason::Refusal
);
let result = match response {
Ok(Some(response)) => match response.stop_reason {
- acp::StopReason::Cancelled => Err(anyhow!("User canceled")),
- acp::StopReason::MaxTokens => Err(anyhow!("The agent reached the maximum number of tokens.")),
- acp::StopReason::MaxTurnRequests => Err(anyhow!("The agent reached the maximum number of allowed requests between user turns. Try prompting again.")),
- acp::StopReason::Refusal => Err(anyhow!("The agent refused to process that prompt. Try again.")),
+ acp_v1::StopReason::Cancelled => Err(anyhow!("User canceled")),
+ acp_v1::StopReason::MaxTokens => Err(anyhow!("The agent reached the maximum number of tokens.")),
+ acp_v1::StopReason::MaxTurnRequests => Err(anyhow!("The agent reached the maximum number of allowed requests between user turns. Try prompting again.")),
+ acp_v1::StopReason::Refusal => Err(anyhow!("The agent refused to process that prompt. Try again.")),
_ => thread.read_with(cx, |thread, _cx| {
thread
.last_message()
@@ -3651,16 +3656,16 @@ pub struct AcpTerminalHandle {
}
impl TerminalHandle for AcpTerminalHandle {
- fn id(&self, cx: &AsyncApp) -> Result<acp::TerminalId> {
+ fn id(&self, cx: &AsyncApp) -> Result<acp_v1::TerminalId> {
Ok(self.terminal.read_with(cx, |term, _cx| term.id().clone()))
}
- fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp::TerminalExitStatus>>> {
+ fn wait_for_exit(&self, cx: &AsyncApp) -> Result<Shared<Task<acp_v1::TerminalExitStatus>>> {
self.terminal
.read_with(cx, |term, _cx| term.wait_for_exit())
}
- fn current_output(&self, cx: &AsyncApp) -> Result<acp::TerminalOutputResponse> {
+ fn current_output(&self, cx: &AsyncApp) -> Result<acp_v1::TerminalOutputResponse> {
Ok(self
.terminal
.read_with(cx, |term, cx| term.current_output(cx)))
@@ -4075,8 +4080,8 @@ mod internal_tests {
authorization
.response
.send(acp_thread::SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOptionKind::AllowOnce,
))
.expect("authorization response should send");
@@ -4086,7 +4091,7 @@ mod internal_tests {
.iter()
.flatten()
.find_map(|content| match content {
- acp::ToolCallContent::Terminal(terminal) => Some(terminal.terminal_id.clone()),
+ acp_v1::ToolCallContent::Terminal(terminal) => Some(terminal.terminal_id.clone()),
_ => None,
})
.expect("terminal tool should announce its real terminal");
@@ -4169,7 +4174,7 @@ mod internal_tests {
fn native_thread_for_session(
agent: &Entity<NativeAgent>,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
) -> Entity<Thread> {
agent.read_with(cx, |agent, _cx| {
@@ -4250,7 +4255,7 @@ mod internal_tests {
thread.set_model(model.clone(), cx);
thread.push_acp_user_block(
old_message_id,
- [acp::ContentBlock::from("old user")],
+ [acp_v1::ContentBlock::from("old user")],
path_style,
cx,
);
@@ -4264,7 +4269,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
compact_message_id,
- acp::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),
+ acp_v1::PromptRequest::new(session_id.clone(), vec!["/compact".into()]),
cx,
)
});
@@ -4406,7 +4411,7 @@ mod internal_tests {
items: vec![json!({"type": "compaction", "encrypted_content": "opaque state"})],
},
)));
- let restored_session_id = acp::SessionId::new("provider-native-compaction");
+ let restored_session_id = acp_v1::SessionId::new("provider-native-compaction");
let database = cx
.update(|cx| ThreadsDatabase::connect(cx))
.await
@@ -4471,7 +4476,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
- acp::PromptRequest::new(session_id.clone(), vec!["old user".into()]),
+ acp_v1::PromptRequest::new(session_id.clone(), vec!["old user".into()]),
cx,
)
});
@@ -4500,7 +4505,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
- acp::PromptRequest::new(session_id, vec!["new user".into()]),
+ acp_v1::PromptRequest::new(session_id, vec!["new user".into()]),
cx,
)
});
@@ -4623,7 +4628,7 @@ mod internal_tests {
thread.set_model(model.clone(), cx);
thread.push_acp_user_block(
ClientUserMessageId::new(),
- [acp::ContentBlock::from("old user")],
+ [acp_v1::ContentBlock::from("old user")],
path_style,
cx,
);
@@ -4674,7 +4679,7 @@ mod internal_tests {
.expect("canceled compaction events should be bridged");
assert_eq!(
response.stop_reason,
- acp::StopReason::Cancelled,
+ acp_v1::StopReason::Cancelled,
"{scenario}"
);
@@ -4743,7 +4748,7 @@ mod internal_tests {
acp_thread::AgentSessionClientUserMessageIds::prompt(
connection.as_ref(),
ClientUserMessageId::new(),
- acp::PromptRequest::new(session_id.clone(), vec!["use a tool".into()]),
+ acp_v1::PromptRequest::new(session_id.clone(), vec!["use a tool".into()]),
cx,
)
});
@@ -4867,14 +4872,16 @@ mod internal_tests {
thread.update(cx, |thread, cx| {
thread.push_acp_user_block(
ClientUserMessageId::new(),
- [acp::ContentBlock::from("hello from the user")],
+ [acp_v1::ContentBlock::from("hello from the user")],
path_style,
cx,
);
});
acp_thread.update(cx, |acp_thread, cx| {
- acp_thread
- .set_draft_prompt(Some(vec![acp::ContentBlock::from("draft in progress")]), cx);
+ acp_thread.set_draft_prompt(
+ Some(vec![acp_v1::ContentBlock::from("draft in progress")]),
+ cx,
+ );
});
});
cx.run_until_parked();
@@ -4909,7 +4916,7 @@ mod internal_tests {
);
assert_eq!(
restored.draft_prompt,
- Some(vec![acp::ContentBlock::from("draft in progress")]),
+ Some(vec![acp_v1::ContentBlock::from("draft in progress")]),
"the current draft prompt should be captured by the quit flush"
);
assert!(
@@ -4943,17 +4950,17 @@ mod internal_tests {
#[test]
fn test_qualified_compact_commands_are_not_native_compact() {
- let unqualified_blocks = [acp::ContentBlock::from("/compact")];
+ let unqualified_blocks = [acp_v1::ContentBlock::from("/compact")];
let unqualified = Command::parse(&unqualified_blocks).unwrap();
assert!(unqualified.is_unqualified("compact"));
- let mcp_blocks = [acp::ContentBlock::from("/server.compact")];
+ let mcp_blocks = [acp_v1::ContentBlock::from("/server.compact")];
let mcp_qualified = Command::parse(&mcp_blocks).unwrap();
assert_eq!(mcp_qualified.prompt_name, "compact");
assert_eq!(mcp_qualified.explicit_server_id, Some("server"));
assert!(!mcp_qualified.is_unqualified("compact"));
- let skill_blocks = [acp::ContentBlock::from("/:compact")];
+ let skill_blocks = [acp_v1::ContentBlock::from("/:compact")];
let skill_qualified = Command::parse(&skill_blocks).unwrap();
assert_eq!(skill_qualified.prompt_name, "compact");
assert_eq!(skill_qualified.skill_scope, Some(""));
@@ -7024,7 +7031,7 @@ mod internal_tests {
Entity<NativeAgent>,
Rc<NativeAgentConnection>,
Entity<Project>,
- acp::SessionId,
+ acp_v1::SessionId,
Arc<FakeLanguageModelProvider>,
) {
let fs = FakeFs::new(cx.executor());
@@ -7256,7 +7263,7 @@ mod internal_tests {
thread.send(
vec![
"What does ".into(),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
"b.md",
MentionUri::File {
abs_path: path!("/a/b.md").into(),
@@ -7320,9 +7327,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::ContentBlock::Text(acp::TextContent::new("Check out ")),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new("b.md", uri.to_string())),
- acp::ContentBlock::Text(acp::TextContent::new(" please")),
+ 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_thread.update(cx, |thread, cx| {
thread.set_draft_prompt(Some(draft_blocks.clone()), cx);
@@ -7447,7 +7454,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::ContentBlock::Text(acp::TextContent::new(
+ let draft_blocks = vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"unsaved draft",
))];
acp_thread.update(cx, |thread, cx| {
@@ -7609,7 +7616,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::ContentBlock::Text(acp::TextContent::new(text))]);
+ .map(|text| vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(text))]);
let (first_gate_tx, first_gate_rx) = oneshot::channel();
database.set_write_gate(first_gate_rx);
@@ -7933,7 +7940,7 @@ mod internal_tests {
fn thread_entries(
thread_store: &Entity<ThreadStore>,
cx: &mut TestAppContext,
- ) -> Vec<(acp::SessionId, String)> {
+ ) -> Vec<(acp_v1::SessionId, String)> {
thread_store.read_with(cx, |store, _| {
store
.entries()
@@ -7998,7 +8005,7 @@ mod internal_tests {
agent: &Entity<NativeAgent>,
acp_thread: &Entity<AcpThread>,
thread: &Entity<Thread>,
- draft: Vec<acp::ContentBlock>,
+ draft: Vec<acp_v1::ContentBlock>,
cx: &mut TestAppContext,
) {
acp_thread.update(cx, |acp_thread, cx| {
@@ -8012,7 +8019,7 @@ mod internal_tests {
fn mcp_message_content_to_acp_content_block(
content: context_server::types::MessageContent,
-) -> acp::ContentBlock {
+) -> acp_v1::ContentBlock {
match content {
context_server::types::MessageContent::Text {
text,
@@ -8022,22 +8029,22 @@ fn mcp_message_content_to_acp_content_block(
data,
mime_type,
annotations: _,
- } => acp::ContentBlock::Image(acp::ImageContent::new(data, mime_type)),
+ } => acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(data, mime_type)),
context_server::types::MessageContent::Audio {
data,
mime_type,
annotations: _,
- } => acp::ContentBlock::Audio(acp::AudioContent::new(data, mime_type)),
+ } => acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new(data, mime_type)),
context_server::types::MessageContent::Resource {
resource,
annotations: _,
} => {
let mut link =
- acp::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
+ acp_v1::ResourceLink::new(resource.uri.to_string(), resource.uri.to_string());
if let Some(mime_type) = resource.mime_type {
link = link.mime_type(mime_type);
}
- acp::ContentBlock::ResourceLink(link)
+ acp_v1::ContentBlock::ResourceLink(link)
}
}
}
diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs
index 973bf590d0a..05b7dbf454c 100644
--- a/crates/agent_ui/src/conversation_view.rs
+++ b/crates/agent_ui/src/conversation_view.rs
@@ -8,7 +8,7 @@ use acp_thread::{
use acp_thread::{AgentConnection, Plan};
use action_log::{ActionLog, ActionLogTelemetry, DiffStats};
use agent::{NativeAgentServer, NoModelConfiguredError, ThreadStore};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v1 as acp_v1;
#[cfg(test)]
use agent_servers::AgentServerDelegate;
use agent_servers::{AgentServer, GEMINI_TERMINAL_AUTH_METHOD_ID};
@@ -168,8 +168,8 @@ impl From<anyhow::Error> for ThreadError {
Self::MaxOutputTokens
} else if error.is::<NoModelConfiguredError>() {
Self::NoModelSelected
- } else if let Some(acp_error) = error.downcast_ref::<acp::Error>()
- && acp_error.code == acp::ErrorCode::AuthRequired
+ } else if let Some(acp_error) = error.downcast_ref::<acp_v1::Error>()
+ && acp_error.code == acp_v1::ErrorCode::AuthRequired
{
Self::AuthenticationRequired(acp_error.message.clone().into())
} else if let Some(lm_error) = error.downcast_ref::<LanguageModelCompletionError>() {
@@ -237,7 +237,7 @@ impl From<anyhow::Error> for ThreadError {
// Extract ACP error code if available
let acp_error_code = error
- .downcast_ref::<acp::Error>()
+ .downcast_ref::<acp_v1::Error>()
.map(|acp_error| SharedString::from(acp_error.code.to_string()));
Self::Other {
@@ -284,9 +284,9 @@ impl ProfileProvider for Entity<agent::Thread> {
#[derive(Default)]
pub(crate) struct Conversation {
- threads: HashMap<acp::SessionId, Entity<AcpThread>>,
- permission_requests: IndexMap<acp::SessionId, Vec<acp::ToolCallId>>,
- elicitation_requests: IndexMap<acp::SessionId, Vec<ElicitationEntryId>>,
+ threads: HashMap<acp_v1::SessionId, Entity<AcpThread>>,
+ permission_requests: IndexMap<acp_v1::SessionId, Vec<acp_v1::ToolCallId>>,
+ elicitation_requests: IndexMap<acp_v1::SessionId, Vec<ElicitationEntryId>>,
subscriptions: Vec<Subscription>,
updated_at: Option<Instant>,
}
@@ -364,8 +364,8 @@ impl Conversation {
fn add_permission_request(
&mut self,
- session_id: &acp::SessionId,
- tool_call_id: &acp::ToolCallId,
+ session_id: &acp_v1::SessionId,
+ tool_call_id: &acp_v1::ToolCallId,
) {
let requests = self
.permission_requests
@@ -378,8 +378,8 @@ impl Conversation {
pub fn permission_options_for_tool_call<'a>(
&'a self,
- session_id: &acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: &acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
cx: &'a App,
) -> Option<&'a PermissionOptions> {
let thread = self.threads.get(session_id)?;
@@ -392,9 +392,9 @@ impl Conversation {
pub fn pending_tool_call<'a>(
&'a self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &'a App,
- ) -> Option<(acp::SessionId, acp::ToolCallId, &'a PermissionOptions)> {
+ ) -> Option<(acp_v1::SessionId, acp_v1::ToolCallId, &'a PermissionOptions)> {
let thread = self.threads.get(session_id)?;
let is_subagent = thread.read(cx).parent_session_id().is_some();
let (result_session_id, thread, tool_id) = if is_subagent {
@@ -414,7 +414,7 @@ impl Conversation {
Some((result_session_id, tool_id.clone(), options))
}
- pub fn subagents_awaiting_permission(&self, cx: &App) -> Vec<(acp::SessionId, usize)> {
+ pub fn subagents_awaiting_permission(&self, cx: &App) -> Vec<(acp_v1::SessionId, usize)> {
self.permission_requests
.iter()
.filter_map(|(session_id, tool_call_ids)| {
@@ -433,9 +433,9 @@ impl Conversation {
/// request for non-subagent sessions.
pub fn pending_tool_call_for_session(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
- ) -> Option<acp::ToolCallId> {
+ ) -> Option<acp_v1::ToolCallId> {
let thread = self.threads.get(session_id)?;
let tool_call_id = self.permission_requests.get(session_id)?.iter().next()?;
let (_, tool_call) = thread.read(cx).tool_call(tool_call_id)?;
@@ -448,7 +448,7 @@ impl Conversation {
Some(tool_call_id.clone())
}
- pub fn pending_tool_call_count_for_session(&self, session_id: &acp::SessionId) -> usize {
+ pub fn pending_tool_call_count_for_session(&self, session_id: &acp_v1::SessionId) -> usize {
self.permission_requests
.get(session_id)
.map(|tool_call_ids| tool_call_ids.len())
@@ -457,9 +457,9 @@ impl Conversation {
pub fn respond_to_elicitation(
&mut self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
elicitation_id: ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
cx: &mut Context<Self>,
) -> Option<()> {
let thread = self.threads.get(&session_id)?.clone();
@@ -471,8 +471,8 @@ impl Conversation {
pub fn authorize_pending_tool_call(
&mut self,
- session_id: &acp::SessionId,
- kind: acp::PermissionOptionKind,
+ session_id: &acp_v1::SessionId,
+ kind: acp_v1::PermissionOptionKind,
cx: &mut Context<Self>,
) -> Option<()> {
let (authorize_session_id, tool_call_id, options) =
@@ -489,8 +489,8 @@ impl Conversation {
pub fn authorize_with_granularity(
&mut self,
- session_id: acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
selection: Option<&thread_view::PermissionSelection>,
is_allow: bool,
cx: &mut Context<Self>,
@@ -504,8 +504,8 @@ impl Conversation {
pub fn authorize_tool_call(
&mut self,
- session_id: acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
outcome: SelectedPermissionOutcome,
cx: &mut Context<Self>,
) {
@@ -543,9 +543,9 @@ impl EventEmitter<RootThreadUpdated> for ConversationView {}
fn permission_option_for_action(
options: &PermissionOptions,
- kind: acp::PermissionOptionKind,
-) -> Option<&acp::PermissionOption> {
- if kind == acp::PermissionOptionKind::AllowAlways
+ kind: acp_v1::PermissionOptionKind,
+) -> Option<&acp_v1::PermissionOption> {
+ if kind == acp_v1::PermissionOptionKind::AllowAlways
&& let PermissionOptions::Flat(options) = options
&& let Some(option) = options.iter().find(|option| {
option.option_id.0.as_ref() == acp_thread::SandboxPermission::AllowAlways.as_id()
@@ -571,9 +571,9 @@ fn resolve_outcome_from_selection(
PermissionOptions::DropdownWithPatterns { choices, .. } => choices.as_slice(),
PermissionOptions::Flat(_) => {
let kind = if is_allow {
- acp::PermissionOptionKind::AllowOnce
+ acp_v1::PermissionOptionKind::AllowOnce
} else {
- acp::PermissionOptionKind::RejectOnce
+ acp_v1::PermissionOptionKind::RejectOnce
};
let option = options.first_option_of_kind(kind)?;
return Some(SelectedPermissionOutcome::new(
@@ -642,7 +642,7 @@ pub struct ConversationView {
project: Entity<Project>,
thread_store: Option<Entity<ThreadStore>>,
pub(crate) thread_id: ThreadId,
- pub(crate) root_session_id: Option<acp::SessionId>,
+ pub(crate) root_session_id: Option<acp_v1::SessionId>,
server_state: ServerState,
focus_handle: FocusHandle,
notifications: Vec<WindowHandle<AgentNotification>>,
@@ -683,7 +683,7 @@ impl ConversationView {
pub fn pending_tool_call<'a>(
&'a self,
cx: &'a App,
- ) -> Option<(acp::SessionId, acp::ToolCallId, &'a PermissionOptions)> {
+ ) -> Option<(acp_v1::SessionId, acp_v1::ToolCallId, &'a PermissionOptions)> {
let session_id = self.active_thread()?.read(cx).session_id.clone();
self.as_connected()?
.conversation
@@ -716,7 +716,7 @@ impl ConversationView {
.and_then(|id| self.thread_view(id))
}
- pub fn thread_view(&self, session_id: &acp::SessionId) -> Option<Entity<ThreadView>> {
+ pub fn thread_view(&self, session_id: &acp_v1::SessionId) -> Option<Entity<ThreadView>> {
let connected = self.as_connected()?;
connected.threads.get(session_id).cloned()
}
@@ -742,7 +742,7 @@ impl ConversationView {
pub fn navigate_to_thread(
&mut self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -783,8 +783,8 @@ enum ServerState {
// hashmap of threads, current becomes session_id
pub struct ConnectedServerState {
auth_state: AuthState,
- active_id: Option<acp::SessionId>,
- pub(crate) threads: HashMap<acp::SessionId, Entity<ThreadView>>,
+ active_id: Option<acp_v1::SessionId>,
+ pub(crate) threads: HashMap<acp_v1::SessionId, Entity<ThreadView>>,
connection: Rc<dyn AgentConnection>,
conversation: Entity<Conversation>,
_connection_entry_subscription: Subscription,
@@ -795,7 +795,7 @@ enum AuthState {
Ok,
Unauthenticated {
description: Option<Entity<Markdown>>,
- pending_auth_method: Option<acp::AuthMethodId>,
+ pending_auth_method: Option<acp_v1::AuthMethodId>,
},
}
@@ -819,7 +819,7 @@ impl ConnectedServerState {
.map_or(false, |view| view.read(cx).thread_error.is_some())
}
- pub fn navigate_to_thread(&mut self, session_id: acp::SessionId) {
+ pub fn navigate_to_thread(&mut self, session_id: acp_v1::SessionId) {
if self.threads.contains_key(&session_id) {
self.active_id = Some(session_id);
}
@@ -846,7 +846,7 @@ impl ConversationView {
agent: Rc<dyn AgentServer>,
connection_store: Entity<AgentConnectionStore>,
connection_key: Agent,
- resume_session_id: Option<acp::SessionId>,
+ resume_session_id: Option<acp_v1::SessionId>,
thread_id: Option<ThreadId>,
work_dirs: Option<PathList>,
title: Option<SharedString>,
@@ -1078,7 +1078,7 @@ impl ConversationView {
agent: Rc<dyn AgentServer>,
connection_store: Entity<AgentConnectionStore>,
connection_key: Agent,
- resume_session_id: Option<acp::SessionId>,
+ resume_session_id: Option<acp_v1::SessionId>,
work_dirs: Option<PathList>,
title: Option<SharedString>,
project: Entity<Project>,
@@ -1674,6 +1674,12 @@ impl ConversationView {
});
list_state.remeasure_items(*index..*index + 1);
active.update(cx, |active, cx| {
+ if active.editing_message == Some(*index)
+ && !active.can_edit_user_message(*index, cx)
+ {
+ active.editing_message = None;
+ cx.notify();
+ }
active.sync_elicitation_state_for_entry(*index, window, cx);
active.auto_expand_streaming_thought(cx);
active.sync_generating_indicator(cx);
@@ -1725,7 +1731,7 @@ impl ConversationView {
});
}
if is_subagent {
- if *stop_reason == acp::StopReason::EndTurn {
+ if *stop_reason == acp_v1::StopReason::EndTurn {
thread.update(cx, |thread, cx| {
thread.mark_as_subagent_output(cx);
});
@@ -1935,7 +1941,7 @@ impl ConversationView {
if !thread.is_draft_thread() {
return None;
}
- let snapshot: Vec<acp::ContentBlock> = thread
+ let snapshot: Vec<acp_v1::ContentBlock> = thread
.draft_prompt()
.map(|p| p.to_vec())
.unwrap_or_default();
@@ -1953,7 +1959,7 @@ impl ConversationView {
fn authenticate(
&mut self,
- method: acp::AuthMethodId,
+ method: acp_v1::AuthMethodId,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -2093,8 +2099,8 @@ impl ConversationView {
fn load_subagent_session(
&mut self,
- subagent_id: acp::SessionId,
- parent_session_id: acp::SessionId,
+ subagent_id: acp_v1::SessionId,
+ parent_session_id: acp_v1::SessionId,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -2153,7 +2159,7 @@ impl ConversationView {
login: task::SpawnInTerminal,
workspace: Entity<Workspace>,
project: Entity<Project>,
- method: acp::AuthMethodId,
+ method: acp_v1::AuthMethodId,
previous_attempt: bool,
window: &mut Window,
cx: &mut App,
@@ -2292,7 +2298,7 @@ impl ConversationView {
&self,
connection: &Rc<dyn AgentConnection>,
description: Option<&Entity<Markdown>>,
- pending_auth_method: Option<&acp::AuthMethodId>,
+ pending_auth_method: Option<&acp_v1::AuthMethodId>,
window: &mut Window,
cx: &Context<Self>,
) -> impl IntoElement {
@@ -2339,7 +2345,7 @@ impl ConversationView {
);
this.authenticate(
- acp::AuthMethodId::new(method_id.clone()),
+ acp_v1::AuthMethodId::new(method_id.clone()),
window,
cx,
)
@@ -2409,7 +2415,7 @@ impl ConversationView {
.map(|elicitation| {
let is_pending = matches!(elicitation.status, ElicitationStatus::Pending { .. });
let schema = match &elicitation.request.mode {
- acp::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
+ acp_v1::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
_ => None,
};
(elicitation.id.clone(), is_pending, schema)
@@ -2589,7 +2595,7 @@ impl ConversationView {
};
match mode {
- acp::ElicitationMode::Form(mode) => {
+ acp_v1::ElicitationMode::Form(mode) => {
let Some(state) = self
.request_elicitation_form_states
.get_mut(&elicitation_id)
@@ -2622,9 +2628,9 @@ impl ConversationView {
Ok(content) => {
this.respond_to_request_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(content),
+ acp_v1::CreateElicitationResponse::new(
+ acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new().content(content),
),
),
cx,
@@ -2643,11 +2649,11 @@ impl ConversationView {
})
.detach();
}
- acp::ElicitationMode::Url(_) => {
+ acp_v1::ElicitationMode::Url(_) => {
self.respond_to_request_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
@@ -2664,7 +2670,7 @@ impl ConversationView {
) {
self.respond_to_request_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
}
@@ -2677,7 +2683,7 @@ impl ConversationView {
) {
self.respond_to_request_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Cancel),
cx,
);
}
@@ -2699,7 +2705,7 @@ impl ConversationView {
fn respond_to_request_elicitation(
&mut self,
elicitation_id: ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
cx: &mut Context<Self>,
) {
self.request_elicitation_form_states.remove(&elicitation_id);
@@ -3352,7 +3358,7 @@ fn loading_contents_spinner(size: IconSize) -> AnyElement {
fn native_available_skills(
native_connection: &agent::NativeAgentConnection,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
cx: &App,
) -> Vec<AvailableSkill> {
native_connection
@@ -3405,7 +3411,7 @@ impl ConversationView {
impl ConversationView {
/// Expands a tool call so its content is visible.
/// This is primarily useful for visual testing.
- pub fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId, cx: &mut Context<Self>) {
+ pub fn expand_tool_call(&mut self, tool_call_id: acp_v1::ToolCallId, cx: &mut Context<Self>) {
if let Some(active) = self.active_thread() {
active.update(cx, |active, cx| {
active.entry_view_state.update(cx, |state, _cx| {
@@ -3701,7 +3707,7 @@ impl AgentCodeSpanResolver {
}
fn plan_label_markdown_style(
- status: &acp::PlanEntryStatus,
+ status: &acp_v1::PlanEntryStatus,
window: &Window,
cx: &App,
) -> MarkdownStyle {
@@ -3710,7 +3716,7 @@ fn plan_label_markdown_style(
MarkdownStyle {
base_text_style: TextStyle {
color: cx.theme().colors().text_muted,
- strikethrough: if matches!(status, acp::PlanEntryStatus::Completed) {
+ strikethrough: if matches!(status, acp_v1::PlanEntryStatus::Completed) {
Some(gpui::StrikethroughStyle {
thickness: px(1.),
color: Some(cx.theme().colors().text_muted.opacity(0.8)),
@@ -3894,7 +3900,7 @@ pub(crate) mod tests {
cx.run_until_parked();
assert!(matches!(
response.lock().as_ref(),
- Some(acp::ElicitationAction::Cancel)
+ Some(acp_v1::ElicitationAction::Cancel)
));
}
@@ -3949,7 +3955,7 @@ pub(crate) mod tests {
cx.run_until_parked();
assert!(matches!(
response.lock().as_ref(),
- Some(acp::ElicitationAction::Cancel)
+ Some(acp_v1::ElicitationAction::Cancel)
));
}
@@ -3969,8 +3975,8 @@ pub(crate) mod tests {
response: response.clone(),
};
let (conversation_view, cx) = setup_conversation_view(server, cx).await;
- let first_request_id = acp::RequestId::Number(1);
- let second_request_id = acp::RequestId::Number(2);
+ let first_request_id = acp_v1::RequestId::Number(1);
+ let second_request_id = acp_v1::RequestId::Number(2);
let first_elicitation_id = store.read_with(cx, |store, _cx| {
assert_eq!(
store.elicitations().len(),
@@ -3981,7 +3987,8 @@ pub(crate) mod tests {
.elicitations()
.iter()
.find_map(|elicitation| {
- let acp::ElicitationScope::Request(scope) = elicitation.request.scope() else {
+ let acp_v1::ElicitationScope::Request(scope) = elicitation.request.scope()
+ else {
return None;
};
(&scope.request_id == &first_request_id).then(|| elicitation.id.clone())
@@ -3992,8 +3999,8 @@ pub(crate) mod tests {
store.update(cx, |store, cx| {
store.respond_to_elicitation(
&first_elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
@@ -4002,7 +4009,7 @@ pub(crate) mod tests {
assert!(matches!(
response.lock().as_ref(),
- Some(acp::ElicitationAction::Accept(_))
+ Some(acp_v1::ElicitationAction::Accept(_))
));
conversation_view.read_with(cx, |view, _cx| {
let connected = view
@@ -4020,7 +4027,7 @@ pub(crate) mod tests {
store.elicitations()
);
};
- let acp::ElicitationScope::Request(scope) = remaining.request.scope() else {
+ let acp_v1::ElicitationScope::Request(scope) = remaining.request.scope() else {
panic!("expected request-scoped elicitation");
};
assert_eq!(scope.request_id, second_request_id);
@@ -4217,7 +4224,7 @@ pub(crate) mod tests {
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -4232,12 +4239,12 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"first response".into(),
)),
cx,
);
- connection.end_turn(session_id, acp::StopReason::EndTurn);
+ connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
});
cx.run_until_parked();
@@ -4262,7 +4269,7 @@ pub(crate) mod tests {
let id = active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -4313,7 +4320,7 @@ pub(crate) mod tests {
// 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::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued".to_string(),
))],
vec![],
@@ -4351,7 +4358,7 @@ pub(crate) mod tests {
// When this generation completes, the queued message should be picked
// up automatically (regression test for the "frozen queue" bug).
- connection.end_turn(session_id, acp::StopReason::EndTurn);
+ connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
cx.run_until_parked();
let queue_len = active_thread(&conversation_view, cx)
@@ -4398,12 +4405,13 @@ pub(crate) mod tests {
add_to_workspace_with_size(conversation_view.clone(), true, cx);
let thread_view = active_thread(&conversation_view, cx);
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
- let notice = acp::Notice::new(acp::NoticeSeverity::Error, "Optional integration failed")
- .description("**Plain text**, not Markdown. Work continues.");
+ let notice =
+ acp_v1::Notice::new(acp_v1::NoticeSeverity::Error, "Optional integration failed")
+ .description("**Plain text**, not Markdown. Work continues.");
thread.update(cx, |thread, cx| {
for _ in 0..2 {
thread
- .handle_session_update(acp::SessionUpdate::Notice(notice.clone()), cx)
+ .handle_session_update(acp_v1::SessionUpdate::Notice(notice.clone()), cx)
.expect("notice should be accepted");
}
});
@@ -4456,7 +4464,7 @@ pub(crate) mod tests {
let root_thread =
active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone());
let root_session_id = root_thread.read_with(cx, |thread, _| thread.session_id().clone());
- let other_session_id = acp::SessionId::new("other-session");
+ let other_session_id = acp_v1::SessionId::new("other-session");
conversation_view.update_in(cx, |view, window, cx| {
view.load_subagent_session(
other_session_id.clone(),
@@ -4487,8 +4495,8 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
root_session_id.clone(),
- acp::SessionUpdate::Notice(acp::Notice::new(
- acp::NoticeSeverity::Error,
+ acp_v1::SessionUpdate::Notice(acp_v1::Notice::new(
+ acp_v1::NoticeSeverity::Error,
"Optional integration failed",
)),
cx,
@@ -4550,9 +4558,9 @@ pub(crate) mod tests {
for index in 0..8 {
thread
.handle_session_update(
- acp::SessionUpdate::Notice(
- acp::Notice::new(
- acp::NoticeSeverity::Other("_advisory".into()),
+ acp_v1::SessionUpdate::Notice(
+ acp_v1::Notice::new(
+ acp_v1::NoticeSeverity::Other("_advisory".into()),
"The optional documentation integration is unavailable",
)
.description(if index == 0 {
@@ -4600,7 +4608,7 @@ pub(crate) mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"Work is continuing.".into(),
)),
cx,
@@ -4706,7 +4714,7 @@ pub(crate) mod tests {
Rc::new(StubAgentServer::new(ResumeOnlyAgentConnection)),
connection_store,
Agent::Custom { id: "Test".into() },
- Some(acp::SessionId::new("resume-session")),
+ Some(acp_v1::SessionId::new("resume-session")),
None,
None,
None,
@@ -4752,7 +4760,7 @@ pub(crate) mod tests {
self,
project,
"RestoredAvailableCommandsConnection",
- acp::SessionId::new("new-session"),
+ acp_v1::SessionId::new("new-session"),
cx,
);
Task::ready(Ok(thread))
@@ -4764,7 +4772,7 @@ pub(crate) mod tests {
fn load_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
_work_dirs: PathList,
_title: Option<SharedString>,
@@ -4781,10 +4789,10 @@ pub(crate) mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::AvailableCommandsUpdate(
- acp::AvailableCommandsUpdate::new(vec![acp::AvailableCommand::new(
- "help", "Get help",
- )]),
+ acp_v1::SessionUpdate::AvailableCommandsUpdate(
+ acp_v1::AvailableCommandsUpdate::new(vec![
+ acp_v1::AvailableCommand::new("help", "Get help"),
+ ]),
),
cx,
)
@@ -4794,13 +4802,13 @@ pub(crate) mod tests {
Task::ready(Ok(thread))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -4808,13 +4816,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -4841,7 +4849,7 @@ pub(crate) mod tests {
Rc::new(StubAgentServer::new(RestoredAvailableCommandsConnection)),
connection_store,
Agent::Custom { id: "Test".into() },
- Some(acp::SessionId::new("restored-session")),
+ Some(acp_v1::SessionId::new("restored-session")),
None,
None,
None,
@@ -4922,7 +4930,7 @@ pub(crate) mod tests {
Rc::new(StubAgentServer::new(connection)),
connection_store,
Agent::Custom { id: "Test".into() },
- Some(acp::SessionId::new("session-1")),
+ Some(acp_v1::SessionId::new("session-1")),
None,
Some(PathList::new(&[PathBuf::from("/project/subdir")])),
None,
@@ -5028,7 +5036,7 @@ pub(crate) mod tests {
cx.update(|_window, cx| cx.new(|cx| AgentConnectionStore::new(project.clone(), cx)));
// Simulate a previous run that persisted metadata for this session.
- let resume_session_id = acp::SessionId::new("persistent-session");
+ let resume_session_id = acp_v1::SessionId::new("persistent-session");
let stored_title: SharedString = "Persistent chat".into();
cx.update(|_window, cx| {
ThreadMetadataStore::global(cx).update(cx, |store, cx| {
@@ -5172,7 +5180,7 @@ pub(crate) mod tests {
// then on success triggers reset() -> new_session() which now succeeds.
conversation_view.update_in(cx, |view, window, cx| {
view.authenticate(
- acp::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
+ acp_v1::AuthMethodId::new(AuthGatedAgentConnection::AUTH_METHOD_ID),
window,
cx,
);
@@ -5242,21 +5250,21 @@ pub(crate) mod tests {
async fn test_notification_for_tool_authorization(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("1");
- let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Label")
- .kind(acp::ToolKind::Edit)
+ let tool_call_id = acp_v1::ToolCallId::new("1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Label")
+ .kind(acp_v1::ToolKind::Edit)
.content(vec!["hi".into()]);
let connection =
StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
tool_call_id,
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
"1",
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -5952,8 +5960,8 @@ pub(crate) mod tests {
setup_conversation_view_with_initial_content_opt(agent, None, cx).await
}
- fn png_image() -> acp::ContentBlock {
- acp::ContentBlock::Image(acp::ImageContent::new(
+ fn png_image() -> acp_v1::ContentBlock {
+ acp_v1::ContentBlock::Image(acp_v1::ImageContent::new(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",
"image/png",
))
@@ -6003,10 +6011,10 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::Plan(acp::Plan::new(vec![acp::PlanEntry::new(
+ acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new(
"Do the thing",
- acp::PlanEntryPriority::Medium,
- acp::PlanEntryStatus::InProgress,
+ acp_v1::PlanEntryPriority::Medium,
+ acp_v1::PlanEntryStatus::InProgress,
)])),
cx,
);
@@ -6026,10 +6034,10 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::Plan(acp::Plan::new(vec![acp::PlanEntry::new(
+ acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new(
"Do the thing",
- acp::PlanEntryPriority::Medium,
- acp::PlanEntryStatus::Completed,
+ acp_v1::PlanEntryPriority::Medium,
+ acp_v1::PlanEntryStatus::Completed,
)])),
cx,
);
@@ -6039,7 +6047,7 @@ pub(crate) mod tests {
assert_thread_list_item_count_matches_entries(view, cx);
});
- connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
+ connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn);
cx.run_until_parked();
active_thread(&conversation_view, cx).read_with(cx, |view, cx| {
assert_thread_list_item_count_matches_entries(view, cx);
@@ -6062,10 +6070,10 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::Plan(acp::Plan::new(vec![acp::PlanEntry::new(
+ acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new(
"Revise the thing",
- acp::PlanEntryPriority::High,
- acp::PlanEntryStatus::InProgress,
+ acp_v1::PlanEntryPriority::High,
+ acp_v1::PlanEntryStatus::InProgress,
)])),
cx,
);
@@ -6091,10 +6099,10 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::Plan(acp::Plan::new(vec![acp::PlanEntry::new(
+ acp_v1::SessionUpdate::Plan(acp_v1::Plan::new(vec![acp_v1::PlanEntry::new(
"Another task",
- acp::PlanEntryPriority::Medium,
- acp::PlanEntryStatus::Completed,
+ acp_v1::PlanEntryPriority::Medium,
+ acp_v1::PlanEntryStatus::Completed,
)])),
cx,
);
@@ -6115,7 +6123,7 @@ pub(crate) mod tests {
assert_thread_list_item_count_matches_entries(view, cx);
assert!(view.thread.read(cx).plan().is_empty());
});
- connection.end_turn(session_id, acp::StopReason::EndTurn);
+ connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
cx.run_until_parked();
}
@@ -6252,8 +6260,8 @@ pub(crate) mod tests {
impl StubAgentServer<StubAgentConnection> {
pub(crate) fn default_response() -> Self {
let conn = StubAgentConnection::new();
- conn.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Default response".into()),
+ conn.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Default response".into()),
)]);
Self::new(conn)
}
@@ -6371,7 +6379,7 @@ pub(crate) mod tests {
connection: Rc<dyn AgentConnection>,
project: Entity<Project>,
name: &'static str,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
cx: &mut App,
) -> Entity<AcpThread> {
let action_log = cx.new(|_| ActionLog::new(project.clone()));
@@ -6385,7 +6393,7 @@ pub(crate) mod tests {
action_log,
session_id,
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -6415,7 +6423,7 @@ pub(crate) mod tests {
_work_dirs: PathList,
cx: &mut App,
) -> Task<gpui::Result<Entity<AcpThread>>> {
- let session_id = acp::SessionId::new("new-session");
+ let session_id = acp_v1::SessionId::new("new-session");
let thread = build_test_thread(
self.clone(),
project,
@@ -6426,10 +6434,10 @@ pub(crate) mod tests {
thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -6451,13 +6459,13 @@ pub(crate) mod tests {
Task::ready(Ok(thread))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -6465,13 +6473,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -6480,7 +6488,7 @@ pub(crate) mod tests {
struct SessionCreationRequestElicitationServer {
store: Entity<ElicitationStore>,
- response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ response: Arc<Mutex<Option<acp_v1::ElicitationAction>>>,
}
impl AgentServer for SessionCreationRequestElicitationServer {
@@ -6512,7 +6520,7 @@ pub(crate) mod tests {
struct SessionCreationRequestElicitationConnection {
store: Entity<ElicitationStore>,
- response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ response: Arc<Mutex<Option<acp_v1::ElicitationAction>>>,
}
impl AgentConnection for SessionCreationRequestElicitationConnection {
@@ -6534,16 +6542,16 @@ pub(crate) mod tests {
self.clone(),
project,
"SessionCreationRequestElicitationConnection",
- acp::SessionId::new("session-creation-request-elicitation-session"),
+ acp_v1::SessionId::new("session-creation-request-elicitation-session"),
cx,
);
let first_response_task = self.store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -6555,10 +6563,12 @@ pub(crate) mod tests {
.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(2)),
- acp::ElicitationSchema::new().string("account", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(
+ acp_v1::RequestId::Number(2),
+ ),
+ acp_v1::ElicitationSchema::new().string("account", true),
),
"Provide an account",
),
@@ -6580,13 +6590,13 @@ pub(crate) mod tests {
Some(self.store.clone())
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -6594,13 +6604,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -6608,7 +6618,7 @@ pub(crate) mod tests {
}
struct ReleaseRequestElicitationServer {
- response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ response: Arc<Mutex<Option<acp_v1::ElicitationAction>>>,
}
impl AgentServer for ReleaseRequestElicitationServer {
@@ -6640,7 +6650,7 @@ pub(crate) mod tests {
struct ReleaseRequestElicitationConnection {
store: Entity<ElicitationStore>,
- response: Arc<Mutex<Option<acp::ElicitationAction>>>,
+ response: Arc<Mutex<Option<acp_v1::ElicitationAction>>>,
}
impl AgentConnection for ReleaseRequestElicitationConnection {
@@ -6662,16 +6672,16 @@ pub(crate) mod tests {
self.clone(),
project,
"ReleaseRequestElicitationConnection",
- acp::SessionId::new("release-request-elicitation-session"),
+ acp_v1::SessionId::new("release-request-elicitation-session"),
cx,
);
let response_task = self.store.update(cx, |store, cx| {
store
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationRequestScope::new(acp::RequestId::Number(1)),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationRequestScope::new(acp_v1::RequestId::Number(1)),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -6692,13 +6702,13 @@ pub(crate) mod tests {
Some(self.store.clone())
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -6706,13 +6716,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -6741,7 +6751,7 @@ pub(crate) mod tests {
self,
project,
"ResumeOnlyAgentConnection",
- acp::SessionId::new("new-session"),
+ acp_v1::SessionId::new("new-session"),
cx,
);
Task::ready(Ok(thread))
@@ -6753,7 +6763,7 @@ pub(crate) mod tests {
fn resume_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
_work_dirs: PathList,
_title: Option<SharedString>,
@@ -6764,13 +6774,13 @@ pub(crate) mod tests {
Task::ready(Ok(thread))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -6778,13 +6788,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -6797,7 +6807,7 @@ pub(crate) mod tests {
#[derive(Clone)]
struct AuthGatedAgentConnection {
authenticated: Arc<Mutex<bool>>,
- auth_method: acp::AuthMethod,
+ auth_method: acp_v1::AuthMethod,
}
impl AuthGatedAgentConnection {
@@ -6806,7 +6816,7 @@ pub(crate) mod tests {
fn new() -> Self {
Self {
authenticated: Arc::new(Mutex::new(false)),
- auth_method: acp::AuthMethod::Agent(acp::AuthMethodAgent::new(
+ auth_method: acp_v1::AuthMethod::Agent(acp_v1::AuthMethodAgent::new(
Self::AUTH_METHOD_ID,
"Test Login",
)),
@@ -6835,7 +6845,7 @@ pub(crate) mod tests {
.into()));
}
- let session_id = acp::SessionId::new("auth-gated-session");
+ let session_id = acp_v1::SessionId::new("auth-gated-session");
let action_log = cx.new(|_| ActionLog::new(project.clone()));
Task::ready(Ok(cx.new(|cx| {
AcpThread::new(
@@ -6847,7 +6857,7 @@ pub(crate) mod tests {
action_log,
session_id,
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -6857,13 +6867,13 @@ pub(crate) mod tests {
})))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
std::slice::from_ref(&self.auth_method)
}
fn authenticate(
&self,
- method_id: acp::AuthMethodId,
+ method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
if &method_id == self.auth_method.id() {
@@ -6885,13 +6895,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
unimplemented!()
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {
unimplemented!()
}
@@ -6928,9 +6938,9 @@ pub(crate) mod tests {
self,
project,
action_log,
- acp::SessionId::new("test"),
+ acp_v1::SessionId::new("test"),
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -6940,13 +6950,13 @@ pub(crate) mod tests {
})))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
unimplemented!()
@@ -6954,13 +6964,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::Refusal)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::Refusal)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {
unimplemented!()
}
@@ -7007,9 +7017,9 @@ pub(crate) mod tests {
self.clone(),
project,
action_log,
- acp::SessionId::new("new-session"),
+ acp_v1::SessionId::new("new-session"),
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -7026,7 +7036,7 @@ pub(crate) mod tests {
fn load_session(
self: Rc<Self>,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
project: Entity<Project>,
work_dirs: PathList,
_title: Option<SharedString>,
@@ -7044,7 +7054,7 @@ pub(crate) mod tests {
action_log,
session_id,
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -7055,13 +7065,13 @@ pub(crate) mod tests {
Task::ready(Ok(thread))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -7069,13 +7079,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
@@ -7184,12 +7194,13 @@ pub(crate) mod tests {
.unwrap();
// First user message
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("tool1", "Edit file 1")
- .kind(acp::ToolKind::Edit)
- .status(acp::ToolCallStatus::Completed)
- .content(vec![acp::ToolCallContent::Diff(
- acp::Diff::new("/project/test1.txt", "new content 1").old_text("old content 1"),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("tool1", "Edit file 1")
+ .kind(acp_v1::ToolKind::Edit)
+ .status(acp_v1::ToolCallStatus::Completed)
+ .content(vec![acp_v1::ToolCallContent::Diff(
+ acp_v1::Diff::new("/project/test1.txt", "new content 1")
+ .old_text("old content 1"),
)]),
)]);
@@ -7221,12 +7232,13 @@ pub(crate) mod tests {
});
// Second user message
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("tool2", "Edit file 2")
- .kind(acp::ToolKind::Edit)
- .status(acp::ToolCallStatus::Completed)
- .content(vec![acp::ToolCallContent::Diff(
- acp::Diff::new("/project/test2.txt", "new content 2").old_text("old content 2"),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("tool2", "Edit file 2")
+ .kind(acp_v1::ToolKind::Edit)
+ .status(acp_v1::ToolCallStatus::Completed)
+ .content(vec![acp_v1::ToolCallContent::Diff(
+ acp_v1::Diff::new("/project/test2.txt", "new content 2")
+ .old_text("old content 2"),
)]),
)]);
@@ -7359,11 +7371,11 @@ pub(crate) mod tests {
// First turn: a subagent tool call. Subagent edits never appear as
// diffs in the parent thread's entries; they are only forwarded to the
// parent's action log through the linked-log mechanism.
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("spawn1", "Subagent task")
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("spawn1", "Subagent task")
.name("spawn_agent")
- .kind(acp::ToolKind::Other)
- .status(acp::ToolCallStatus::Completed),
+ .kind(acp_v1::ToolKind::Other)
+ .status(acp_v1::ToolCallStatus::Completed),
)]);
thread
@@ -7407,8 +7419,8 @@ pub(crate) mod tests {
});
// Second turn: a plain follow-up.
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response".into()),
)]);
thread
.update(cx, |thread, cx| thread.send_raw("Follow-up", cx))
@@ -7441,8 +7453,8 @@ pub(crate) mod tests {
editor.set_text("Edited follow-up", window, cx);
});
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("New response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("New response".into()),
)]);
active_thread(&conversation_view, cx).update_in(cx, |view, window, cx| {
view.regenerate(follow_up_ix, user_message_editor.clone(), window, cx);
@@ -7484,8 +7496,8 @@ pub(crate) mod tests {
let connection = StubAgentConnection::new();
// Each user prompt will result in a user message entry plus an agent message entry.
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response 1".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response 1".into()),
)]);
let (conversation_view, cx) =
@@ -7503,8 +7515,8 @@ pub(crate) mod tests {
.unwrap();
cx.run_until_parked();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response 2".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response 2".into()),
)]);
thread
@@ -7559,8 +7571,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new(
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(
"Yes, you can substitute banana for plantain in this recipe.".into(),
),
)]);
@@ -7579,8 +7591,8 @@ pub(crate) mod tests {
.unwrap();
cx.run_until_parked();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new(
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(
"Banana yogurt also works as a topping; whisk the banana smooth first.".into(),
),
)]);
@@ -7658,13 +7670,13 @@ pub(crate) mod tests {
let connection = StubAgentConnection::new();
connection.set_next_prompt_updates(vec![
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentThoughtChunk(acp_v1::ContentChunk::new(
"Hidden papaya reasoning.".into(),
)),
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new(
+ acp_v1::SessionUpdate::AgentThoughtChunk(acp_v1::ContentChunk::new(
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(
"A second hidden papaya.",
"thought://details",
)
@@ -7672,7 +7684,7 @@ pub(crate) mod tests {
),
)),
)),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"Final answer without that fruit.".into(),
)),
]);
@@ -7748,8 +7760,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
connection.set_next_prompt_updates(vec![
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("".into())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(png_image())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new("".into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(png_image())),
]);
let (_conversation_view, cx) =
setup_full_size_conversation_and_send(connection, "Show an image", cx).await;
@@ -7768,9 +7780,9 @@ pub(crate) mod tests {
init_test(cx);
let image = png_image();
- let resource = acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new(
+ let resource = acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(
"Resource needle follows the image.",
"memory://ordered",
)
@@ -7779,14 +7791,18 @@ pub(crate) mod tests {
));
let connection = StubAgentConnection::new();
connection.set_next_prompt_updates(vec![
- acp::SessionUpdate::AgentThoughtChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentThoughtChunk(acp_v1::ContentChunk::new(
"Private needle must not be copied.".into(),
)),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Before needle.".into())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(image.clone())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("After needle.".into())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(image)),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(resource)),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ "Before needle.".into(),
+ )),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(image.clone())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ "After needle.".into(),
+ )),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(image)),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(resource)),
]);
let (conversation_view, cx) =
@@ -7892,7 +7908,7 @@ pub(crate) mod tests {
#[gpui::test]
async fn test_message_context_menu_uses_clicked_content(cx: &mut TestAppContext) {
init_test(cx);
- let acp::ContentBlock::Image(image) = png_image() else {
+ let acp_v1::ContentBlock::Image(image) = png_image() else {
panic!("expected image fixture");
};
let linked_image = format!(
@@ -7901,11 +7917,13 @@ pub(crate) mod tests {
);
let connection = StubAgentConnection::new();
connection.set_next_prompt_updates(vec![
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"[first](https://one.example/)".into(),
)),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(png_image())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(linked_image.into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(png_image())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ linked_image.into(),
+ )),
]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -7973,9 +7991,9 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
connection.set_next_prompt_updates(vec![
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("**first**".into())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(png_image())),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("*second*".into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new("**first**".into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(png_image())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new("*second*".into())),
]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -8033,12 +8051,12 @@ pub(crate) mod tests {
async fn test_thread_search_includes_expanded_tool_call_content(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("search-tool-content");
+ let tool_call_id = acp_v1::ToolCallId::new("search-tool-content");
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(tool_call_id.clone(), "Inspect output")
- .kind(acp::ToolKind::Other)
- .status(acp::ToolCallStatus::Completed)
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Inspect output")
+ .kind(acp_v1::ToolKind::Other)
+ .status(acp_v1::ToolCallStatus::Completed)
.content(vec!["Tool output mentions papaya once.".into()]),
)]);
@@ -8094,18 +8112,18 @@ pub(crate) mod tests {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
"search-tool-content",
- acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(
- acp::ContentBlock::Text(acp::TextContent::new(
+ acp_v1::ToolCallUpdateFields::new().content(vec![
+ acp_v1::ToolCallContent::Content(acp_v1::Content::new(
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"Replacement contains mango.",
)),
)),
- acp::ToolCallContent::Content(acp::Content::new(
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new(
+ acp_v1::ToolCallContent::Content(acp_v1::Content::new(
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(
"Resource mango output.",
"tool://replacement",
)
@@ -8144,20 +8162,21 @@ pub(crate) mod tests {
for (fields, expected_matches) in [
(
- acp::ToolCallUpdateFields::new()
+ acp_v1::ToolCallUpdateFields::new()
.content(vec![])
.raw_output(serde_json::json!("Raw mango")),
1,
),
(
- acp::ToolCallUpdateFields::new().raw_output(serde_json::json!("Raw mango mango")),
+ acp_v1::ToolCallUpdateFields::new()
+ .raw_output(serde_json::json!("Raw mango mango")),
2,
),
] {
thread
.update(cx, |thread, cx| {
thread.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
"search-tool-content",
fields,
)),
@@ -8182,8 +8201,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("First reply, no fruit here.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("First reply, no fruit here.".into()),
)]);
let (conversation_view, cx) =
@@ -8197,8 +8216,8 @@ pub(crate) mod tests {
.await
.unwrap();
cx.run_until_parked();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Second reply, still no fruit.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Second reply, still no fruit.".into()),
)]);
thread
.update(cx, |thread, cx| thread.send_raw("Where is the papaya?", cx))
@@ -8254,8 +8273,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("First reply, no fruit here.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("First reply, no fruit here.".into()),
)]);
let (conversation_view, cx) =
@@ -8269,8 +8288,8 @@ pub(crate) mod tests {
.await
.unwrap();
cx.run_until_parked();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Second reply, still no fruit.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Second reply, still no fruit.".into()),
)]);
thread
.update(cx, |thread, cx| thread.send_raw("Where is the papaya?", cx))
@@ -8337,8 +8356,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Mango is a tropical fruit.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Mango is a tropical fruit.".into()),
)]);
let (conversation_view, cx) =
@@ -8387,8 +8406,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Mango is a tropical fruit.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Mango is a tropical fruit.".into()),
)]);
let (conversation_view, cx) =
@@ -8474,30 +8493,30 @@ pub(crate) mod tests {
.read_with(cx, |view, _| view.thread_search_bar.clone())
.expect("thread search bar should be open");
let resource =
- acp::EmbeddedResource::new(acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new("retained resource details", "summary://context")
+ acp_v1::EmbeddedResource::new(acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new("retained resource details", "summary://context")
.mime_type("text/markdown".to_string()),
));
for (update, query) in [
(
- acp::CompactionUpdate::new("failed", acp::CompactionStatus::Failed)
+ acp_v1::CompactionUpdate::new("failed", acp_v1::CompactionStatus::Failed)
.error("model *still* unavailable <details>"),
"model *still* unavailable <details>",
),
(
- acp::CompactionUpdate::new("completed", acp::CompactionStatus::Completed).summary(
- vec![
- acp::ContentBlock::Text(acp::TextContent::new("Retained summary")),
- acp::ContentBlock::Resource(resource),
- ],
- ),
+ acp_v1::CompactionUpdate::new("completed", acp_v1::CompactionStatus::Completed)
+ .summary(vec![
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("Retained summary")),
+ acp_v1::ContentBlock::Resource(resource),
+ ]),
"retained resource details",
),
] {
thread
.update(cx, |thread, cx| {
- thread.handle_session_update(acp::SessionUpdate::CompactionUpdate(update), cx)
+ thread
+ .handle_session_update(acp_v1::SessionUpdate::CompactionUpdate(update), cx)
})
.expect("failed to receive compaction details");
cx.run_until_parked();
@@ -8577,24 +8596,24 @@ pub(crate) mod tests {
for (update, expected_count) in [
(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new("tool", "")
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new("tool", "")
.name("mcp__search_tool")
- .status(acp::ToolCallStatus::Completed),
+ .status(acp_v1::ToolCallStatus::Completed),
),
1,
),
(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
"tool",
- acp::ToolCallUpdateFields::new().title("Reading **file**"),
+ acp_v1::ToolCallUpdateFields::new().title("Reading **file**"),
)),
0,
),
(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
"tool",
- acp::ToolCallUpdateFields::new().title("\n\t "),
+ acp_v1::ToolCallUpdateFields::new().title("\n\t "),
)),
1,
),
@@ -8612,7 +8631,7 @@ pub(crate) mod tests {
);
thread.read_with(cx, |thread, cx| {
let (_, call) = thread
- .tool_call(&acp::ToolCallId::new("tool"))
+ .tool_call(&acp_v1::ToolCallId::new("tool"))
.expect("tool call should exist");
assert_eq!(
!call.label.read(cx).search_highlights().is_empty(),
@@ -8627,8 +8646,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("First reply mentions banana once.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("First reply mentions banana once.".into()),
)]);
let (conversation_view, cx) =
@@ -8676,8 +8695,8 @@ pub(crate) mod tests {
);
// Advance past the debounced thread-update rescan.
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Banana banana: two more banana hits here.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Banana banana: two more banana hits here.".into()),
)]);
thread
.update(cx, |thread, cx| thread.send_raw("More banana please", cx))
@@ -8710,8 +8729,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new(
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(
"Banana banana banana, the banana fits the banana bread.".into(),
),
)]);
@@ -8776,8 +8795,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Sure, I can help with that.".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Sure, I can help with that.".into()),
)]);
let (conversation_view, cx) =
@@ -8918,8 +8937,8 @@ pub(crate) mod tests {
});
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new(
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(
"Banana banana banana, multiple banana mentions in this reply.".into(),
),
)]);
@@ -9018,8 +9037,8 @@ pub(crate) mod tests {
});
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new(
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new(
"Banana banana banana, multiple banana mentions in this reply.".into(),
),
)]);
@@ -9100,8 +9119,8 @@ pub(crate) mod tests {
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response".into()),
)]);
let (conversation_view, cx) =
@@ -9207,14 +9226,229 @@ pub(crate) mod tests {
);
}
+ async fn assert_unsupported_source_message_cannot_regenerate(
+ unsupported: agent_client_protocol::schema::v2::ContentBlock,
+ cx: &mut TestAppContext,
+ ) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ init_test(cx);
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::default_response(), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+
+ let thread_view = active_thread(&conversation_view, cx);
+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
+ thread
+ .update(cx, |thread, cx| thread.send_raw("original", cx))
+ .await
+ .expect("send initial message");
+ cx.run_until_parked();
+
+ let client_id = ClientUserMessageId::new();
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block(
+ Some(client_id.clone()),
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new("still visible")),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+
+ let index = thread.read_with(cx, |thread, _| thread.entries().len() - 1);
+ let entry_view_state = thread_view.read_with(cx, |view, _| view.entry_view_state.clone());
+ let editor = entry_view_state.read_with(cx, |state, _| {
+ state
+ .entry(index)
+ .and_then(|entry| entry.message_editor())
+ .cloned()
+ .expect("user message editor")
+ });
+ cx.focus(&editor);
+ thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, Some(index)));
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block(Some(client_id), unsupported.clone(), cx);
+ });
+ cx.run_until_parked();
+
+ thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None));
+ let rendered = editor.update(cx, |editor, cx| editor.text(cx));
+ assert!(rendered.contains("still visible"));
+ assert!(rendered.contains("Unsupported message content"));
+ cx.simulate_input("attempted edit");
+ assert_eq!(editor.update(cx, |editor, cx| editor.text(cx)), rendered);
+
+ thread_view.update_in(cx, |view, window, cx| {
+ view.handle_entry_view_event(
+ &entry_view_state,
+ &EntryViewEvent {
+ entry_index: index,
+ view_event: ViewEvent::MessageEditorEvent(
+ editor.clone(),
+ MessageEditorEvent::Send,
+ ),
+ },
+ window,
+ cx,
+ );
+ view.regenerate(index, editor.clone(), window, cx);
+ });
+ let other_editor = entry_view_state.read_with(cx, |state, _| {
+ state
+ .entry(0)
+ .and_then(|entry| entry.message_editor())
+ .cloned()
+ .expect("original editor")
+ });
+ cx.focus(&other_editor);
+ other_editor.update_in(cx, |editor, window, cx| {
+ assert!(editor.focus_handle(cx).is_focused(window));
+ });
+ let composer = message_editor(&conversation_view, cx);
+ cx.focus(&composer);
+ cx.run_until_parked();
+ thread_view.read_with(cx, |view, _| assert_eq!(view.editing_message, None));
+ thread.read_with(cx, |thread, _| {
+ assert_eq!(
+ thread.entries()[index]
+ .user_message()
+ .expect("user message")
+ .content
+ .source_blocks()[1],
+ unsupported
+ );
+ assert_eq!(thread.entries().len(), index + 1);
+ });
+ }
+
+ #[gpui::test]
+ async fn test_unsupported_source_message_cannot_regenerate(cx: &mut TestAppContext) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ assert_unsupported_source_message_cannot_regenerate(
+ acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
+ "_future",
+ Default::default(),
+ )),
+ cx,
+ )
+ .await;
+ }
+
+ #[gpui::test]
+ async fn test_unknown_annotation_source_message_cannot_regenerate(cx: &mut TestAppContext) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ assert_unsupported_source_message_cannot_regenerate(
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new("annotated text").annotations(
+ acp_v2::Annotations::new().audience(vec![acp_v2::Role::Other("_future".into())]),
+ )),
+ cx,
+ )
+ .await;
+ }
+
+ #[gpui::test]
+ async fn test_regenerate_does_not_resend_fallback_after_delayed_rewind(
+ cx: &mut TestAppContext,
+ ) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ init_test(cx);
+ for (cancel_before_update, cancel_after_update) in
+ [(false, false), (true, false), (false, true)]
+ {
+ let connection = StubAgentConnection::new();
+ let (conversation_view, cx) =
+ setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await;
+ add_to_workspace(conversation_view.clone(), cx);
+ let thread_view = active_thread(&conversation_view, cx);
+ let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
+ let prompt = thread.update(cx, |thread, cx| thread.send_raw("original", cx));
+ cx.run_until_parked();
+ let session_id = thread.read_with(cx, |thread, _| thread.session_id().clone());
+ connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn);
+ prompt.await.expect("initial prompt should finish");
+ cx.run_until_parked();
+
+ let client_id = thread.read_with(cx, |thread, _| {
+ thread
+ .entries()
+ .first()
+ .and_then(|entry| entry.user_message())
+ .and_then(|message| message.client_id.clone())
+ .expect("initial user message")
+ });
+ let editor = thread_view.read_with(cx, |view, cx| {
+ view.entry_view_state
+ .read(cx)
+ .entry(0)
+ .and_then(|entry| entry.message_editor())
+ .cloned()
+ .expect("initial message editor")
+ });
+ cx.focus(&editor);
+ editor.update_in(cx, |editor, window, cx| {
+ editor.set_text("edited", window, cx);
+ });
+ let finish_truncate = connection.defer_next_truncate();
+ thread_view.update_in(cx, |view, window, cx| {
+ view.regenerate(0, editor.clone(), window, cx);
+ });
+ cx.run_until_parked();
+ assert_eq!(thread.read_with(cx, |thread, _| thread.entries().len()), 1);
+
+ if cancel_before_update {
+ thread_view.update_in(cx, |view, window, cx| {
+ view.cancel_editing(&Default::default(), window, cx);
+ });
+ }
+ thread.update(cx, |thread, cx| {
+ thread.push_user_content_block(
+ Some(client_id),
+ acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
+ "_future",
+ Default::default(),
+ )),
+ cx,
+ );
+ });
+ cx.run_until_parked();
+ if cancel_after_update {
+ thread_view.update_in(cx, |view, window, cx| {
+ view.cancel_editing(&Default::default(), window, cx);
+ });
+ }
+ assert!(
+ editor
+ .update(cx, |editor, cx| editor.text(cx))
+ .contains("Unsupported message content")
+ );
+ finish_truncate
+ .send(())
+ .expect("truncate should be pending");
+ cx.run_until_parked();
+
+ let resent =
+ thread.read_with(cx, |thread, _| thread.status() == ThreadStatus::Generating);
+ if resent {
+ connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
+ cx.run_until_parked();
+ }
+ assert!(!resent, "regeneration must not submit a read-only fallback");
+ thread.read_with(cx, |thread, _| assert!(thread.entries().is_empty()));
+ thread_view.read_with(cx, |view, _| assert!(view.thread_error.is_some()));
+ }
+ }
+
#[gpui::test]
async fn test_message_editing_regenerate(cx: &mut TestAppContext) {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response".into()),
)]);
let (conversation_view, cx) =
@@ -9268,8 +9502,8 @@ pub(crate) mod tests {
});
// Send
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("New Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("New Response".into()),
)]);
user_message_editor.update_in(cx, |_editor, window, cx| {
@@ -9381,10 +9615,12 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("Response".into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ "Response".into(),
+ )),
cx,
);
- connection.end_turn(session_id, acp::StopReason::EndTurn);
+ connection.end_turn(session_id, acp_v1::StopReason::EndTurn);
});
conversation_view.read_with(cx, |view, cx| {
@@ -9509,7 +9745,7 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"Response chunk".into(),
)),
cx,
@@ -9640,7 +9876,7 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"Message 1 resp".into(),
)),
cx,
@@ -9675,7 +9911,7 @@ pub(crate) mod tests {
// Simulate a response sent after beginning to cancel
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new("onse".into())),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new("onse".into())),
cx,
);
});
@@ -9706,12 +9942,12 @@ pub(crate) mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id.clone(),
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"Message 2 response".into(),
)),
cx,
);
- connection.end_turn(session_id.clone(), acp::StopReason::EndTurn);
+ connection.end_turn(session_id.clone(), acp_v1::StopReason::EndTurn);
});
cx.run_until_parked();
@@ -9746,8 +9982,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response".into()),
)]);
let (conversation_view, cx) =
@@ -9848,8 +10084,8 @@ pub(crate) mod tests {
init_test(cx);
let connection = StubAgentConnection::new();
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::AgentMessageChunk(
- acp::ContentChunk::new("Response".into()),
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::AgentMessageChunk(
+ acp_v1::ContentChunk::new("Response".into()),
)]);
let (conversation_view, cx) =
@@ -9920,15 +10156,15 @@ pub(crate) mod tests {
init_test(cx);
for (exit_status, failure_selector) in [
(
- acp::TerminalExitStatus::new().exit_code(7),
+ acp_v1::TerminalExitStatus::new().exit_code(7),
"terminal-tool-failed-Some(7)",
),
(
- acp::TerminalExitStatus::new().signal("SIGTERM"),
+ acp_v1::TerminalExitStatus::new().signal("SIGTERM"),
"terminal-tool-failed-None",
),
(
- acp::TerminalExitStatus::new().exit_code(u32::MAX),
+ acp_v1::TerminalExitStatus::new().exit_code(u32::MAX),
"terminal-tool-failed-Some(4294967295)",
),
] {
@@ -9937,8 +10173,8 @@ pub(crate) mod tests {
add_to_workspace_with_size(conversation_view.clone(), true, cx);
let thread_view = active_thread(&conversation_view, cx);
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
- let terminal_id = acp::TerminalId::new("provider-terminal");
- let tool_id = acp::ToolCallId::new("provider-tool");
+ let terminal_id = acp_v1::TerminalId::new("provider-terminal");
+ let tool_id = acp_v1::ToolCallId::new("provider-tool");
let terminal = cx.new(|cx| {
terminal::TerminalBuilder::new_display_only(
Default::default(),
@@ -9964,13 +10200,13 @@ pub(crate) mod tests {
);
thread
.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(tool_id.clone(), "provider command")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::InProgress)
- .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
- terminal_id.clone(),
- ))]),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_id.clone(), "provider command")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::InProgress)
+ .content(vec![acp_v1::ToolCallContent::Terminal(
+ acp_v1::Terminal::new(terminal_id.clone()),
+ )]),
),
cx,
)
@@ -10029,9 +10265,10 @@ pub(crate) mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
tool_id.clone(),
- acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::Completed),
+ acp_v1::ToolCallUpdateFields::new()
+ .status(acp_v1::ToolCallStatus::Completed),
)),
cx,
)
@@ -10067,8 +10304,8 @@ pub(crate) mod tests {
add_to_workspace_with_size(conversation_view.clone(), true, cx);
let thread_view = active_thread(&conversation_view, cx);
let thread = thread_view.read_with(cx, |view, _| view.thread.clone());
- let terminal_id = acp::TerminalId::new("acp-owned-terminal");
- let tool_id = acp::ToolCallId::new("acp-owned-tool");
+ let terminal_id = acp_v1::TerminalId::new("acp-owned-terminal");
+ let tool_id = acp_v1::ToolCallId::new("acp-owned-tool");
let lower_terminal = cx.new(|cx| {
terminal::TerminalBuilder::new_display_only(
Default::default(),
@@ -10093,13 +10330,13 @@ pub(crate) mod tests {
);
thread
.handle_session_update(
- acp::SessionUpdate::ToolCall(
- acp::ToolCall::new(tool_id.clone(), "client-owned command")
- .kind(acp::ToolKind::Execute)
- .status(acp::ToolCallStatus::InProgress)
- .content(vec![acp::ToolCallContent::Terminal(acp::Terminal::new(
- terminal_id,
- ))]),
+ acp_v1::SessionUpdate::ToolCall(
+ acp_v1::ToolCall::new(tool_id.clone(), "client-owned command")
+ .kind(acp_v1::ToolKind::Execute)
+ .status(acp_v1::ToolCallStatus::InProgress)
+ .content(vec![acp_v1::ToolCallContent::Terminal(
+ acp_v1::Terminal::new(terminal_id),
+ )]),
),
cx,
)
@@ -10142,9 +10379,9 @@ pub(crate) mod tests {
async fn test_tool_permission_buttons_terminal_with_pattern(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("terminal-1");
- let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
- .kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("terminal-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `cargo build --release`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options = ToolPermissionContext::new(
TerminalTool::NAME,
@@ -10158,7 +10395,7 @@ pub(crate) mod tests {
permission_options,
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10254,9 +10491,9 @@ pub(crate) mod tests {
async fn test_tool_permission_buttons_edit_file_with_path_pattern(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("edit-file-1");
- let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
- .kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("edit-file-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Edit `src/main.rs`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(EditFileTool::NAME, vec!["src/main.rs".to_string()])
@@ -10268,7 +10505,7 @@ pub(crate) mod tests {
permission_options,
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10344,9 +10581,9 @@ pub(crate) mod tests {
async fn test_tool_permission_buttons_fetch_with_domain_pattern(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("fetch-1");
- let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
- .kind(acp::ToolKind::Fetch);
+ let tool_call_id = acp_v1::ToolCallId::new("fetch-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Fetch `https://docs.rs/gpui`")
+ .kind(acp_v1::ToolKind::Fetch);
let permission_options =
ToolPermissionContext::new(FetchTool::NAME, vec!["https://docs.rs/gpui".to_string()])
@@ -10358,7 +10595,7 @@ pub(crate) mod tests {
permission_options,
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10434,9 +10671,10 @@ pub(crate) mod tests {
async fn test_tool_permission_buttons_without_pattern(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("terminal-no-pattern-1");
- let tool_call = acp::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
- .kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("terminal-no-pattern-1");
+ let tool_call =
+ acp_v1::ToolCall::new(tool_call_id.clone(), "Run `./deploy.sh --production`")
+ .kind(acp_v1::ToolKind::Edit);
// No pattern button since ./deploy.sh doesn't match the alphanumeric pattern
let permission_options = ToolPermissionContext::new(
@@ -10451,7 +10689,7 @@ pub(crate) mod tests {
permission_options,
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10538,9 +10776,9 @@ pub(crate) mod tests {
async fn test_authorize_tool_call_action_triggers_authorization(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("action-test-1");
- let tool_call =
- acp::ToolCall::new(tool_call_id.clone(), "Run `cargo test`").kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("action-test-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `cargo test`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo test".to_string()])
@@ -10552,7 +10790,7 @@ pub(crate) mod tests {
permission_options,
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10616,9 +10854,9 @@ pub(crate) mod tests {
async fn test_authorize_tool_call_action_with_pattern_option(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("pattern-action-test-1");
- let tool_call =
- acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("pattern-action-test-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `npm install`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
@@ -10630,7 +10868,7 @@ pub(crate) mod tests {
permission_options.clone(),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10695,9 +10933,9 @@ pub(crate) mod tests {
async fn test_granularity_selection_updates_state(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("granularity-test-1");
- let tool_call =
- acp::ToolCall::new(tool_call_id.clone(), "Run `cargo build`").kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("granularity-test-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `cargo build`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(TerminalTool::NAME, vec!["cargo build".to_string()])
@@ -10709,7 +10947,7 @@ pub(crate) mod tests {
permission_options.clone(),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
add_to_workspace(thread_view.clone(), cx);
@@ -10773,9 +11011,9 @@ pub(crate) mod tests {
async fn test_allow_button_uses_selected_granularity(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("allow-granularity-test-1");
- let tool_call =
- acp::ToolCall::new(tool_call_id.clone(), "Run `npm install`").kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("allow-granularity-test-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `npm install`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(TerminalTool::NAME, vec!["npm install".to_string()])
@@ -10810,7 +11048,7 @@ pub(crate) mod tests {
permission_options.clone(),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (thread_view, cx) = setup_conversation_view(StubAgentServer::new(connection), cx).await;
add_to_workspace(thread_view.clone(), cx);
@@ -10870,9 +11108,9 @@ pub(crate) mod tests {
async fn test_deny_button_uses_selected_granularity(cx: &mut TestAppContext) {
init_test(cx);
- let tool_call_id = acp::ToolCallId::new("deny-granularity-test-1");
- let tool_call =
- acp::ToolCall::new(tool_call_id.clone(), "Run `git push`").kind(acp::ToolKind::Edit);
+ let tool_call_id = acp_v1::ToolCallId::new("deny-granularity-test-1");
+ let tool_call = acp_v1::ToolCall::new(tool_call_id.clone(), "Run `git push`")
+ .kind(acp_v1::ToolKind::Edit);
let permission_options =
ToolPermissionContext::new(TerminalTool::NAME, vec!["git push".to_string()])
@@ -10884,7 +11122,7 @@ pub(crate) mod tests {
permission_options.clone(),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -10986,40 +11224,40 @@ pub(crate) mod tests {
fn flat_allow_deny_options() -> PermissionOptions {
PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Yes",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("deny"),
"No",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v1::PermissionOptionKind::RejectOnce,
),
])
}
fn sandbox_permission_options() -> PermissionOptions {
PermissionOptions::Flat(vec![
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow"),
"Allow once",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow_thread"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow_thread"),
"Allow for this thread",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v1::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("allow_always"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("allow_always"),
"Allow always",
- acp::PermissionOptionKind::AllowAlways,
+ acp_v1::PermissionOptionKind::AllowAlways,
),
- acp::PermissionOption::new(
- acp::PermissionOptionId::new("deny"),
+ acp_v1::PermissionOption::new(
+ acp_v1::PermissionOptionId::new("deny"),
"Deny",
- acp::PermissionOptionKind::RejectOnce,
+ acp_v1::PermissionOptionKind::RejectOnce,
),
])
}
@@ -11028,9 +11266,11 @@ pub(crate) mod tests {
fn permission_option_for_action_prefers_explicit_sandbox_allow_always() {
let options = sandbox_permission_options();
- let option =
- super::permission_option_for_action(&options, acp::PermissionOptionKind::AllowAlways)
- .unwrap();
+ let option = super::permission_option_for_action(
+ &options,
+ acp_v1::PermissionOptionKind::AllowAlways,
+ )
+ .unwrap();
assert_eq!(option.option_id.0.as_ref(), "allow_always");
}
@@ -11042,7 +11282,7 @@ pub(crate) mod tests {
let outcome = super::resolve_outcome_from_selection(&options, None, true).unwrap();
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -11052,7 +11292,10 @@ pub(crate) mod tests {
let outcome = super::resolve_outcome_from_selection(&options, None, false).unwrap();
assert_eq!(outcome.option_id.0.as_ref(), "deny");
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::RejectOnce);
+ assert_eq!(
+ outcome.option_kind,
+ acp_v1::PermissionOptionKind::RejectOnce
+ );
}
#[test]
@@ -11077,7 +11320,7 @@ pub(crate) mod tests {
// Last choice is "Only this time" → option_id "allow".
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -11092,7 +11335,10 @@ pub(crate) mod tests {
// Choice 0 = "Always for terminal".
assert!(outcome.option_id.0.contains("always_allow:terminal"));
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowAlways);
+ assert_eq!(
+ outcome.option_kind,
+ acp_v1::PermissionOptionKind::AllowAlways
+ );
}
#[test]
@@ -11131,7 +11377,7 @@ pub(crate) mod tests {
super::resolve_outcome_from_selection(&options, Some(&selection), true).unwrap();
assert_eq!(outcome.option_id.0.as_ref(), "allow");
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowOnce);
+ assert_eq!(outcome.option_kind, acp_v1::PermissionOptionKind::AllowOnce);
}
#[test]
@@ -11150,7 +11396,10 @@ pub(crate) mod tests {
let outcome =
super::resolve_outcome_from_selection(&options, Some(&selection), true).unwrap();
- assert_eq!(outcome.option_kind, acp::PermissionOptionKind::AllowAlways);
+ assert_eq!(
+ outcome.option_kind,
+ acp_v1::PermissionOptionKind::AllowAlways
+ );
assert!(
outcome.params.is_some(),
"checked patterns should attach terminal params"
@@ -11218,7 +11467,7 @@ pub(crate) mod tests {
cx.run_until_parked();
cx.update(|_, _cx| {
- connection.end_turn(session_id, acp::StopReason::MaxTokens);
+ connection.end_turn(session_id, acp_v1::StopReason::MaxTokens);
});
cx.run_until_parked();
@@ -11235,7 +11484,7 @@ pub(crate) mod tests {
}
fn create_test_acp_thread(
- parent_session_id: Option<acp::SessionId>,
+ parent_session_id: Option<acp_v1::SessionId>,
session_id: &str,
connection: Rc<dyn AgentConnection>,
project: Entity<Project>,
@@ -11250,8 +11499,8 @@ pub(crate) mod tests {
connection,
project,
action_log,
- acp::SessionId::new(session_id),
- watch::Receiver::constant(acp::PromptCapabilities::new()),
+ acp_v1::SessionId::new(session_id),
+ watch::Receiver::constant(acp_v1::PromptCapabilities::new()),
cx,
)
})
@@ -11263,20 +11512,20 @@ pub(crate) mod tests {
option_id: &str,
cx: &mut TestAppContext,
) -> Task<acp_thread::RequestPermissionOutcome> {
- let tool_call_id = acp::ToolCallId::new(tool_call_id);
+ let tool_call_id = acp_v1::ToolCallId::new(tool_call_id);
let label = format!("Tool {tool_call_id}");
- let option_id = acp::PermissionOptionId::new(option_id);
+ let option_id = acp_v1::PermissionOptionId::new(option_id);
cx.update(|cx| {
thread.update(cx, |thread, cx| {
thread
.request_tool_call_authorization(
- acp::ToolCall::new(tool_call_id, label)
- .kind(acp::ToolKind::Edit)
+ acp_v1::ToolCall::new(tool_call_id, label)
+ .kind(acp_v1::ToolKind::Edit)
.into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
option_id,
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
@@ -11294,7 +11543,7 @@ pub(crate) mod tests {
let project = Project::test(fs, [], cx).await;
let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
- let session_id = acp::SessionId::new("session-1");
+ let session_id = acp_v1::SessionId::new("session-1");
let (thread, conversation) = cx.update(|cx| {
let thread =
create_test_acp_thread(None, "session-1", connection.clone(), project.clone(), cx);
@@ -11314,17 +11563,17 @@ pub(crate) mod tests {
.read(cx)
.pending_tool_call(&session_id, cx)
.expect("Expected a pending tool call");
- assert_eq!(tool_call_id, acp::ToolCallId::new("tc-1"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("tc-1"));
});
cx.update(|cx| {
conversation.update(cx, |conversation, cx| {
conversation.authorize_tool_call(
session_id.clone(),
- acp::ToolCallId::new("tc-1"),
+ acp_v1::ToolCallId::new("tc-1"),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-1"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow-1"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -11338,17 +11587,17 @@ pub(crate) mod tests {
.read(cx)
.pending_tool_call(&session_id, cx)
.expect("Expected tc-2 to be pending after tc-1 was authorized");
- assert_eq!(tool_call_id, acp::ToolCallId::new("tc-2"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("tc-2"));
});
cx.update(|cx| {
conversation.update(cx, |conversation, cx| {
conversation.authorize_tool_call(
session_id.clone(),
- acp::ToolCallId::new("tc-2"),
+ acp_v1::ToolCallId::new("tc-2"),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-2"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow-2"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -11376,13 +11625,13 @@ pub(crate) mod tests {
let project = Project::test(fs, [], cx).await;
let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
- let parent_session_id = acp::SessionId::new("parent");
- let subagent_session_id = acp::SessionId::new("subagent");
+ let parent_session_id = acp_v1::SessionId::new("parent");
+ let subagent_session_id = acp_v1::SessionId::new("subagent");
let (parent_thread, subagent_thread, conversation) = cx.update(|cx| {
let parent_thread =
create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
let subagent_thread = create_test_acp_thread(
- Some(acp::SessionId::new("parent")),
+ Some(acp_v1::SessionId::new("parent")),
"subagent",
connection.clone(),
project.clone(),
@@ -11410,7 +11659,7 @@ pub(crate) mod tests {
.pending_tool_call(&subagent_session_id, cx)
.expect("Expected subagent's pending tool call");
assert_eq!(returned_session_id, subagent_session_id);
- assert_eq!(tool_call_id, acp::ToolCallId::new("subagent-tc"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("subagent-tc"));
});
// Querying with the parent's session ID returns the first pending
@@ -11421,7 +11670,7 @@ pub(crate) mod tests {
.pending_tool_call(&parent_session_id, cx)
.expect("Expected a pending tool call from parent query");
assert_eq!(returned_session_id, parent_session_id);
- assert_eq!(tool_call_id, acp::ToolCallId::new("parent-tc"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("parent-tc"));
});
}
@@ -11433,8 +11682,8 @@ pub(crate) mod tests {
let fs = FakeFs::new(cx.executor());
let project = Project::test(fs, [], cx).await;
let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
- let parent_session_id = acp::SessionId::new("parent");
- let subagent_session_id = acp::SessionId::new("subagent");
+ let parent_session_id = acp_v1::SessionId::new("parent");
+ let subagent_session_id = acp_v1::SessionId::new("subagent");
let (subagent_thread, conversation) = cx.update(|cx| {
let parent_thread =
create_test_acp_thread(None, "parent", connection.clone(), project.clone(), cx);
@@ -11457,10 +11706,10 @@ pub(crate) mod tests {
request_test_tool_authorization(&subagent_thread, "resolved-tool", "allow-child", cx);
subagent_thread.update(cx, |thread, cx| {
thread.authorize_tool_call(
- acp::ToolCallId::new("resolved-tool"),
+ acp_v1::ToolCallId::new("resolved-tool"),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-child"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow-child"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -11473,11 +11722,11 @@ pub(crate) mod tests {
let response = subagent_thread.update(cx, |thread, cx| {
thread
.request_tool_call_authorization(
- acp::ToolCall::new("queued-tool", "Queued permission").into(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
+ acp_v1::ToolCall::new("queued-tool", "Queued permission").into(),
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
"allow-child",
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
acp_thread::AuthorizationKind::PermissionGrant,
cx,
@@ -11494,7 +11743,7 @@ pub(crate) mod tests {
request_test_tool_authorization(&subagent_thread, "later-tool", "allow-child", cx);
for (tool_id, pending_count) in [("child-tool", 3), ("queued-tool", 2), ("later-tool", 1)] {
- let tool_id = acp::ToolCallId::new(tool_id);
+ let tool_id = acp_v1::ToolCallId::new(tool_id);
conversation.read_with(cx, |conversation, cx| {
assert_eq!(
conversation.pending_tool_call_for_session(&subagent_session_id, cx),
@@ -11515,8 +11764,8 @@ pub(crate) mod tests {
subagent_session_id.clone(),
tool_id,
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-child"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow-child"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -11543,8 +11792,8 @@ pub(crate) mod tests {
let project = Project::test(fs, [], cx).await;
let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
- let session_id_a = acp::SessionId::new("thread-a");
- let session_id_b = acp::SessionId::new("thread-b");
+ let session_id_a = acp_v1::SessionId::new("thread-a");
+ let session_id_b = acp_v1::SessionId::new("thread-b");
let (thread_a, thread_b, conversation) = cx.update(|cx| {
let thread_a =
create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
@@ -11570,7 +11819,7 @@ pub(crate) mod tests {
.pending_tool_call(&session_id_a, cx)
.expect("Expected a pending tool call");
assert_eq!(returned_session_id, session_id_a);
- assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("tc-a"));
});
// Querying with thread-b also returns thread-a's tool call,
@@ -11584,7 +11833,7 @@ pub(crate) mod tests {
returned_session_id, session_id_a,
"Non-subagent queries always return the first pending request in FIFO order"
);
- assert_eq!(tool_call_id, acp::ToolCallId::new("tc-a"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("tc-a"));
});
// After authorizing thread-a's tool call, thread-b's becomes first
@@ -11592,10 +11841,10 @@ pub(crate) mod tests {
conversation.update(cx, |conversation, cx| {
conversation.authorize_tool_call(
session_id_a.clone(),
- acp::ToolCallId::new("tc-a"),
+ acp_v1::ToolCallId::new("tc-a"),
SelectedPermissionOutcome::new(
- acp::PermissionOptionId::new("allow-a"),
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionId::new("allow-a"),
+ acp_v1::PermissionOptionKind::AllowOnce,
),
cx,
);
@@ -11610,7 +11859,7 @@ pub(crate) mod tests {
.pending_tool_call(&session_id_b, cx)
.expect("Expected thread-b's tool call after thread-a's was authorized");
assert_eq!(returned_session_id, session_id_b);
- assert_eq!(tool_call_id, acp::ToolCallId::new("tc-b"));
+ assert_eq!(tool_call_id, acp_v1::ToolCallId::new("tc-b"));
});
}
@@ -11626,20 +11875,20 @@ pub(crate) mod tests {
usize,
&'a mut VisualTestContext,
) {
- let tool_call_id_value = acp::ToolCallId::new(tool_call_id);
- let tool_call = acp::ToolCall::new(tool_call_id_value.clone(), "Run something")
- .kind(acp::ToolKind::Edit);
+ let tool_call_id_value = acp_v1::ToolCallId::new(tool_call_id);
+ let tool_call = acp_v1::ToolCall::new(tool_call_id_value.clone(), "Run something")
+ .kind(acp_v1::ToolKind::Edit);
let connection =
StubAgentConnection::new().with_permission_requests(HashMap::from_iter([(
tool_call_id_value.clone(),
- PermissionOptions::Flat(vec![acp::PermissionOption::new(
+ PermissionOptions::Flat(vec![acp_v1::PermissionOption::new(
"allow",
"Allow",
- acp::PermissionOptionKind::AllowOnce,
+ acp_v1::PermissionOptionKind::AllowOnce,
)]),
)]));
- connection.set_next_prompt_updates(vec![acp::SessionUpdate::ToolCall(tool_call)]);
+ connection.set_next_prompt_updates(vec![acp_v1::SessionUpdate::ToolCall(tool_call)]);
let (conversation_view, cx) =
setup_conversation_view(StubAgentServer::new(connection), cx).await;
@@ -11748,8 +11997,8 @@ pub(crate) mod tests {
let project = Project::test(fs, [], cx).await;
let connection: Rc<dyn AgentConnection> = Rc::new(StubAgentConnection::new());
- let session_id_a = acp::SessionId::new("thread-a");
- let session_id_b = acp::SessionId::new("thread-b");
+ let session_id_a = acp_v1::SessionId::new("thread-a");
+ let session_id_b = acp_v1::SessionId::new("thread-b");
let (thread_a, thread_b, conversation) = cx.update(|cx| {
let thread_a =
create_test_acp_thread(None, "thread-a", connection.clone(), project.clone(), cx);
@@ -11774,13 +12023,13 @@ pub(crate) mod tests {
.read(cx)
.pending_tool_call_for_session(&session_id_a, cx)
.expect("Expected a pending tool call in thread A");
- assert_eq!(tool_call_id_a, acp::ToolCallId::new("tc-a"));
+ assert_eq!(tool_call_id_a, acp_v1::ToolCallId::new("tc-a"));
let tool_call_id_b = conversation
.read(cx)
.pending_tool_call_for_session(&session_id_b, cx)
.expect("Expected a pending tool call in thread B");
- assert_eq!(tool_call_id_b, acp::ToolCallId::new("tc-b"));
+ assert_eq!(tool_call_id_b, acp_v1::ToolCallId::new("tc-b"));
});
}
@@ -11851,11 +12100,11 @@ pub(crate) mod tests {
thread.update(cx, |thread, cx| {
thread
.handle_session_update(
- acp::SessionUpdate::ToolCallUpdate(acp::ToolCallUpdate::new(
- acp::ToolCallId::new("perm-flicker"),
- acp::ToolCallUpdateFields::new().content(vec![
- acp::ToolCallContent::Content(acp::Content::new(
- acp::ContentBlock::Text(acp::TextContent::new(
+ acp_v1::SessionUpdate::ToolCallUpdate(acp_v1::ToolCallUpdate::new(
+ acp_v1::ToolCallId::new("perm-flicker"),
+ acp_v1::ToolCallUpdateFields::new().content(vec![
+ acp_v1::ToolCallContent::Content(acp_v1::Content::new(
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"Plan step\n\n".repeat(100),
)),
)),
@@ -11913,7 +12162,7 @@ pub(crate) mod tests {
let thread = thread_view.read_with(cx, |view, _cx| view.thread.clone());
thread.update(cx, |thread, cx| {
let result = thread.handle_session_update(
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
"More content".into(),
)),
cx,
@@ -12097,7 +12346,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::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -12136,7 +12385,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::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"existing content".to_string(),
))],
window,
@@ -12147,7 +12396,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::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -12183,7 +12432,7 @@ pub(crate) mod tests {
active_thread(&conversation_view, cx).update_in(cx, |thread, window, cx| {
thread.add_to_queue(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"first queued".to_string(),
))],
vec![],
@@ -12191,7 +12440,7 @@ pub(crate) mod tests {
cx,
);
thread.add_to_queue(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"second queued".to_string(),
))],
vec![],
@@ -12300,9 +12549,9 @@ pub(crate) mod tests {
thread
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().image(true));
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().image(true));
thread.add_to_queue(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"queued message".to_string(),
))],
vec![],
@@ -12475,7 +12724,7 @@ pub(crate) mod tests {
#[derive(Clone)]
struct CloseCapableConnection {
- closed_sessions: Arc<Mutex<Vec<acp::SessionId>>>,
+ closed_sessions: Arc<Mutex<Vec<acp_v1::SessionId>>>,
}
impl CloseCapableConnection {
@@ -12510,9 +12759,9 @@ pub(crate) mod tests {
self,
project,
action_log,
- acp::SessionId::new("close-capable-session"),
+ acp_v1::SessionId::new("close-capable-session"),
watch::Receiver::constant(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -12529,20 +12778,20 @@ pub(crate) mod tests {
fn close_session(
self: Rc<Self>,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
_cx: &mut App,
) -> Task<Result<()>> {
self.closed_sessions.lock().push(session_id.clone());
Task::ready(Ok(()))
}
- fn auth_methods(&self) -> &[acp::AuthMethod] {
+ fn auth_methods(&self) -> &[acp_v1::AuthMethod] {
&[]
}
fn authenticate(
&self,
- _method_id: acp::AuthMethodId,
+ _method_id: acp_v1::AuthMethodId,
_cx: &mut App,
) -> Task<gpui::Result<()>> {
Task::ready(Ok(()))
@@ -12550,13 +12799,13 @@ pub(crate) mod tests {
fn prompt(
&self,
- _params: acp::PromptRequest,
+ _params: acp_v1::PromptRequest,
_cx: &mut App,
- ) -> Task<gpui::Result<acp::PromptResponse>> {
- Task::ready(Ok(acp::PromptResponse::new(acp::StopReason::EndTurn)))
+ ) -> Task<gpui::Result<acp_v1::PromptResponse>> {
+ Task::ready(Ok(acp_v1::PromptResponse::new(acp_v1::StopReason::EndTurn)))
}
- fn cancel(&self, _session_id: &acp::SessionId, _cx: &mut App) {}
+ fn cancel(&self, _session_id: &acp_v1::SessionId, _cx: &mut App) {}
fn into_any(self: Rc<Self>) -> Rc<dyn Any> {
self
diff --git a/crates/agent_ui/src/conversation_view/message_queue.rs b/crates/agent_ui/src/conversation_view/message_queue.rs
index 31f1a000235..b87c632264e 100644
--- a/crates/agent_ui/src/conversation_view/message_queue.rs
+++ b/crates/agent_ui/src/conversation_view/message_queue.rs
@@ -7,7 +7,7 @@ pub struct QueueEntryId(usize);
pub struct QueueEntry {
pub id: QueueEntryId,
- pub content: Vec<acp::ContentBlock>,
+ pub content: Vec<acp_v1::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
diff --git a/crates/agent_ui/src/conversation_view/thread_search_bar.rs b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
index cfc5e6eb260..437c3babb2f 100644
--- a/crates/agent_ui/src/conversation_view/thread_search_bar.rs
+++ b/crates/agent_ui/src/conversation_view/thread_search_bar.rs
@@ -945,7 +945,7 @@ mod tests {
use acp_thread::{
ContentBlock, ContextCompaction, ContextCompactionId, ContextCompactionStatus,
};
- use agent_client_protocol::schema::v1 as acp;
+ use agent_client_protocol::schema::v1 as acp_v1;
use language::LanguageRegistry;
#[gpui::test]
@@ -954,7 +954,11 @@ mod tests {
let error = cx.new(|cx| Markdown::new("error match".into(), None, None, cx));
let language_registry = Arc::new(LanguageRegistry::test(cx.background_executor().clone()));
let unsupported_block = ContentBlock::new_output(
- acp::ContentBlock::Audio(acp::AudioContent::new("YXVkaW8=", "audio/wav")),
+ acp_thread::content::from_v1(acp_v1::ContentBlock::Audio(acp_v1::AudioContent::new(
+ "YXVkaW8=",
+ "audio/wav",
+ )))
+ .expect("known v1 audio content"),
&language_registry,
cx,
);
diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs
index 97fc7ea325a..da1fcf9a658 100644
--- a/crates/agent_ui/src/conversation_view/thread_view.rs
+++ b/crates/agent_ui/src/conversation_view/thread_view.rs
@@ -4,7 +4,7 @@ use crate::{
open_abs_path_at_point,
thread_metadata_store::{ThreadId, ThreadMetadataStore},
};
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::{v1 as acp_v1, v2 as acp_v2};
use std::cell::RefCell;
use acp_thread::{
@@ -564,8 +564,8 @@ impl PermissionSelection {
pub struct ThreadView {
pub(crate) root_thread_id: ThreadId,
- pub session_id: acp::SessionId,
- pub parent_session_id: Option<acp::SessionId>,
+ pub session_id: acp_v1::SessionId,
+ pub parent_session_id: Option<acp_v1::SessionId>,
pub thread: Entity<AcpThread>,
pub(crate) conversation: Entity<super::Conversation>,
pub server_view: WeakEntity<ConversationView>,
@@ -590,14 +590,14 @@ pub struct ThreadView {
thread_feedback: ThreadFeedbackState,
pub list_state: ListState,
pub session_capabilities: SharedSessionCapabilities,
- pub expanded_tool_call_raw_inputs: HashSet<acp::ToolCallId>,
- collapsed_sandbox_authorization_details: HashSet<acp::ToolCallId>,
- collapsed_sandbox_network_details: HashSet<acp::ToolCallId>,
+ pub expanded_tool_call_raw_inputs: HashSet<acp_v1::ToolCallId>,
+ collapsed_sandbox_authorization_details: HashSet<acp_v1::ToolCallId>,
+ collapsed_sandbox_network_details: HashSet<acp_v1::ToolCallId>,
/// Sandbox escalation prompts whose "surprising Unicode" warning the user
/// has explicitly acknowledged. Until a prompt's tool call is in this set,
/// its allow buttons stay disabled. See [`Self::sandbox_confusable_findings`].
- acknowledged_confusable_warnings: HashSet<acp::ToolCallId>,
- pub subagent_scroll_handles: RefCell<HashMap<acp::SessionId, ScrollHandle>>,
+ acknowledged_confusable_warnings: HashSet<acp_v1::ToolCallId>,
+ pub subagent_scroll_handles: RefCell<HashMap<acp_v1::SessionId, ScrollHandle>>,
pub edits_expanded: bool,
pub plan_expanded: bool,
pub queue_expanded: bool,
@@ -606,18 +606,18 @@ pub struct ThreadView {
pub editing_message: Option<usize>,
pub message_queue: MessageQueue,
pub turn_fields: TurnFields,
- pub discarded_partial_edits: HashSet<acp::ToolCallId>,
+ pub discarded_partial_edits: HashSet<acp_v1::ToolCallId>,
pub is_loading_contents: bool,
pub new_server_version_available: Option<SharedString>,
pub resumed_without_history: bool,
- pub(crate) permission_selections: HashMap<acp::ToolCallId, PermissionSelection>,
+ pub(crate) permission_selections: HashMap<acp_v1::ToolCallId, PermissionSelection>,
elicitation_form_states: HashMap<ElicitationEntryId, ElicitationFormState>,
pub _cancel_task: Option<Task<()>>,
_save_task: Option<Task<()>>,
_draft_resolve_task: Option<Task<()>>,
_sandbox_status_refresh_task: Option<Task<()>>,
pub hovered_edited_file_buttons: Option<usize>,
- pub in_flight_prompt: Option<Vec<acp::ContentBlock>>,
+ pub in_flight_prompt: Option<Vec<acp_v1::ContentBlock>>,
pub _subscriptions: Vec<Subscription>,
pub message_editor: Entity<MessageEditor>,
pub add_context_menu_handle: PopoverMenuHandle<ContextMenu>,
@@ -839,7 +839,7 @@ impl ThreadView {
// SECURITY: Be explicit about not auto submitting prompt from external source.
should_auto_submit = false;
editor.set_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
prompt.into_string(),
))],
window,
@@ -1203,7 +1203,7 @@ impl ThreadView {
&self,
message_editor: &Entity<MessageEditor>,
cx: &mut App,
- ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
+ ) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
let expand = self.as_native_thread(cx).is_some_and(|thread| {
let thread = thread.read(cx);
AgentSettings::get_global(cx)
@@ -1233,6 +1233,25 @@ impl ThreadView {
self.parent_session_id.is_some()
}
+ pub(super) fn can_edit_user_message(&self, index: usize, cx: &App) -> bool {
+ let thread = self.thread.read(cx);
+ let Some(message) = thread
+ .entries()
+ .get(index)
+ .and_then(|entry| entry.user_message())
+ else {
+ return false;
+ };
+ !self.is_subagent()
+ && thread.supports_truncate(cx)
+ && message.client_id.is_some()
+ && message
+ .content
+ .source_blocks()
+ .iter()
+ .all(acp_thread::content::can_convert_to_v1)
+ }
+
/// Returns the currently active editor, either for a message that is being
/// edited or the editor for a new message.
pub(crate) fn active_editor(&self, cx: &App) -> Entity<MessageEditor> {
@@ -1284,12 +1303,7 @@ impl ThreadView {
});
}
ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::Focus) => {
- if let Some(AgentThreadEntry::UserMessage(user_message)) =
- self.thread.read(cx).entries().get(event.entry_index)
- && self.thread.read(cx).supports_truncate(cx)
- && user_message.client_id.is_some()
- && !self.is_subagent()
- {
+ if self.can_edit_user_message(event.entry_index, cx) {
self.editing_message = Some(event.entry_index);
cx.notify();
}
@@ -1297,9 +1311,7 @@ impl ThreadView {
ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::LostFocus) => {
if let Some(AgentThreadEntry::UserMessage(user_message)) =
self.thread.read(cx).entries().get(event.entry_index)
- && self.thread.read(cx).supports_truncate(cx)
- && user_message.client_id.is_some()
- && !self.is_subagent()
+ && self.can_edit_user_message(event.entry_index, cx)
{
if editor.read(cx).text(cx).as_str() == user_message.content.to_markdown(cx) {
self.editing_message = None;
@@ -1309,7 +1321,7 @@ impl ThreadView {
}
ViewEvent::MessageEditorEvent(_editor, MessageEditorEvent::SendImmediately) => {}
ViewEvent::MessageEditorEvent(editor, MessageEditorEvent::Send) => {
- if !self.is_subagent() {
+ if self.can_edit_user_message(event.entry_index, cx) {
self.regenerate(event.entry_index, editor.clone(), window, cx);
}
}
@@ -1581,18 +1593,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::ContentBlock::Text(text_content)) = content.first_mut() {
+ if let Some(acp_v1::ContentBlock::Text(text_content)) = content.first_mut() {
text_content.text = strip_leading_command(&text_content.text, &command_name);
}
if matches!(
content.first(),
- Some(acp::ContentBlock::Text(text)) if text.text.trim().is_empty()
+ Some(acp_v1::ContentBlock::Text(text)) if text.text.trim().is_empty()
) {
content.remove(0);
}
let command_block =
- acp::ContentBlock::Text(acp::TextContent::new(format!("/{command_name}")));
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new(format!("/{command_name}")));
this.update_in(cx, |this, window, cx| {
// Queue the remainder first, then start the command turn; the
@@ -1656,7 +1668,9 @@ impl ThreadView {
pub fn send_content(
&mut self,
- contents_task: Task<anyhow::Result<Option<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>>>,
+ contents_task: Task<
+ anyhow::Result<Option<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>>,
+ >,
is_native_command: bool,
window: &mut Window,
cx: &mut Context<Self>,
@@ -1716,8 +1730,8 @@ impl ThreadView {
let text: String = contents
.iter()
.filter_map(|block| match block {
- acp::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
- acp::ContentBlock::ResourceLink(resource_link) => {
+ acp_v1::ContentBlock::Text(text_content) => Some(text_content.text.clone()),
+ acp_v1::ContentBlock::ResourceLink(resource_link) => {
Some(format!("@{}", resource_link.name))
}
_ => None,
@@ -2008,7 +2022,7 @@ impl ThreadView {
window: &mut Window,
cx: &mut Context<Self>,
) {
- if self.is_loading_contents {
+ if self.is_loading_contents || !self.can_edit_user_message(entry_ix, cx) {
return;
}
let thread = self.thread.clone();
@@ -2058,6 +2072,16 @@ impl ThreadView {
.update(cx, |thread, cx| thread.rewind(client_id, cx))
.await?;
this.update_in(cx, |thread, window, cx| {
+ // Rewind can outlive a source update that replaces the editor with a fallback.
+ if message_editor.read(cx).editor().read(cx).read_only(cx) {
+ thread.handle_thread_error(
+ anyhow!(
+ "The conversation was rewound, but the message became read-only and was not resent."
+ ),
+ cx,
+ );
+ return;
+ }
cx.emit(AcpThreadViewEvent::Interacted);
thread.send_impl(message_editor, window, cx);
thread.activation_focus_handle(cx).focus(window, cx);
@@ -2105,7 +2129,7 @@ impl ThreadView {
pub fn add_to_queue(
&mut self,
- content: Vec<acp::ContentBlock>,
+ content: Vec<acp_v1::ContentBlock>,
tracked_buffers: Vec<Entity<Buffer>>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -2274,7 +2298,7 @@ impl ThreadView {
let is_native_command = content
.first()
.and_then(|block| match block {
- acp::ContentBlock::Text(text) => Some(text.text.as_str()),
+ acp_v1::ContentBlock::Text(text) => Some(text.text.as_str()),
_ => None,
})
.and_then(|text| {
@@ -2470,7 +2494,11 @@ impl ThreadView {
.get(index)
.and_then(|e| e.user_message())
{
- editor.set_message(user_message.content.source_blocks().to_vec(), window, cx);
+ editor.set_source_message(
+ user_message.content.source_blocks().to_vec(),
+ window,
+ cx,
+ );
}
})
};
@@ -2480,8 +2508,8 @@ impl ThreadView {
pub fn authorize_tool_call(
&mut self,
- session_id: acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
outcome: SelectedPermissionOutcome,
window: &mut Window,
cx: &mut Context<Self>,
@@ -2503,7 +2531,7 @@ impl ThreadView {
if self.pending_allow_blocked_by_confusables(cx) {
return;
}
- self.authorize_pending_tool_call(acp::PermissionOptionKind::AllowAlways, window, cx);
+ self.authorize_pending_tool_call(acp_v1::PermissionOptionKind::AllowAlways, window, cx);
}
pub fn allow_once(&mut self, _: &AllowOnce, window: &mut Window, cx: &mut Context<Self>) {
@@ -2540,7 +2568,7 @@ impl ThreadView {
pub fn authorize_pending_tool_call(
&mut self,
- kind: acp::PermissionOptionKind,
+ kind: acp_v1::PermissionOptionKind,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<()> {
@@ -2594,7 +2622,7 @@ impl ThreadView {
elicitation_id.clone(),
matches!(elicitation.status, ElicitationStatus::Pending { .. }),
match &elicitation.request.mode {
- acp::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
+ acp_v1::ElicitationMode::Form(mode) => Some(mode.requested_schema.clone()),
_ => None,
},
)
@@ -2644,7 +2672,7 @@ impl ThreadView {
};
match mode {
- acp::ElicitationMode::Form(mode) => {
+ acp_v1::ElicitationMode::Form(mode) => {
let Some(state) = self.elicitation_form_states.get_mut(&elicitation_id) else {
return;
};
@@ -2674,9 +2702,9 @@ impl ThreadView {
Ok(content) => {
this.respond_to_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(
- acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new().content(content),
+ acp_v1::CreateElicitationResponse::new(
+ acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new().content(content),
),
),
cx,
@@ -2696,11 +2724,11 @@ impl ThreadView {
})
.detach();
}
- acp::ElicitationMode::Url(_) => {
+ acp_v1::ElicitationMode::Url(_) => {
self.respond_to_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Accept(
- acp::ElicitationAcceptAction::new(),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Accept(
+ acp_v1::ElicitationAcceptAction::new(),
)),
cx,
);
@@ -2717,7 +2745,7 @@ impl ThreadView {
) {
self.respond_to_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Decline),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Decline),
cx,
);
}
@@ -2730,7 +2758,7 @@ impl ThreadView {
) {
self.respond_to_elicitation(
elicitation_id,
- acp::CreateElicitationResponse::new(acp::ElicitationAction::Cancel),
+ acp_v1::CreateElicitationResponse::new(acp_v1::ElicitationAction::Cancel),
cx,
);
}
@@ -2751,7 +2779,7 @@ impl ThreadView {
fn respond_to_elicitation(
&mut self,
elicitation_id: ElicitationEntryId,
- response: acp::CreateElicitationResponse,
+ response: acp_v1::CreateElicitationResponse,
cx: &mut Context<Self>,
) {
let session_id = self.session_id.clone();
@@ -2768,14 +2796,14 @@ impl ThreadView {
window: &mut Window,
cx: &mut Context<Self>,
) {
- let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
- let option_id = acp::PermissionOptionId::new(action.option_id.clone());
+ let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());
+ let option_id = acp_v1::PermissionOptionId::new(action.option_id.clone());
let option_kind = match action.option_kind.as_str() {
- "AllowOnce" => acp::PermissionOptionKind::AllowOnce,
- "AllowAlways" => acp::PermissionOptionKind::AllowAlways,
- "RejectOnce" => acp::PermissionOptionKind::RejectOnce,
- "RejectAlways" => acp::PermissionOptionKind::RejectAlways,
- _ => acp::PermissionOptionKind::AllowOnce,
+ "AllowOnce" => acp_v1::PermissionOptionKind::AllowOnce,
+ "AllowAlways" => acp_v1::PermissionOptionKind::AllowAlways,
+ "RejectOnce" => acp_v1::PermissionOptionKind::RejectOnce,
+ "RejectAlways" => acp_v1::PermissionOptionKind::RejectAlways,
+ _ => acp_v1::PermissionOptionKind::AllowOnce,
};
let session_id = self.thread.read(cx).session_id().clone();
@@ -2794,7 +2822,7 @@ impl ThreadView {
_window: &mut Window,
cx: &mut Context<Self>,
) {
- let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
+ let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());
self.permission_selections
.insert(tool_call_id, PermissionSelection::Choice(action.index));
@@ -2807,7 +2835,7 @@ impl ThreadView {
_window: &mut Window,
cx: &mut Context<Self>,
) {
- let tool_call_id = acp::ToolCallId::new(action.tool_call_id.clone());
+ let tool_call_id = acp_v1::ToolCallId::new(action.tool_call_id.clone());
match self.permission_selections.get_mut(&tool_call_id) {
Some(PermissionSelection::SelectedPatterns(checked)) => {
@@ -2868,8 +2896,8 @@ impl ThreadView {
fn authorize_with_granularity(
&mut self,
- session_id: acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
is_allow: bool,
window: &mut Window,
cx: &mut Context<Self>,
@@ -3425,7 +3453,7 @@ impl ThreadView {
fn collect_subagent_items_for_sessions(
entries: &[AgentThreadEntry],
- awaiting_session_ids: &[acp::SessionId],
+ awaiting_session_ids: &[acp_v1::SessionId],
cx: &App,
) -> Vec<(SharedString, usize)> {
let tool_calls_by_session: HashMap<_, _> = entries
@@ -3827,20 +3855,20 @@ impl ThreadView {
.text_xs()
.text_color(cx.theme().colors().text_muted)
.child(match entry.status {
- acp::PlanEntryStatus::InProgress => {
+ acp_v1::PlanEntryStatus::InProgress => {
Icon::new(IconName::TodoProgress)
.size(IconSize::Small)
.color(Color::Accent)
.with_rotate_animation(2)
.into_any_element()
}
- acp::PlanEntryStatus::Completed => {
+ acp_v1::PlanEntryStatus::Completed => {
Icon::new(IconName::TodoComplete)
.size(IconSize::Small)
.color(Color::Success)
.into_any_element()
}
- acp::PlanEntryStatus::Pending | _ => {
+ acp_v1::PlanEntryStatus::Pending | _ => {
Icon::new(IconName::TodoPending)
.size(IconSize::Small)
.color(Color::Muted)
@@ -6121,8 +6149,15 @@ impl ThreadView {
.is_some_and(|checkpoint| checkpoint.show);
let is_subagent = self.is_subagent();
- let can_rewind = self.thread.read(cx).supports_truncate(cx);
- let is_editable = can_rewind && message.client_id.is_some() && !is_subagent;
+ let can_restore_checkpoint = self.thread.read(cx).supports_truncate(cx)
+ && message.client_id.is_some()
+ && !is_subagent;
+ let source_is_representable = message
+ .content
+ .source_blocks()
+ .iter()
+ .all(acp_thread::content::can_convert_to_v1);
+ let is_editable = can_restore_checkpoint && source_is_representable;
let agent_name = if is_subagent {
"subagents".into()
} else {
@@ -6142,7 +6177,7 @@ impl ThreadView {
.px_2()
.gap_1p5()
.w_full()
- .when(is_editable && has_checkpoint_button, |this| {
+ .when(can_restore_checkpoint && has_checkpoint_button, |this| {
this.children(message.client_id.clone().map(|client_id| {
h_flex()
.px_3()
@@ -6262,10 +6297,14 @@ impl ThreadView {
.child(Label::new("Unavailable Editing"))
.child(
div().max_w_64().child(
- Label::new(format!(
- "Editing previous messages is not available for {} yet.",
- agent_name
- ))
+ Label::new(if source_is_representable {
+ format!(
+ "Editing previous messages is not available for {} yet.",
+ agent_name
+ )
+ } else {
+ "This message contains unsupported content and cannot be edited or resent.".to_string()
+ })
.size(LabelSize::Small)
.color(Color::Muted),
),
@@ -7705,7 +7744,7 @@ impl ThreadView {
ToolCallStatus::InProgress | ToolCallStatus::Pending
) =>
{
- if matches!(tool_call.kind, acp::ToolKind::Execute) {
+ if matches!(tool_call.kind, acp_v1::ToolKind::Execute) {
has_running_terminal_call = true;
} else {
return false;
@@ -7790,7 +7829,7 @@ impl ThreadView {
fn render_terminal_tool_call(
&self,
- active_session_id: &acp::SessionId,
+ active_session_id: &acp_v1::SessionId,
entry_ix: usize,
terminal: &Entity<acp_thread::Terminal>,
tool_call: &ToolCall,
@@ -8049,8 +8088,8 @@ impl ThreadView {
fn is_first_tool_call(
&self,
- active_session_id: &acp::SessionId,
- tool_call_id: &acp::ToolCallId,
+ active_session_id: &acp_v1::SessionId,
+ tool_call_id: &acp_v1::ToolCallId,
cx: &App,
) -> bool {
self.conversation
@@ -8064,7 +8103,7 @@ impl ThreadView {
fn render_any_tool_call(
&self,
- active_session_id: &acp::SessionId,
+ active_session_id: &acp_v1::SessionId,
entry_ix: usize,
tool_call: &ToolCall,
focus_handle: &FocusHandle,
@@ -8131,7 +8170,7 @@ impl ThreadView {
fn render_tool_call(
&self,
- active_session_id: &acp::SessionId,
+ active_session_id: &acp_v1::SessionId,
entry_ix: usize,
tool_call: &ToolCall,
focus_handle: &FocusHandle,
@@ -8151,10 +8190,10 @@ impl ThreadView {
tool_call.status,
ToolCallStatus::WaitingForConfirmation { .. }
);
- let is_terminal_tool = matches!(tool_call.kind, acp::ToolKind::Execute);
+ let is_terminal_tool = matches!(tool_call.kind, acp_v1::ToolKind::Execute);
let is_edit =
- matches!(tool_call.kind, acp::ToolKind::Edit) || tool_call.diffs().next().is_some();
+ matches!(tool_call.kind, acp_v1::ToolKind::Edit) || tool_call.diffs().next().is_some();
let is_cancelled_edit = is_edit && matches!(tool_call.status, ToolCallStatus::Canceled);
let (has_revealed_diff, tool_call_output_focus, tool_call_output_focus_handle) = tool_call
@@ -8673,7 +8712,7 @@ impl ThreadView {
fn render_sandbox_authorization_details(
&self,
entry_ix: usize,
- tool_call_id: &acp::ToolCallId,
+ tool_call_id: &acp_v1::ToolCallId,
details: &SandboxAuthorizationDetails,
window: &Window,
cx: &Context<Self>,
@@ -9023,7 +9062,7 @@ impl ThreadView {
/// allow buttons. See [`Self::sandbox_confusables_block_allow`].
fn render_sandbox_confusable_warning(
&self,
- tool_call_id: &acp::ToolCallId,
+ tool_call_id: &acp_v1::ToolCallId,
findings: &[(String, Vec<unicode_confusables::SuspiciousChar>)],
window: &Window,
cx: &Context<Self>,
@@ -9329,11 +9368,11 @@ impl ThreadView {
fn render_permission_buttons(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
is_first: bool,
options: &PermissionOptions,
entry_ix: usize,
- tool_call_id: acp::ToolCallId,
+ tool_call_id: acp_v1::ToolCallId,
focus_handle: &FocusHandle,
// When true, the "allow" choices are disabled (e.g. an unacknowledged
// surprising-Unicode warning is showing). "Deny"/"Retry" stay enabled.
@@ -9386,8 +9425,8 @@ impl ThreadView {
choices: &[PermissionOptionChoice],
patterns: Option<(&[PermissionPattern], &str)>,
entry_ix: usize,
- session_id: acp::SessionId,
- tool_call_id: acp::ToolCallId,
+ session_id: acp_v1::SessionId,
+ tool_call_id: acp_v1::ToolCallId,
focus_handle: &FocusHandle,
allow_disabled: bool,
cx: &Context<Self>,
@@ -9514,7 +9553,7 @@ impl ThreadView {
choices: &[PermissionOptionChoice],
current_label: SharedString,
entry_ix: usize,
- tool_call_id: acp::ToolCallId,
+ tool_call_id: acp_v1::ToolCallId,
selected_index: usize,
is_first: bool,
cx: &Context<Self>,
@@ -9589,7 +9628,7 @@ impl ThreadView {
_tool_name: &str,
current_label: SharedString,
entry_ix: usize,
- tool_call_id: acp::ToolCallId,
+ tool_call_id: acp_v1::ToolCallId,
is_first: bool,
cx: &Context<Self>,
) -> AnyElement {
@@ -9771,16 +9810,16 @@ impl ThreadView {
fn render_permission_buttons_flat(
&self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
is_first: bool,
- options: &[acp::PermissionOption],
+ options: &[acp_v1::PermissionOption],
entry_ix: usize,
- tool_call_id: acp::ToolCallId,
+ tool_call_id: acp_v1::ToolCallId,
focus_handle: &FocusHandle,
allow_disabled: bool,
cx: &Context<Self>,
) -> Div {
- let mut seen_kinds: ArrayVec<acp::PermissionOptionKind, 3, u8> = ArrayVec::new();
+ let mut seen_kinds: ArrayVec<acp_v1::PermissionOptionKind, 3, u8> = ArrayVec::new();
div()
.p_1()
@@ -9808,13 +9847,13 @@ impl ThreadView {
)
} else {
match option.kind {
- acp::PermissionOptionKind::AllowOnce => (
+ acp_v1::PermissionOptionKind::AllowOnce => (
Icon::new(IconName::Check)
.size(IconSize::XSmall)
.color(Color::Success),
Some(&AllowOnce as &dyn Action),
),
- acp::PermissionOptionKind::AllowAlways => (
+ acp_v1::PermissionOptionKind::AllowAlways => (
Icon::new(IconName::CheckDouble)
.size(IconSize::XSmall)
.color(Color::Success),
@@ -9826,13 +9865,13 @@ impl ThreadView {
Some(&AllowAlways as &dyn Action)
},
),
- acp::PermissionOptionKind::RejectOnce => (
+ acp_v1::PermissionOptionKind::RejectOnce => (
Icon::new(IconName::Close)
.size(IconSize::XSmall)
.color(Color::Error),
Some(&RejectOnce as &dyn Action),
),
- acp::PermissionOptionKind::RejectAlways | _ => (
+ acp_v1::PermissionOptionKind::RejectAlways | _ => (
Icon::new(IconName::Close)
.size(IconSize::XSmall)
.color(Color::Error),
@@ -9845,8 +9884,8 @@ impl ThreadView {
// warning is unacknowledged; "deny"/"retry" stay enabled.
let is_allow = matches!(
option.kind,
- acp::PermissionOptionKind::AllowOnce
- | acp::PermissionOptionKind::AllowAlways
+ acp_v1::PermissionOptionKind::AllowOnce
+ | acp_v1::PermissionOptionKind::AllowAlways
) && !is_retry;
let disabled = allow_disabled && is_allow;
@@ -9952,7 +9991,7 @@ impl ThreadView {
cx: &Context<Self>,
) -> Div {
let has_location = tool_call.locations.len() == 1;
- let is_file = tool_call.kind == acp::ToolKind::Edit && has_location;
+ let is_file = tool_call.kind == acp_v1::ToolKind::Edit && has_location;
let is_subagent_tool_call = tool_call.is_subagent();
let file_icon = if has_location {
@@ -9991,16 +10030,16 @@ impl ThreadView {
.into_any_element()
} else {
Icon::new(match tool_call.kind {
- acp::ToolKind::Read => IconName::ToolSearch,
- acp::ToolKind::Edit => IconName::ToolPencil,
- acp::ToolKind::Delete => IconName::ToolDeleteFile,
- acp::ToolKind::Move => IconName::ArrowRightLeft,
- acp::ToolKind::Search => IconName::ToolSearch,
- acp::ToolKind::Execute => IconName::ToolTerminal,
- acp::ToolKind::Think => IconName::ToolThink,
- acp::ToolKind::Fetch => IconName::ToolWeb,
- acp::ToolKind::SwitchMode => IconName::ArrowRightLeft,
- acp::ToolKind::Other | _ => IconName::ToolHammer,
+ acp_v1::ToolKind::Read => IconName::ToolSearch,
+ acp_v1::ToolKind::Edit => IconName::ToolPencil,
+ acp_v1::ToolKind::Delete => IconName::ToolDeleteFile,
+ acp_v1::ToolKind::Move => IconName::ArrowRightLeft,
+ acp_v1::ToolKind::Search => IconName::ToolSearch,
+ acp_v1::ToolKind::Execute => IconName::ToolTerminal,
+ acp_v1::ToolKind::Think => IconName::ToolThink,
+ acp_v1::ToolKind::Fetch => IconName::ToolWeb,
+ acp_v1::ToolKind::SwitchMode => IconName::ArrowRightLeft,
+ acp_v1::ToolKind::Other | _ => IconName::ToolHammer,
})
.size(IconSize::Small)
.color(Color::Muted)
@@ -10171,7 +10210,7 @@ impl ThreadView {
fn render_tool_call_content(
&self,
- session_id: &acp::SessionId,
+ session_id: &acp_v1::SessionId,
entry_ix: usize,
content: &ToolCallContent,
context_ix: usize,
@@ -10255,7 +10294,7 @@ impl ThreadView {
fn render_embedded_resource_output(
&self,
- resource: &acp::EmbeddedResource,
+ resource: &acp_v2::EmbeddedResource,
context_ix: usize,
card_layout: bool,
cx: &Context<Self>,
@@ -10279,10 +10318,10 @@ impl ThreadView {
.into_any_element()
}
- fn render_embedded_resource_label(&self, resource: &acp::EmbeddedResource) -> AnyElement {
+ fn render_embedded_resource_label(&self, resource: &acp_v2::EmbeddedResource) -> AnyElement {
let uri = match &resource.resource {
- acp::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),
- acp::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),
+ acp_v2::EmbeddedResourceResource::BlobResourceContents(blob) => blob.uri.as_str(),
+ acp_v2::EmbeddedResourceResource::TextResourceContents(text) => text.uri.as_str(),
_ => "",
};
if uri.is_empty() {
@@ -10297,7 +10336,7 @@ impl ThreadView {
fn render_resource_link(
&self,
- resource_link: &acp::ResourceLink,
+ resource_link: &acp_v2::ResourceLink,
cx: &Context<Self>,
) -> AnyElement {
let uri: SharedString = resource_link.uri.clone().into();
@@ -10488,7 +10527,7 @@ impl ThreadView {
&self,
entry_ix: usize,
image: Arc<gpui::Image>,
- location: Option<acp::ToolCallLocation>,
+ location: Option<acp_v1::ToolCallLocation>,
card_layout: bool,
cx: &Context<Self>,
) -> AnyElement {
@@ -10527,10 +10566,10 @@ impl ThreadView {
fn render_subagent_tool_call(
&self,
- active_session_id: &acp::SessionId,
+ active_session_id: &acp_v1::SessionId,
entry_ix: usize,
tool_call: &ToolCall,
- subagent_session_id: Option<acp::SessionId>,
+ subagent_session_id: Option<acp_v1::SessionId>,
focus_handle: &FocusHandle,
window: &Window,
cx: &Context<Self>,
@@ -10557,7 +10596,7 @@ impl ThreadView {
fn render_subagent_card(
&self,
- active_session_id: &acp::SessionId,
+ active_session_id: &acp_v1::SessionId,
entry_ix: usize,
thread_view: Option<&Entity<ThreadView>>,
tool_call: &ToolCall,
@@ -12369,7 +12408,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp::SessionConfigOptionCategory::ThoughtLevel,
+ acp_v1::SessionConfigOptionCategory::ThoughtLevel,
false,
cx,
)
@@ -12388,7 +12427,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp::SessionConfigOptionCategory::ThoughtLevel,
+ acp_v1::SessionConfigOptionCategory::ThoughtLevel,
window,
cx,
)
@@ -12436,7 +12475,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp::SessionConfigOptionCategory::Mode,
+ acp_v1::SessionConfigOptionCategory::Mode,
window,
cx,
)
@@ -12459,7 +12498,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp::SessionConfigOptionCategory::Mode,
+ acp_v1::SessionConfigOptionCategory::Mode,
false,
cx,
)
@@ -12486,7 +12525,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.toggle_category_picker(
- acp::SessionConfigOptionCategory::Model,
+ acp_v1::SessionConfigOptionCategory::Model,
window,
cx,
)
@@ -12508,7 +12547,7 @@ impl Render for ThreadView {
if let Some(config_options_view) = this.config_options_view.clone() {
let handled = config_options_view.update(cx, |view, cx| {
view.cycle_category_option(
- acp::SessionConfigOptionCategory::Model,
+ acp_v1::SessionConfigOptionCategory::Model,
true,
cx,
)
@@ -12717,7 +12756,7 @@ pub(crate) fn open_link(
/// command is never echoed as a user message (see `send_command_queueing_remainder`).
fn leading_native_command(
text: &str,
- available_commands: &[acp::AvailableCommand],
+ available_commands: &[acp_v1::AvailableCommand],
) -> Option<String> {
let rest = text.trim_start().strip_prefix('/')?;
let name_end = rest.find(char::is_whitespace).unwrap_or(rest.len());
@@ -12777,14 +12816,14 @@ mod tests {
}
}
- fn native_command(name: &str) -> acp::AvailableCommand {
- acp::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(
+ fn native_command(name: &str) -> acp_v1::AvailableCommand {
+ acp_v1::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(
acp_thread::CommandCategory::Native,
))
}
- fn mcp_command(name: &str) -> acp::AvailableCommand {
- acp::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(
+ fn mcp_command(name: &str) -> acp_v1::AvailableCommand {
+ acp_v1::AvailableCommand::new(name, "").meta(acp_thread::meta_with_command_category(
acp_thread::CommandCategory::Mcp,
))
}
diff --git a/crates/agent_ui/src/entry_view_state.rs b/crates/agent_ui/src/entry_view_state.rs
index 63a374ad1aa..91a33ee8a53 100644
--- a/crates/agent_ui/src/entry_view_state.rs
+++ b/crates/agent_ui/src/entry_view_state.rs
@@ -2,7 +2,7 @@ use std::{ops::Range, sync::Arc};
use acp_thread::{AcpThread, AgentThreadEntry, AssistantMessageChunk};
use agent::ThreadStore;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v1 as acp_v1;
use agent_settings::AgentSettings;
use collections::{HashMap, HashSet};
use editor::{
@@ -47,7 +47,7 @@ pub struct EntryViewState {
auto_expanded_thinking_block: Option<(usize, usize)>,
user_toggled_thinking_blocks: HashSet<(usize, usize)>,
expanded_compactions: HashSet<usize>,
- expanded_tool_calls: HashSet<acp::ToolCallId>,
+ expanded_tool_calls: HashSet<acp_v1::ToolCallId>,
}
impl EntryViewState {
@@ -73,19 +73,19 @@ impl EntryViewState {
}
}
- pub(crate) fn is_tool_call_expanded(&self, tool_call_id: &acp::ToolCallId) -> bool {
+ pub(crate) fn is_tool_call_expanded(&self, tool_call_id: &acp_v1::ToolCallId) -> bool {
self.expanded_tool_calls.contains(tool_call_id)
}
- pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp::ToolCallId) {
+ pub(crate) fn expand_tool_call(&mut self, tool_call_id: acp_v1::ToolCallId) {
self.expanded_tool_calls.insert(tool_call_id);
}
- pub(crate) fn collapse_tool_call(&mut self, tool_call_id: &acp::ToolCallId) {
+ pub(crate) fn collapse_tool_call(&mut self, tool_call_id: &acp_v1::ToolCallId) {
self.expanded_tool_calls.remove(tool_call_id);
}
- pub(crate) fn toggle_tool_call_expansion(&mut self, tool_call_id: &acp::ToolCallId) {
+ pub(crate) fn toggle_tool_call_expansion(&mut self, tool_call_id: &acp_v1::ToolCallId) {
if !self.expanded_tool_calls.remove(tool_call_id) {
self.expanded_tool_calls.insert(tool_call_id.clone());
}
@@ -240,16 +240,26 @@ impl EntryViewState {
let can_rewind = thread.read(cx).supports_truncate(cx);
let has_client_id = message.client_id.is_some();
let is_subagent = thread.read(cx).parent_session_id().is_some();
- let chunks = message.content.source_blocks().to_vec();
+ let source_blocks = message.content.source_blocks();
+ let source_is_representable = source_blocks
+ .iter()
+ .all(acp_thread::content::can_convert_to_v1);
+ let is_editable =
+ can_rewind && has_client_id && !is_subagent && source_is_representable;
if let Some(Entry::UserMessage(editor)) = self.entries.get_mut(index) {
- if !editor.focus_handle(cx).is_focused(window) {
- // Only update if we are not editing.
- // If we are, cancelling the edit will set the message to the newest content.
+ // Keep focused drafts unless newly unsupported content makes
+ // the message read-only and needs its fallback shown.
+ let refreshed_source = (!source_is_representable
+ || !editor.focus_handle(cx).is_focused(window))
+ .then(|| source_blocks.to_vec());
+ editor.update(cx, |editor, cx| editor.set_read_only(!is_editable, cx));
+ if let Some(source_blocks) = refreshed_source {
editor.update(cx, |editor, cx| {
- editor.set_message(chunks, window, cx);
+ editor.set_source_message(source_blocks, window, cx);
});
}
} else {
+ let source_blocks = source_blocks.to_vec();
let message_editor = cx.new(|cx| {
let mut editor = MessageEditor::new(
self.workspace.clone(),
@@ -265,10 +275,10 @@ impl EntryViewState {
window,
cx,
);
- if !can_rewind || !has_client_id || is_subagent {
+ if !is_editable {
editor.set_read_only(true, cx);
}
- editor.set_message(chunks, window, cx);
+ editor.set_source_message(source_blocks, window, cx);
editor
});
cx.subscribe(&message_editor, move |_, editor, event, cx| {
@@ -491,9 +501,9 @@ pub struct EntryViewEvent {
}
pub enum ViewEvent {
- NewDiff(acp::ToolCallId),
- NewTerminal(acp::ToolCallId),
- TerminalMovedToBackground(acp::ToolCallId),
+ NewDiff(acp_v1::ToolCallId),
+ NewTerminal(acp_v1::ToolCallId),
+ TerminalMovedToBackground(acp_v1::ToolCallId),
MessageEditorEvent(Entity<MessageEditor>, MessageEditorEvent),
OpenDiffLocation {
path: String,
@@ -722,7 +732,7 @@ mod tests {
use std::sync::Arc;
use acp_thread::{AgentConnection, StubAgentConnection};
- use agent_client_protocol::schema::v1 as acp;
+ use agent_client_protocol::schema::v1 as acp_v1;
use buffer_diff::{DiffHunkStatus, DiffHunkStatusKind};
use editor::RowInfo;
use fs::FakeFs;
@@ -773,10 +783,10 @@ mod tests {
cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace = multi_workspace.read_with(cx, |mw, _| mw.workspace().clone());
- let tool_call = acp::ToolCall::new("tool", "Tool call")
- .status(acp::ToolCallStatus::InProgress)
- .content(vec![acp::ToolCallContent::Diff(
- acp::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),
+ let tool_call = acp_v1::ToolCall::new("tool", "Tool call")
+ .status(acp_v1::ToolCallStatus::InProgress)
+ .content(vec![acp_v1::ToolCallContent::Diff(
+ acp_v1::Diff::new("/project/hello.txt", "hello world").old_text("hi world"),
)]);
let connection = Rc::new(StubAgentConnection::new());
let thread = cx
@@ -792,7 +802,7 @@ mod tests {
let session_id = thread.update(cx, |thread, _| thread.session_id().clone());
cx.update(|_, cx| {
- connection.send_update(session_id, acp::SessionUpdate::ToolCall(tool_call), cx)
+ connection.send_update(session_id, acp_v1::SessionUpdate::ToolCall(tool_call), cx)
});
let thread_store = None;
@@ -889,10 +899,10 @@ mod tests {
let _response_task = thread.update(cx, |thread, cx| {
thread
.request_elicitation(
- acp::CreateElicitationRequest::new(
- acp::ElicitationFormMode::new(
- acp::ElicitationSessionScope::new(session_id.clone()),
- acp::ElicitationSchema::new().string("name", true),
+ acp_v1::CreateElicitationRequest::new(
+ acp_v1::ElicitationFormMode::new(
+ acp_v1::ElicitationSessionScope::new(session_id.clone()),
+ acp_v1::ElicitationSchema::new().string("name", true),
),
"Provide a name",
),
@@ -903,8 +913,8 @@ mod tests {
cx.update(|_, cx| {
connection.send_update(
session_id,
- acp::SessionUpdate::AgentMessageChunk(acp::ContentChunk::new(
- acp::ContentBlock::Text(acp::TextContent::new("hello")),
+ acp_v1::SessionUpdate::AgentMessageChunk(acp_v1::ContentChunk::new(
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("hello")),
)),
cx,
);
diff --git a/crates/agent_ui/src/message_editor.rs b/crates/agent_ui/src/message_editor.rs
index fe10a36cb95..1f05167adaf 100644
--- a/crates/agent_ui/src/message_editor.rs
+++ b/crates/agent_ui/src/message_editor.rs
@@ -11,7 +11,7 @@ use crate::{
};
use acp_thread::MentionUri;
use agent::ThreadStore;
-use agent_client_protocol::schema::v1 as acp;
+use agent_client_protocol::schema::v1 as acp_v1;
use anyhow::{Result, anyhow};
use base64::Engine as _;
use editor::{
@@ -47,15 +47,15 @@ use zed_actions::agent::{Chat, PasteRaw};
#[derive(Default)]
pub struct SessionCapabilities {
- prompt_capabilities: acp::PromptCapabilities,
- available_commands: Vec<acp::AvailableCommand>,
+ prompt_capabilities: acp_v1::PromptCapabilities,
+ available_commands: Vec<acp_v1::AvailableCommand>,
available_skills: Vec<AvailableSkill>,
}
impl SessionCapabilities {
pub fn new(
- prompt_capabilities: acp::PromptCapabilities,
- available_commands: Vec<acp::AvailableCommand>,
+ prompt_capabilities: acp_v1::PromptCapabilities,
+ available_commands: Vec<acp_v1::AvailableCommand>,
available_skills: Vec<AvailableSkill>,
) -> Self {
Self {
@@ -66,8 +66,8 @@ impl SessionCapabilities {
}
pub fn from_acp_commands(
- prompt_capabilities: acp::PromptCapabilities,
- available_commands: Vec<acp::AvailableCommand>,
+ prompt_capabilities: acp_v1::PromptCapabilities,
+ available_commands: Vec<acp_v1::AvailableCommand>,
) -> Self {
Self::new(prompt_capabilities, available_commands, Vec::new())
}
@@ -80,7 +80,7 @@ impl SessionCapabilities {
self.prompt_capabilities.embedded_context
}
- pub fn available_commands(&self) -> &[acp::AvailableCommand] {
+ pub fn available_commands(&self) -> &[acp_v1::AvailableCommand] {
&self.available_commands
}
@@ -125,11 +125,11 @@ impl SessionCapabilities {
self.available_skills.clone()
}
- pub fn set_prompt_capabilities(&mut self, prompt_capabilities: acp::PromptCapabilities) {
+ pub fn set_prompt_capabilities(&mut self, prompt_capabilities: acp_v1::PromptCapabilities) {
self.prompt_capabilities = prompt_capabilities;
}
- pub fn set_available_commands(&mut self, available_commands: Vec<acp::AvailableCommand>) {
+ pub fn set_available_commands(&mut self, available_commands: Vec<acp_v1::AvailableCommand>) {
self.available_commands = available_commands;
}
@@ -643,7 +643,7 @@ impl MessageEditor {
.iter()
.find(|available_command| available_command.name == command_name)?;
- let acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput {
+ let acp_v1::AvailableCommandInput::Unstructured(acp_v1::UnstructuredCommandInput {
mut hint,
..
}) = available_command.input.clone()?
@@ -676,7 +676,7 @@ impl MessageEditor {
pub fn insert_thread_summary(
&mut self,
- session_id: acp::SessionId,
+ session_id: acp_v1::SessionId,
title: Option<SharedString>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -750,7 +750,7 @@ impl MessageEditor {
fn validate_slash_commands(
text: &str,
- available_commands: &[acp::AvailableCommand],
+ available_commands: &[acp_v1::AvailableCommand],
available_skills: &[AvailableSkill],
agent_id: &AgentId,
) -> Result<()> {
@@ -824,7 +824,7 @@ impl MessageEditor {
/// when both a global and a project-local skill share a name.
/// Globals carry an empty scope and so render as `/:<name>`.
fn format_available_commands(
- commands: &[acp::AvailableCommand],
+ commands: &[acp_v1::AvailableCommand],
skills: &[AvailableSkill],
) -> String {
if commands.is_empty() && skills.is_empty() {
@@ -842,7 +842,7 @@ impl MessageEditor {
&self,
full_mention_content: bool,
cx: &mut Context<Self>,
- ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
+ ) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
let text = self.editor.read(cx).text(cx);
let (available_commands, available_skills) = {
let session_capabilities = self.session_capabilities.read();
@@ -865,7 +865,10 @@ impl MessageEditor {
})
}
- pub fn draft_contents(&self, cx: &mut Context<Self>) -> Task<Result<Vec<acp::ContentBlock>>> {
+ pub fn draft_contents(
+ &self,
+ cx: &mut Context<Self>,
+ ) -> Task<Result<Vec<acp_v1::ContentBlock>>> {
let build_task = self.build_content_blocks(false, cx);
cx.spawn(async move |_, _cx| {
let (blocks, _tracked_buffers) = build_task.await?;
@@ -877,7 +880,7 @@ impl MessageEditor {
&self,
full_mention_content: bool,
cx: &mut Context<Self>,
- ) -> Task<Result<(Vec<acp::ContentBlock>, Vec<Entity<Buffer>>)>> {
+ ) -> Task<Result<(Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>)>> {
let contents = self
.mention_set
.update(cx, |store, cx| store.contents(full_mention_content, cx));
@@ -908,7 +911,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::ContentBlock> {
+ pub fn draft_content_blocks_snapshot(&self, cx: &App) -> Vec<acp_v1::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);
@@ -1684,7 +1687,7 @@ impl MessageEditor {
pub fn set_message(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -1692,9 +1695,60 @@ impl MessageEditor {
self.insert_message_blocks(message, false, window, cx);
}
+ pub fn set_source_message(
+ &mut self,
+ source_blocks: Vec<agent_client_protocol::schema::v2::ContentBlock>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ use agent_client_protocol::schema::v2::ContentBlock;
+
+ if source_blocks
+ .iter()
+ .all(acp_thread::content::can_convert_to_v1)
+ {
+ match source_blocks
+ .into_iter()
+ .map(acp_thread::content::to_v1)
+ .collect::<Result<Vec<_>, _>>()
+ {
+ Ok(message) => self.set_message(message, window, cx),
+ Err(error) => {
+ log::error!("failed to display representable source message: {error}");
+ self.set_message(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
+ "[Unsupported message content — this message cannot be edited or resent]",
+ ))],
+ window,
+ cx,
+ );
+ }
+ }
+ return;
+ }
+
+ let mut visible = Vec::new();
+ for block in source_blocks {
+ if acp_thread::content::can_convert_to_v1(&block) {
+ match acp_thread::content::to_v1(block) {
+ Ok(block) => visible.push(block),
+ Err(error) => log::error!("failed to display source content: {error}"),
+ }
+ } else if let ContentBlock::Text(text) = block {
+ visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
+ text.text,
+ )));
+ }
+ }
+ visible.push(acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
+ "\n[Unsupported message content — this message cannot be edited or resent]",
+ )));
+ self.set_message(visible, window, cx);
+ }
+
pub fn append_message(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
separator: Option<&str>,
window: &mut Window,
cx: &mut Context<Self>,
@@ -1717,7 +1771,7 @@ impl MessageEditor {
fn insert_message_blocks(
&mut self,
- message: Vec<acp::ContentBlock>,
+ message: Vec<acp_v1::ContentBlock>,
append_to_existing: bool,
window: &mut Window,
cx: &mut Context<Self>,
@@ -1736,11 +1790,11 @@ impl MessageEditor {
for chunk in message {
match chunk {
- acp::ContentBlock::Text(text_content) => {
+ acp_v1::ContentBlock::Text(text_content) => {
append_normalized(&mut text, text_content.text);
}
- acp::ContentBlock::Resource(acp::EmbeddedResource {
- resource: acp::EmbeddedResourceResource::TextResourceContents(resource),
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource {
+ resource: acp_v1::EmbeddedResourceResource::TextResourceContents(resource),
..
}) => {
let Some(mention_uri) = MentionUri::parse(&resource.uri, path_style).log_err()
@@ -1759,7 +1813,7 @@ impl MessageEditor {
},
));
}
- acp::ContentBlock::ResourceLink(resource) => {
+ acp_v1::ContentBlock::ResourceLink(resource) => {
if let Some(mention_uri) =
MentionUri::parse(&resource.uri, path_style).log_err()
{
@@ -1769,7 +1823,7 @@ impl MessageEditor {
mentions.push((start..end, mention_uri, Mention::Link));
}
}
- acp::ContentBlock::Image(acp::ImageContent {
+ acp_v1::ContentBlock::Image(acp_v1::ImageContent {
uri,
data,
mime_type,
@@ -2076,7 +2130,7 @@ fn build_chunks_from_creases(
buffer_snapshot: &MultiBufferSnapshot,
supports_embedded_context: bool,
mut resolve: impl FnMut(&CreaseId) -> Option<(MentionUri, Option<Mention>)>,
-) -> (Vec<acp::ContentBlock>, Vec<Entity<Buffer>>) {
+) -> (Vec<acp_v1::ContentBlock>, Vec<Entity<Buffer>>) {
let mut ix = text
.char_indices()
.find(|(_, c)| !c.is_whitespace())
@@ -2140,7 +2194,7 @@ fn mention_to_content_block(
mention: Option<&Mention>,
supports_embedded_context: bool,
tracked_buffers: &mut Vec<Entity<Buffer>>,
-) -> acp::ContentBlock {
+) -> acp_v1::ContentBlock {
match mention {
Some(Mention::Text {
content,
@@ -2148,20 +2202,23 @@ fn mention_to_content_block(
}) => {
tracked_buffers.extend(mention_tracked_buffers.iter().cloned());
if supports_embedded_context {
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new(content.clone(), uri.to_uri().to_string()),
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(
+ content.clone(),
+ uri.to_uri().to_string(),
+ ),
),
))
} else {
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
uri.name(),
uri.to_uri().to_string(),
))
}
}
- Some(Mention::Image(mention_image)) => acp::ContentBlock::Image(
- acp::ImageContent::new(mention_image.data.clone(), mention_image.format.mime_type())
+ Some(Mention::Image(mention_image)) => acp_v1::ContentBlock::Image(
+ acp_v1::ImageContent::new(mention_image.data.clone(), mention_image.format.mime_type())
.uri(match uri {
MentionUri::File { .. } | MentionUri::PastedImage { .. } => {
Some(uri.to_uri().to_string())
@@ -2172,7 +2229,7 @@ fn mention_to_content_block(
}
}),
),
- _ => acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ _ => acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
uri.name(),
uri.to_uri().to_string(),
)),
@@ -2249,7 +2306,7 @@ mod tests {
use super::PromptLocalCommand;
use acp_thread::MentionUri;
use agent::{ThreadStore, outline};
- use agent_client_protocol::schema::v1 as acp;
+ use agent_client_protocol::schema::v1 as acp_v1;
use base64::Engine as _;
use editor::{
AnchorRangeExt as _, Editor, EditorMode, MultiBufferOffset, SelectionEffects,
@@ -2260,7 +2317,7 @@ mod tests {
use futures::{FutureExt as _, StreamExt as _};
use gpui::{
AppContext, ClipboardEntry, ClipboardItem, Entity, EventEmitter, ExternalPaths,
- FocusHandle, Focusable, Task, TestAppContext, VisualTestContext,
+ FocusHandle, Focusable, Task, TestAppContext, VisualContext, VisualTestContext,
};
use language_model::LanguageModelRegistry;
use lsp::{CompletionContext, CompletionTriggerKind};
@@ -2293,8 +2350,8 @@ mod tests {
warning: None,
};
let session_capabilities = SessionCapabilities::new(
- acp::PromptCapabilities::default(),
- vec![acp::AvailableCommand::new("help", "Get help")],
+ acp_v1::PromptCapabilities::default(),
+ vec![acp_v1::AvailableCommand::new("help", "Get help")],
vec![skill],
);
@@ -2308,17 +2365,17 @@ mod tests {
#[test]
fn test_completion_commands_derive_category_from_meta() {
let session_capabilities = SessionCapabilities::new(
- acp::PromptCapabilities::default(),
+ acp_v1::PromptCapabilities::default(),
vec![
- acp::AvailableCommand::new("compact", "Built-in").meta(
+ acp_v1::AvailableCommand::new("compact", "Built-in").meta(
acp_thread::meta_with_command_category(acp_thread::CommandCategory::Native),
),
- acp::AvailableCommand::new("deploy", "MCP").meta(
+ acp_v1::AvailableCommand::new("deploy", "MCP").meta(
acp_thread::meta_with_command_category(acp_thread::CommandCategory::Mcp),
),
// No category meta: this is how external ACP agents' commands
// arrive, and they should group on their own.
- acp::AvailableCommand::new("help", "External"),
+ acp_v1::AvailableCommand::new("help", "External"),
],
Vec::new(),
);
@@ -2354,7 +2411,7 @@ mod tests {
// `/:<name>`); project-local skills carry their worktree root
// name. The empty-scope encoding means a worktree literally
// named `global` no longer collides with the global source.
- let commands = vec![acp::AvailableCommand::new("help", "Get help")];
+ let commands = vec![acp_v1::AvailableCommand::new("help", "Get help")];
let skills = vec![make_skill("deploy", ""), make_skill("deploy", "zed")];
let no_skills = Vec::new();
@@ -2613,7 +2670,7 @@ mod tests {
.unwrap();
// We don't send a resource link for the deleted crease.
- pretty_assertions::assert_matches!(content.as_slice(), [acp::ContentBlock::Text { .. }]);
+ pretty_assertions::assert_matches!(content.as_slice(), [acp_v1::ContentBlock::Text { .. }]);
}
#[gpui::test]
@@ -2636,7 +2693,7 @@ mod tests {
let project = Project::test(fs.clone(), ["/test".as_ref()], cx).await;
let thread_store = None;
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
- acp::PromptCapabilities::default(),
+ acp_v1::PromptCapabilities::default(),
vec![],
)));
@@ -2682,7 +2739,7 @@ mod tests {
// Now simulate Claude providing its list of available commands (which doesn't include file)
session_capabilities
.write()
- .set_available_commands(vec![acp::AvailableCommand::new("help", "Get help")]);
+ .set_available_commands(vec![acp_v1::AvailableCommand::new("help", "Get help")]);
// Test that unsupported slash commands trigger an error when we have a list of available commands
editor.update_in(cx, |editor, window, cx| {
@@ -2722,7 +2779,7 @@ mod tests {
.unwrap();
assert_eq!(content.len(), 1);
- if let acp::ContentBlock::Text(text) = &content[0] {
+ if let acp_v1::ContentBlock::Text(text) = &content[0] {
assert_eq!(text.text, "Hello Claude!");
} else {
panic!("Expected ContentBlock::Text");
@@ -2740,7 +2797,7 @@ mod tests {
.unwrap();
assert_eq!(content.len(), 1);
- if let acp::ContentBlock::Text(text) = &content[0] {
+ if let acp_v1::ContentBlock::Text(text) = &content[0] {
assert_eq!(text.text, "Check this @");
} else {
panic!("Expected ContentBlock::Text");
@@ -2797,13 +2854,13 @@ mod tests {
let thread_store = None;
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
- acp::PromptCapabilities::default(),
+ acp_v1::PromptCapabilities::default(),
vec![
- acp::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),
- acp::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(
- acp::AvailableCommandInput::Unstructured(acp::UnstructuredCommandInput::new(
- "<name>",
- )),
+ acp_v1::AvailableCommand::new("quick-math", "2 + 2 = 4 - 1 = 3"),
+ acp_v1::AvailableCommand::new("say-hello", "Say hello to whoever you want").input(
+ acp_v1::AvailableCommandInput::Unstructured(
+ acp_v1::UnstructuredCommandInput::new("<name>"),
+ ),
),
],
)));
@@ -2968,7 +3025,7 @@ mod tests {
let mut cx = VisualTestContext::from_window(window.into(), cx);
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
- acp::PromptCapabilities::default(),
+ acp_v1::PromptCapabilities::default(),
Vec::new(),
)));
@@ -3082,8 +3139,8 @@ mod tests {
let mut cx = VisualTestContext::from_window(window.into(), cx);
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
- acp::PromptCapabilities::default(),
- vec![acp::AvailableCommand::new("hello", "Say hello")],
+ acp_v1::PromptCapabilities::default(),
+ vec![acp_v1::AvailableCommand::new("hello", "Say hello")],
)));
// Track every event emitted by the message editor across the
@@ -3236,7 +3293,7 @@ mod tests {
let thread_store = cx.new(|cx| ThreadStore::new(cx));
let session_capabilities = Arc::new(RwLock::new(SessionCapabilities::from_acp_commands(
- acp::PromptCapabilities::default(),
+ acp_v1::PromptCapabilities::default(),
vec![],
)));
@@ -3295,7 +3352,7 @@ mod tests {
message_editor.update(&mut cx, |editor, _cx| {
editor.session_capabilities.write().set_prompt_capabilities(
- acp::PromptCapabilities::new()
+ acp_v1::PromptCapabilities::new()
.image(true)
.audio(true)
.embedded_context(true),
@@ -3750,10 +3807,9 @@ mod tests {
cx,
);
// Enable embedded context so files are actually included
- editor
- .session_capabilities
- .write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true));
+ editor.session_capabilities.write().set_prompt_capabilities(
+ acp_v1::PromptCapabilities::new().embedded_context(true),
+ );
editor
})
});
@@ -3830,7 +3886,7 @@ mod tests {
let thread_store = Some(cx.new(|cx| ThreadStore::new(cx)));
- let session_id = acp::SessionId::new("thread-123");
+ let session_id = acp_v1::SessionId::new("thread-123");
let title = Some("Previous Conversation".into());
let message_editor = cx.update(|window, cx| {
@@ -3918,7 +3974,7 @@ mod tests {
cx,
);
editor.insert_thread_summary(
- acp::SessionId::new("thread-123"),
+ acp_v1::SessionId::new("thread-123"),
Some("Previous Conversation".into()),
window,
cx,
@@ -3976,7 +4032,7 @@ mod tests {
editor
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true));
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().embedded_context(true));
});
let supported_modes = {
@@ -4032,7 +4088,7 @@ mod tests {
editor
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true));
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().embedded_context(true));
});
let supported_modes = {
@@ -4184,7 +4240,10 @@ mod tests {
content,
vec![
"What is in ".into(),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new("main.rs", main_rs_uri))
+ acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
+ "main.rs",
+ main_rs_uri
+ ))
]
);
@@ -4192,7 +4251,7 @@ mod tests {
editor
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true))
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().embedded_context(true))
});
let content = message_editor
@@ -4206,9 +4265,9 @@ mod tests {
content,
vec![
"What is in ".into(),
- acp::ContentBlock::Resource(acp::EmbeddedResource::new(
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents::new(file_content, main_rs_uri)
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource::new(
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents::new(file_content, main_rs_uri)
)
))
]
@@ -4891,27 +4950,26 @@ mod tests {
editor
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().embedded_context(true));
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().embedded_context(true));
editor.draft_content_blocks_snapshot(cx)
});
// Each selection mention must round-trip as a `Resource` block carrying
// its URI and content, not as a `Text` block containing the fold
// placeholder string.
- let resource_uris: Vec<&str> =
- blocks
- .iter()
- .filter_map(|block| match block {
- acp::ContentBlock::Resource(acp::EmbeddedResource {
- resource:
- acp::EmbeddedResourceResource::TextResourceContents(
- acp::TextResourceContents { uri, .. },
- ),
- ..
- }) => Some(uri.as_str()),
- _ => None,
- })
- .collect();
+ let resource_uris: Vec<&str> = blocks
+ .iter()
+ .filter_map(|block| match block {
+ acp_v1::ContentBlock::Resource(acp_v1::EmbeddedResource {
+ resource:
+ acp_v1::EmbeddedResourceResource::TextResourceContents(
+ acp_v1::TextResourceContents { uri, .. },
+ ),
+ ..
+ }) => Some(uri.as_str()),
+ _ => None,
+ })
+ .collect();
assert_eq!(
resource_uris.len(),
2,
@@ -4919,7 +4977,7 @@ mod tests {
);
assert!(resource_uris.contains(&fixture.first_uri.to_uri().to_string().as_str()));
for block in &blocks {
- if let acp::ContentBlock::Text(text) = block {
+ if let acp_v1::ContentBlock::Text(text) = block {
assert!(
!text.text.split_whitespace().any(|word| word == "selection"),
"text block must not contain bare fold placeholder: {:?}",
@@ -5321,7 +5379,7 @@ mod tests {
message_editor
.session_capabilities
.write()
- .set_prompt_capabilities(acp::PromptCapabilities::new().image(true));
+ .set_prompt_capabilities(acp_v1::PromptCapabilities::new().image(true));
});
let temporary_image_path = write_test_png_file(None);
@@ -5559,7 +5617,7 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"hello world".to_string(),
))],
window,
@@ -5572,6 +5630,93 @@ mod tests {
assert!(!message_editor.update(cx, |editor, cx| editor.is_empty(cx)));
}
+ #[gpui::test]
+ async fn test_source_message_known_text_remains_editable(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (message_editor, cx) = setup_message_editor(cx).await;
+
+ message_editor.update_in(cx, |editor, window, cx| {
+ editor.set_source_message(
+ vec![agent_client_protocol::schema::v2::ContentBlock::Text(
+ agent_client_protocol::schema::v2::TextContent::new("original"),
+ )],
+ window,
+ cx,
+ );
+ });
+ let workspace = message_editor.read_with(cx, |editor, _| {
+ editor.workspace.upgrade().expect("message workspace")
+ });
+ workspace.update_in(cx, |workspace, window, cx| {
+ workspace.active_pane().update(cx, |pane, cx| {
+ pane.add_item(
+ Box::new(cx.new(|_| MessageEditorItem(message_editor.clone()))),
+ true,
+ true,
+ None,
+ window,
+ cx,
+ );
+ });
+ });
+ cx.focus(&message_editor);
+ cx.simulate_input("edited");
+ assert!(
+ message_editor
+ .update(cx, |editor, cx| editor.text(cx))
+ .contains("edited")
+ );
+ }
+
+ #[gpui::test]
+ async fn test_source_message_unknown_content_indicated_with_known_text(
+ cx: &mut TestAppContext,
+ ) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ init_test(cx);
+ let (message_editor, cx) = setup_message_editor(cx).await;
+ message_editor.update_in(cx, |editor, window, cx| {
+ editor.set_read_only(true, cx);
+ editor.set_source_message(
+ vec![
+ acp_v2::ContentBlock::Text(acp_v2::TextContent::new("visible text")),
+ acp_v2::ContentBlock::Other(acp_v2::OtherContentBlock::new(
+ "_future",
+ Default::default(),
+ )),
+ ],
+ window,
+ cx,
+ );
+ assert!(editor.text(cx).contains("visible text"));
+ assert!(editor.text(cx).contains("Unsupported message content"));
+ });
+ }
+
+ #[gpui::test]
+ async fn test_source_message_unknown_annotation_indicated_with_text(cx: &mut TestAppContext) {
+ use agent_client_protocol::schema::v2 as acp_v2;
+
+ init_test(cx);
+ let (message_editor, cx) = setup_message_editor(cx).await;
+ message_editor.update_in(cx, |editor, window, cx| {
+ editor.set_read_only(true, cx);
+ editor.set_source_message(
+ vec![acp_v2::ContentBlock::Text(
+ acp_v2::TextContent::new("annotated text").annotations(
+ acp_v2::Annotations::new()
+ .audience(vec![acp_v2::Role::Other("_future".into())]),
+ ),
+ )],
+ window,
+ cx,
+ );
+ assert!(editor.text(cx).contains("annotated text"));
+ assert!(editor.text(cx).contains("Unsupported message content"));
+ });
+ }
+
#[gpui::test]
async fn test_set_message_normalizes_crlf_before_mention(cx: &mut TestAppContext) {
init_test(cx);
@@ -5580,8 +5725,8 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
vec![
- acp::ContentBlock::Text(acp::TextContent::new("before\r\n".to_string())),
- acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
+ acp_v1::ContentBlock::Text(acp_v1::TextContent::new("before\r\n".to_string())),
+ acp_v1::ContentBlock::ResourceLink(acp_v1::ResourceLink::new(
"file.txt",
"file:///project/file.txt",
)),
@@ -5607,7 +5752,7 @@ mod tests {
// Set initial content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"old content".to_string(),
))],
window,
@@ -5618,7 +5763,7 @@ mod tests {
// Replace with new content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"new content".to_string(),
))],
window,
@@ -5640,7 +5785,7 @@ mod tests {
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"appended".to_string(),
))],
Some("\n\n"),
@@ -5664,7 +5809,7 @@ mod tests {
// Seed initial content.
message_editor.update_in(cx, |editor, window, cx| {
editor.set_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"initial".to_string(),
))],
window,
@@ -5675,7 +5820,7 @@ mod tests {
// Append with separator.
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
- vec![acp::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"appended".to_string(),
))],
Some("\n\n"),
@@ -5728,7 +5873,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::ContentBlock::Text(acp::TextContent::new(
+ vec![acp_v1::ContentBlock::Text(acp_v1::TextContent::new(
"prefix text".to_string(),
))],
window,
@@ -5739,10 +5884,9 @@ mod tests {
// Append a message that contains a ResourceLink mention.
message_editor.update_in(cx, |editor, window, cx| {
editor.append_message(
- vec![acp::ContentBlock::ResourceLink(acp::ResourceLink::new(
- "file.txt",
- "file:///project/file.txt",
- ))],
+ vec![acp_v1::ContentBlock::ResourceLink(
+ acp_v1::ResourceLink::new("file.txt", "file:///project/file.txt"),
+ )],
Some("\n\n"),
window,
cx,